Game Development Reference
In-Depth Information
How to do it...
We will start by creating the AIState class. This will have two steps, as follows:
1. We add a field to store AIControl and give it two abstract methods called
stateEnter and stateExit .
2. These should be triggered when enabling and disabling the class, respectively. We
override setEnabled to achieve this, as shown in the following code:
public void setEnabled(boolean enabled) {
if(enabled && !this.enabled){
stateEnter();
}else if(!enabled && this.enabled){
stateExit();
}
this.enabled = enabled;
}
With AIState done, we can look at the first behavior, PatrolState . We can imple-
ment this by performing the following steps:
1. First of all we add a Vector3f field called moveTarget . This is the position it
will try to reach, relative to the current position.
2. We add an if statement with three outcomes in the controlUpdate method,
which is the main bulk of the logic in the class. The first clause should disable it
and enable the AttackState if AIControl has found a suitable target using
the following code:
if(aiControl.getTarget() != null){
this.setEnabled(false);
Vector3f direction =
aiControl.getTarget().getWorldTranslation().subtract(spatial.getWorldTranslation());
this.spatial.getControl(BetterCharacterControl.class).setViewDirection(direction);
this.spatial.getControl(AttackState.class).setEnabled(true);
}
Search WWH ::




Custom Search