O'Reilly logo

iOS Swift Game Development Cookbook, 3rd Edition by Paris Buttfield-Addison, Jonathon Manning

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required