Chapter 9. Artificial Intelligence and Behavior

Games are often at their best when they’re challenging for players. There are a number of ways to make 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 her.

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.

9.1 Making Vector Math Nicer in Swift

Problem

You have a collection of CGPoint values, and you want to be able to use the +, -, *, and / operators with them. You also want to treat CGPoints like vectors, and get information like their length or a normalized version of that vector.

Solution

Use Swift’s operator overloading feature to add support for working with two CGPoints, and for working with a CGPoint and a scalar (like a CGFloat):

/* Adding points together */
func + (left: CGPoint, right : CGPoint) -> CGPoint {
    return CGPoint(x: left.x + right.x, y: left.y + right.y)
}

func - (left: CGPoint, right : CGPoint) -> CGPoint {
    return CGPoint(x: left.x - right.x, y: left.y - right.y)
}

func += ( left: inout CGPoint, right: CGPoint) {
    left = left + right
}

func -= ( left: inout CGPoint, right: CGPoint) {
    left = left + right
}

/* Working with scalars */

func + (left: CGPoint, right: CGFloat) -> CGPoint {
    return CGPoint(x: left.x + right ...

Get iOS Swift Game Development Cookbook, 3rd Edition 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.