Chapter 11. Artificial Intelligence and Behavior

Games are often at their best when they’re a challenge to the player. There are a number of ways for making your game challenging, including creating complex puzzles; however, one of the most satisfying challenges that a player can enjoy is defeating something that’s trying to outthink or outmaneuver them.

In this chapter, you’ll learn how to create movement behavior, how to pursue and flee from targets, how to find the shortest path between two locations, and how to design an AI system that thinks ahead.

Making an Object Move Toward a Position

Problem

You want an object to move toward another object.

Solution

Subtract the target position from the object’s current position, normalize the result, and then multiply it by the speed at which you want to move toward the target. Then, add the result to the current position:

// Determine the direction to this position
GLKVector2 myPosition = ... // the location where we are right now
GLKVector2 targetPosition = ... // the location where we want to be
float movementSpeed = ... // how fast we want to move toward this target

GLKVector2 offset = GLKVector2Subtract(targetPosition, myPosition);

// Reduce this vector to be the same length as our movement speed
offset = GLKVector2Normalize(offset);
offset = GLKVector2MultiplyScalar(offset, self.movementSpeed * deltaTime);

// Add this to our current position
GLKVector2 newPosition = self.position;
newPosition.x += offset.x;
newPosition.y += offset.y;

Get iOS Game Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.