Game Development Reference
In-Depth Information
How to do it...
Perform the following steps to fire non-instant bullets:
1. Let's begin by defining our
Bullet
class. The
worldPosition
and
direc-
tion
variables are used by the
Ray
class as a starting position each step it takes.
The
RANGE
field is a static field that defines the maximum range, inside which the
bullet will be effective. The
distance
variable is the distance the bullet has
traveled since it was instanced. It also needs to keep track of whether it's alive or
not, for cleanup reasons. It should be said that this particular bullet is rather slow
and short lived.
private Vector3f worldPosition;
private Vector3f direction;
private float speed = 10;
private Ray ray;
private final static int RANGE = 10;
private float distance;
private boolean alive = true;
2. To avoid unnecessary object creation, we instance
Ray
in the constructor as fol-
lows, which we'll reuse throughout the lifespan of the bullet:
ray = new Ray(origin, direction);
ray.setOrigin(worldPosition);
3. It's in the
update
method that most of the work is done. At the beginning, we set
the ray's origin to be the current position of the bullet. The direction will stay the
same, so no need to change that. We do, however, need to set limit factorized by
the time passed for the update (
tpf
). The limit is also the distance the bullet has
traveled since the last update, so we use this to update the current position of the
bullet:
ray.setLimit (speed * tpf);
distance += ray.limit;
worldPosition.addLocal(direction.mult(ray.limit));
4. If the total distance is longer than the range, the bullet can be considered beyond its
effective range. We set
alive
to
false
as follows so that it can be removed: