## 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 `CGPoint`s 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` `+=` `(``inout` `left``:` `CGPoint``,` `right``:` `CGPoint``)` `{`
`left` `=` `left` `+` `right`
`}`

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

`/* Working with scalars */`

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

Get iOS Swift Game Development Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.