Game Development Reference
In-Depth Information
How to do it
Perform the following steps to implement the flee behavior in the game:
1. Open the Player.m file and add the following line of code just after the seek func-
tion:
- (void) flee:(CGPoint )target
deltaTime:(float)deltaTime {
// Work out the direction to this position
GLKVector2 myPosition =
GLKVector2Make(self.position.x, self.position.y);
GLKVector2 targetPosition =
GLKVector2Make(target.x, target.y);
GLKVector2 offset =
GLKVector2Subtract(targetPosition, myPosition);
// Reduce this vector to be the same length as our
movement speed
offset = GLKVector2Normalize(offset);
offset = GLKVector2MultiplyScalar(offset, -10);
[self.physicsBody
applyForce:CGVectorMake(offset.x, offset.y)];
}
2. Now, add the following code in the update function after the seek code:
if (self.behaviourType == Flee) {
[self flee:self.target deltaTime:deltaTime];
}
3. Now, our function is ready to flee the player. This function will accept a target
from which it will flee. So, once again, we will be using the same approach, and
when the user will tap on the screen, we will make the object flee from the tapped
point. The final Player.m file should look something similar to the following
screenshot:
Search WWH ::




Custom Search