Game Development Reference
In-Depth Information
How to do it...
We need to perform the following steps to get a basic, but functional attacking (or follow-
ing) AI:
1. We begin by creating a new class called AIControl , extending Ab-
stractControl . The core of the recipe will be based around an enum (enumer-
ation) called state . For now it only needs two values: Idle and Follow .
2. Add fields for BetterCharacterControl , called physicsCharacter ,
Booleans forward and backwards , a Vector3f field for walkDirection ,
and another for viewDirection . If it's going to follow something, it also needs
a target field, which can be Spatial .
3. The bulk of the logic is carried out in a switch statement in the controlUp-
date method, as shown in the following code. The first case is Idle . In this case,
the AI shouldn't do anything:
switch(state){
case Idle:
forward = false;
backward = false;
break;
4. In the Follow case, we should first check whether target is set. If there is a
target, we find the direction to the target and make the AI face it by setting
viewDirection , as shown in the following code:
case Follow:
if(target != null){
Vector3f dirToTarget =
target.getWorldTranslation().subtract(spatial.getWorldTranslation());
dirToTarget.y = 0;
dirToTarget.normalizeLocal();
viewDirection.set(dirToTarget);
5. We check the distance to the target. If it's more than 5 the AI will try to get closer.
If the distance instead is less than 3 , it will try to back up a bit. The AI can also
lose track of the target if it is more than 20 units away. In this case, it also changes
state to Idle , as shown in the following code:
Search WWH ::




Custom Search