Game Development Reference
In-Depth Information
How to do it...
We'll start by defining a GatherResourceState class. It extends the same AIState
we defined in the Decision making - Finite State Machine recipe. This will be implemen-
ted by performing the following steps:
1. First of all it needs access to the AIControl called aiControl .
2. It needs two additional fields, a Spatial defining something to pick up called
resource , and an integer called amountCarried .
3. In controlUpdate method, we define two branches. The first is for if the unit
isn't carrying anything, amountCarried == 0 . In this case, the unit should
move towards resource . Once it gets close enough, it should pick up some, and
amountCarried should be increased, as shown in the following code:
Vector3f direction =
resource.getWorldTranslation().subtract(this.spatial.getWorldTranslation());
if(direction.length() > 1f){
direction.normalizeLocal();
aiControl.move(direction, true);
} else {
amountCarried = 10;
}
4. In the other case, amountCarried is more than 0 . Now, the unit should move
towards the HQ instead. Once it's close enough, finishTask() is called.
5. The finishTask method calls the AI Manager via aiControl to increase the
resource amount that the state handles with the supplied amount as follows:
aiControl.getAiManager().onFinishTask(this.getClass(),
amountCarried);
amountCarried = 0;
6. Finally, we create two new classes that extend this class, namely Gather-
FoodState and GatherWoodState .
With the new state handled, we can focus on the AIControl class. It will follow the pat-
tern established elsewhere in the chapter, but it needs some new functionality. This will be
implemented by performing the following three steps:
Search WWH ::




Custom Search