Game Development Reference
In-Depth Information
How to do it
Now we will implement the wander behavior and will take our project a little more further.
Perform the following steps to implement the wander behavior:
1. Open the Player.m file and add the following line of code in the end of the file:
int myRandom() {
return (arc4random() % 2 ? 1 : -1);
}
- (void)wanderWithDeltaTime:(float)deltaTime
{
int boxWidth = 20;
CGRect targetRect = CGRectMake(self.target.x -
boxWidth, self.target.y - boxWidth, boxWidth*2,
boxWidth*2);
if (!CGRectContainsPoint(targetRect,
self.position)) {
[self seek:self.target deltaTime:deltaTime];
} else {
int offsetX = self.scene.size.width;
int offsetY = self.scene.size.height;
self.target = CGPointMake(arc4random() %
offsetX, arc4random() % offsetY);
}
}
We have implemented the algorithm that we have seen in the start of this section.
In this code, we are getting a random local point in front of the player, and then
make the player to seek that location. This will make a wander behavior.
2. Now, add the following line of code in the update method:
Search WWH ::




Custom Search