Chapter 12. Artificial Intelligence and Behavior
Games are often at their best when they’re a challenge to the player. 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.
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{returnCGPoint(x:left.x+right.x,y:left.y+right.y)}func-(left:CGPoint,right:CGPoint)->CGPoint{returnCGPoint(x:left.x-right.x,y:left.y-right.y)}func+=(inoutleft:CGPoint,right:CGPoint){left=left+right}func-=(inoutleft:CGPoint,right:CGPoint){left=left+right}/* Working with scalars */func+(left:CGPoint,right:CGFloat)->CGPoint{returnCGPoint(x:left.x+right,y:left.y+
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access