Game Development Reference
In-Depth Information
How to do it...
We will start by defining a class that all objects emitting sounds will use. This will require
the following steps to be performed:
1. We create a class called
SoundEmitterControl
, extending
AbstractCon-
trol
.
2. It needs three fields, a
Vector3f
called
lastPosition
, a float for
noiseEmitted
, and another float called
maxSpeed
.
3. In the
controlUpdate
method, we sample the velocity the spatial has. This is
the distance between the current
worldTranslation
and
lastPosition
.
Divided by
tpf
(time-per-frame) we get the distance per second, as shown in the
following code:
float movementSpeed =
lastPosition.distance(spatial.getWorldTranslation()) /
tpf;
4. If it's actually moving, we see how much it moves compared to
maxSpeed
.
Normalized between 0 and 1, this value becomes
noiseEmitted
, as shown in
the following code:
movementSpeed = Math.min(movementSpeed, maxSpeed);
noiseEmitted = movementSpeed / maxSpeed;
5. Finally, we set
lastPosition
to current
worldTranslation
. Now we will
implement the changes to detect sound in
AIControl
. This will have five steps.
We start by defining a float called
hearingRange
. In the
sense()
method, we
parse the list of
targetableObjects
and see if they have
SoundEmitter-
Control
. If any does, we check the distance between it and the AI using the fol-
lowing code:
float distance =
s.getWorldTranslation().distance(spatial.getWorldTranslation());
6. We get the
noiseEmitted
value from
SoundEmitterControl
and see how
much is picked up by the AI, as shown in the following code: