Game Development Reference
In-Depth Information
How to do it...
To get our AI to sense something, we need to modify the AIControl class from the pre-
vious recipe by performing the following steps:
1. We need to define some values, a float called sightRange , for how far the AI
can see, and an angle representing the field of view (to one side) in radians.
2. With this done, we create a sense() method. Inside we define a Quaternion
called aimDirection that will be the ray direction relative to the AI's
viewDirection field.
3. We convert the angle to a Quaternion and multiply it with viewDirection to
get the direction of the ray, as shown in the following code:
rayDirection.set(viewDirection);
aimDirection.fromAngleAxis(angleX, Vector3f.UNIT_Y);
aimDirection.multLocal(rayDirection);
4. We check whether the ray collides with any of the objects in our target-
ableObjects list using the following code:
CollisionResults col = new CollisionResults();
for(Spatial s: targetableObjects){
s.collideWith(ray, col);
}
5. If this happens, we set the target to be this object and exit the sensing loop, as
shown in the following code. Otherwise, it should continue searching for it:
if(col.size() > 0){
target = col.getClosestCollision().getGeometry();
foundTarget = true;
break;
}
6. If the sense method returns true, the AI now has a target, and should switch to the
Follow state. We add a check for this in the controlUpdate method and the
Idle case, as shown in the following code:
case Idle:
if(!targetableObjects.isEmpty() && sense()){
Search WWH ::




Custom Search