Game Development Reference
In-Depth Information
How to do it...
To implement automatic cover detection, perform the following steps:
1. There are a few new fields we need to introduce to keep track of things. It's not
enough to simply send one ray from the center to detect the cover, so we'll need to
cast from the edges or near edges of the player model as well. We call this offset
playerWidth
. The
inCover
variable is used to keep track of whether the play-
er is in cover mode or not (toggled). The
hasLowCover
and
hasHighCover
variables are set in the cover-detection method and are a way for us to know
whether the player is currently within limits of a cover (but not necessarily in the
cover mode). The
lowHeight
and
highHeight
variables are the heights where
we'll cast
Ray
from in order to check for cover. The
structures
variable is
everything we should check for cover against. Don't supply
rootNode
here or
we'll end up colliding with ourselves:
private float playerWidth = 0.1f;
private boolean inCover, hasLowCover, hasHighCover;
private float lowHeight = 0.5f, highHeight = 1.5f;
private Node structures;
2. Now let's move to the fun part, which is detecting cover. A new method called
checkCover
needs to be created. It takes
Vector3f
as the input and is the pos-
ition from where the rays originate need to be originated.
3. Next, we define a new
Ray
instance. We don't set the origin yet; we just set the
direction to be the same as the character's
viewDirection
and a maximum
length for it (and this may vary depending on the context and game) as follows:
Ray ray = new Ray();
ray.setDirection(viewDirection);
ray.setLimit(0.8f);
4. We define two integer fields called
lowCollisions
and
highCollisions
to
keep a track of how many collisions we've had.
5. Next, we populate a new field called
leftDir
. This is the direction that is to the
left of the character. We multiply this by
playerWidth
to get the left extreme to
look for cover in, as follows: