# An Introduction to GameplayKit: Part 2

Read Time: 14 min
This post is part of a series called An Introduction to GameplayKit.
An Introduction to GameplayKit: Part 1
An Introduction to GameplayKit: Part 3

This is the second part of An Introduction to GameplayKit. If you haven't yet gone through the first part, then I recommend reading that tutorial first before continuing with this one.

## Introduction

In this tutorial, I am going to teach you about two more features of the GameplayKit framework you can take advantage of:

• agents, goals, and behaviors
• pathfinding

By utilizing agents, goals, and behaviors, we are going to build in some basic artificial intelligence (AI) into the game that we started in the first part of this series. The AI will enable our red and yellow enemy dots to target and move towards our blue player dot. We are also going to implement pathfinding to extend on this AI to navigate around obstacles.

For this tutorial, you can use your copy of the completed project from the first part of this series or download a fresh copy of the source code from GitHub.

## 1. Agents, Goals, and Behaviors

In GameplayKit, agents, goals and behaviors are used in combination with each other to define how different objects move in relation to each other throughout your scene. For a single object (or SKShapeNode in our game), you begin by creating an agent, represented by the GKAgent class. However, for 2D games, like ours, we need to use the concrete GKAgent2D class.

The GKAgent class is a subclass of GKComponent. This means that your game needs to be using an entity- and component-based structure as I showed you in the first tutorial of this series.

Agents represent an object's position, size, and velocity. You then add a behavior, represented by the GKBehaviour class, to this agent. Finally, you create a set of goals, represented by the GKGoal class, and add them to the behavior object. Goals can be used to create many different gameplay elements, for example:

• moving towards an agent
• moving away from an agent
• grouping close together with other agents
• wandering around a specific position

Your behavior object monitors and calculates all of the goals that you add to it and then relays this data back to the agent. Let's see how this works in practice.

Open your Xcode project and navigate to PlayerNode.swift. We first need to make sure the PlayerNode class conforms to the GKAgentDelegate protocol.

 1 class PlayerNode: SKShapeNode, GKAgentDelegate {  2 ... 

Next, add the following code block to the PlayerNode class.

 1 var agent = GKAgent2D()  2 3 // MARK: Agent Delegate  4 func agentWillUpdate(agent: GKAgent) {  5  if let agent2D = agent as? GKAgent2D {  6  agent2D.position = float2(Float(position.x), Float(position.y))  7  }  8 }  9 10 func agentDidUpdate(agent: GKAgent) {  11  if let agent2D = agent as? GKAgent2D {  12  self.position = CGPoint(x: CGFloat(agent2D.position.x), y: CGFloat(agent2D.position.y))  13  }  14 } 

We start by adding a property to the PlayerNode class so that we always have a reference to the current player's agent object. Next, we implement the two methods of the GKAgentDelegate protocol. By implementing these methods, we ensure that the player dot displayed on screen will always mirror the changes that GameplayKit makes.

The agentWillUpdate(_:) method is called just before GameplayKit looks through the behavior and goals of that agent to determine where it should move. Likewise, the agentDidUpdate(_:) method is called straight after GameplayKit has completed this process.

Our implementation of these two methods ensures that the node we see on screen reflects the changes GameplayKit makes and that GameplayKit uses the last position of the node when performing its calculations.

Next, open ContactNode.swift and replace the file's contents with the following implementation:

 1 import UIKit  2 import SpriteKit  3 import GameplayKit  4 5 class ContactNode: SKShapeNode, GKAgentDelegate {  6   7  var agent = GKAgent2D()  8   9  // MARK: Agent Delegate  10  func agentWillUpdate(agent: GKAgent) {  11  if let agent2D = agent as? GKAgent2D {  12  agent2D.position = float2(Float(position.x), Float(position.y))  13  }  14  }  15   16  func agentDidUpdate(agent: GKAgent) {  17  if let agent2D = agent as? GKAgent2D {  18  self.position = CGPoint(x: CGFloat(agent2D.position.x), y: CGFloat(agent2D.position.y))  19  }  20  }  21 } 

By implementing the GKAgentDelegate protocol in the ContactNode class, we allow for all of the other dots in our game to be up to date with GameplayKit as well as our player dot.

It's now time to set up the behaviors and goals. To make this work, we need to take care of three things:

• Add the player node's agent to its entity and set its delegate.
• Configure agents, behaviors, and goals for all of our enemy dots.
• Update all of these agents at the correct time.

Firstly, open GameScene.swift and, at the end of the didMoveToView(_:) method, add the following two lines of code:

 1 playerNode.entity.addComponent(playerNode.agent)  2 playerNode.agent.delegate = playerNode 

With these two lines of code, we add the agent as a component and set the agent's delegate to be the node itself.

Next, replace the implementation of the initialSpawn method with the following implementation:

 1 func initialSpawn() {  2  for point in self.spawnPoints {  3  let respawnFactor = arc4random() % 3 // Will produce a value between 0 and 2 (inclusive)  4   5  var node: SKShapeNode? = nil  6   7  switch respawnFactor {  8  case 0:  9  node = PointsNode(circleOfRadius: 25)  10  node!.physicsBody = SKPhysicsBody(circleOfRadius: 25)  11  node!.fillColor = UIColor.greenColor()  12  case 1:  13  node = RedEnemyNode(circleOfRadius: 75)  14  node!.physicsBody = SKPhysicsBody(circleOfRadius: 75)  15  node!.fillColor = UIColor.redColor()  16  case 2:  17  node = YellowEnemyNode(circleOfRadius: 50)  18  node!.physicsBody = SKPhysicsBody(circleOfRadius: 50)  19  node!.fillColor = UIColor.yellowColor()  20  default:  21  break  22  }  23   24  if let entity = node?.valueForKey("entity") as? GKEntity,  25  let agent = node?.valueForKey("agent") as? GKAgent2D where respawnFactor != 0 {  26 27  entity.addComponent(agent)  28  agent.delegate = node as? ContactNode  29  agent.position = float2(x: Float(point.x), y: Float(point.y))  30  agents.append(agent)  31   32  let behavior = GKBehavior(goal: GKGoal(toSeekAgent: playerNode.agent), weight: 1.0)  33  agent.behavior = behavior  34   35  agent.mass = 0.01  36  agent.maxSpeed = 50  37  agent.maxAcceleration = 1000  38  }  39   40  node!.position = point  41  node!.strokeColor = UIColor.clearColor()  42  node!.physicsBody!.contactTestBitMask = 1  43  self.addChild(node!)  44  }  45 } 

The most important code that we've added is located in the if statement that follows the switch statement. Let's go through this code line by line:

• We first add the agent to the entity as a component and configure its delegate.
• Next, we assign the agent's position and add the agent to a stored array, agents. We'll add this property to the GameScene class in a moment.
• We then create a GKBehavior object with a single GKGoal to target the current player's agent. The weight parameter in this initializer is used to determine which goals should take precedence over others. For example, imagine that you have a goal to target a particular agent and a goal to move away from another agent, but you want the targeting goal to take preference. In this case, you could give the targeting goal a weight of 1 and the moving away goal a weight of 0.5. This behavior is then assigned to the enemy node's agent.
• Lastly, we configure the massmaxSpeed, and maxAcceleration properties of the agent. These affect how fast the objects can move and turn. Feel free to play around with these values and see how it affects the movement of the enemy dots.

Next, add the following two properties to the GameScene class:

 1 var agents: [GKAgent2D] = []  2 var lastUpdateTime: CFTimeInterval = 0.0 

The agents array will be used to keep a reference to the enemy agents in the scene. The lastUpdateTime property will be used to calculate the time that has passed since the scene was last updated.

Finally, replace the implementation of the update(_:) method of the GameScene class with the following implementation:

 1 override func update(currentTime: CFTimeInterval) {  2  /* Called before each frame is rendered */  3  self.camera?.position = playerNode.position  4   5  if self.lastUpdateTime == 0 {  6  lastUpdateTime = currentTime  7  }  8   9  let delta = currentTime - lastUpdateTime  10  lastUpdateTime = currentTime  11   12  playerNode.agent.updateWithDeltaTime(delta)  13   14  for agent in agents {  15  agent.updateWithDeltaTime(delta)  16  }  17 } 

In the update(_:) method, we calculate the time that has passed since the last scene update and then update the agents with that value.

Build and run your app, and begin moving around the scene. You will see that the enemy dots will slowly begin moving towards you.

As you can see, while the enemy dots do target the current player, they do not navigate around the white barriers, instead they try to move through them. Let's make the enemies a bit smarter with pathfinding.

## 2. Pathfinding

With the GameplayKit framework, you can add complex pathfinding to your game by combining physics bodies with GameplayKit classes and methods. For our game, we are going to set it up so that the enemy dots will target the player dot and at the same time navigate around obstacles.

Pathfinding in GameplayKit begins with creating a graph of your scene. This graph is a collection of individual locations, also referred to as nodes, and connections between these locations. These connections define how a particular object can move from one location to another. A graph can model the available paths in your scene in one of three ways:

• A continuous space containing obstacles: This graph model allows for smooth paths around obstacles from one location to another. For this model, the GKObstacleGraph class is used for the graph, the GKPolygonObstacle class for obstacles, and the GKGraphNode2D class for nodes (locations).
• A simple 2D grid: In this case, valid locations can only be those with integer coordinates. This graph model is useful when your scene has a distinct grid layout and you do not need smooth paths. When using this model, objects can only move horizontally or vertically in a single direction at any one time. For this model, the GKGridGraph class is used for the graph and the GKGridGraphNode class for nodes.
• A collection of locations and the connections between them: This is the most generic graph model and is recommended for cases where objects move between distinct spaces, but their specific location within that space is not essential to the gameplay. For this model, the GKGraph class is used for the graph and the GKGraphNode class for nodes.

Because we want the player dot in our game to navigate around the white barriers, we are going to use the GKObstacleGraph class to create a graph of our scene. To begin, replace the spawnPoints property in the GameScene class with the following:

 1 let spawnPoints = [  2  CGPoint(x: 245, y: 3900),  3  CGPoint(x: 700, y: 3500),  4  CGPoint(x: 1250, y: 1500),  5  CGPoint(x: 1200, y: 1950),  6  CGPoint(x: 1200, y: 2450),  7  CGPoint(x: 1200, y: 2950),  8  CGPoint(x: 1200, y: 3400),  9  CGPoint(x: 2550, y: 2350),  10  CGPoint(x: 2500, y: 3100),  11  CGPoint(x: 3000, y: 2400),  12  CGPoint(x: 2048, y: 2400),  13  CGPoint(x: 2200, y: 2200)  14  ]  15 var graph: GKObstacleGraph! 

The spawnPoints array contains some altered spawn locations for the purposes of this tutorial. This is because currently GameplayKit can only calculate paths between objects that are relatively close to each other.

Due to the large default distance between dots in this game, a couple of new spawn points must be added to illustrate pathfinding. Note that we also declare a graph property of type GKObstacleGraph to keep a reference to the graph we will create.

Next, add the following two lines of code at the start of the didMoveToView(_:) method:

 1 let obstacles = SKNode.obstaclesFromNodePhysicsBodies(self.children)  2 graph = GKObstacleGraph(obstacles: obstacles, bufferRadius: 0.0) 

In the first line, we create an array of obstacles from the physics bodies in the scene. We then create the graph object using these obstacles. The bufferRadius parameter in this initializer can be used to force objects to not come within a certain distance of these obstacles. These lines need to be added at the start of the didMoveToView(_:) method, because the graph we create is needed by the time the initialSpawn method is called.

Finally, replace the initialSpawn method with the following implementation:

 1 func initialSpawn() {  2  let endNode = GKGraphNode2D(point: float2(x: 2048.0, y: 2048.0))  3  self.graph.connectNodeUsingObstacles(endNode)  4   5  for point in self.spawnPoints {  6  let respawnFactor = arc4random() % 3 // Will produce a value between 0 and 2 (inclusive)  7   8  var node: SKShapeNode? = nil  9   10  switch respawnFactor {  11  case 0:  12  node = PointsNode(circleOfRadius: 25)  13  node!.physicsBody = SKPhysicsBody(circleOfRadius: 25)  14  node!.fillColor = UIColor.greenColor()  15  case 1:  16  node = RedEnemyNode(circleOfRadius: 75)  17  node!.physicsBody = SKPhysicsBody(circleOfRadius: 75)  18  node!.fillColor = UIColor.redColor()  19  case 2:  20  node = YellowEnemyNode(circleOfRadius: 50)  21  node!.physicsBody = SKPhysicsBody(circleOfRadius: 50)  22  node!.fillColor = UIColor.yellowColor()  23  default:  24  break  25  }  26   27  if let entity = node?.valueForKey("entity") as? GKEntity,  28  let agent = node?.valueForKey("agent") as? GKAgent2D where respawnFactor != 0 {  29   30  entity.addComponent(agent)  31  agent.delegate = node as? ContactNode  32  agent.position = float2(x: Float(point.x), y: Float(point.y))  33  agents.append(agent)  34   35  /*let behavior = GKBehavior(goal: GKGoal(toSeekAgent: playerNode.agent), weight: 1.0)  36  agent.behavior = behavior*/  37   38  /*** BEGIN PATHFINDING ***/  39  let startNode = GKGraphNode2D(point: agent.position)  40  self.graph.connectNodeUsingObstacles(startNode)  41   42  let pathNodes = self.graph.findPathFromNode(startNode, toNode: endNode) as! [GKGraphNode2D]  43   44  if !pathNodes.isEmpty {  45  let path = GKPath(graphNodes: pathNodes, radius: 1.0)  46   47  let followPath = GKGoal(toFollowPath: path, maxPredictionTime: 1.0, forward: true)  48  let stayOnPath = GKGoal(toStayOnPath: path, maxPredictionTime: 1.0)  49   50  let behavior = GKBehavior(goals: [followPath, stayOnPath])  51  agent.behavior = behavior  52  }  53   54  self.graph.removeNodes([startNode])  55  /*** END PATHFINDING ***/  56   57  agent.mass = 0.01  58  agent.maxSpeed = 50  59  agent.maxAcceleration = 1000  60  }  61   62  node!.position = point  63  node!.strokeColor = UIColor.clearColor()  64  node!.physicsBody!.contactTestBitMask = 1  65  self.addChild(node!)  66  }  67   68  self.graph.removeNodes([endNode])  69 } 

We begin the method by creating a GKGraphNode2D object with the default player spawn coordinates. Next, we connect this node to the graph so that it can be used when finding paths.

Most of the initialSpawn method remains unchanged. I have added some comments to show you where the pathfinding portion of the code is located in the first if statement. Let's go through this code step by step:

• We create another GKGraphNode2D instance and connect this to the graph.
• We create a series of nodes which make up a path by calling the findPathFromNode(_:toNode:) method on our graph.
• If a series of path nodes has been created successfully, we then create a path from them. The radius parameter works similar to the bufferRadius parameter from before and defines how much an object can move away from the created path.
• We create two GKGoal objects, one for following the path and another for staying on the path. The maxPredictionTime parameter allows for the goal to calculate as best it can ahead of time whether anything is going to interrupt the object from following/staying on that particular path.
• Lastly, we create a new behavior with these two goals and assign this to the agent.

You will also notice that we remove the nodes we create from the graph once we are finished with them. This is a good practice to follow as it ensures that the nodes you have created do not interfere with any other pathfinding calculations later on.

Build and run your app one last time, and you will see two dots spawn very close to you and begin moving towards you. You may have to run the game multiple times if they both spawn as green dots.

Important!

In this tutorial, we used GameplayKit's pathfinding feature to enable enemy dots to target the player dot around obstacles. Note that this was just for a practical example of pathfinding.

For an actual production game, it would be best to implement this functionality by combining the player targeting goal from earlier in this tutorial with an obstacle-avoiding goal created with the init(toAvoidObstacles:maxPredictionTime:) convenience method, which you can read more about in the GKGoal Class Reference.

## Conclusion

In this tutorial, I showed you how you can utilize agents, goals, and behaviors in games that have an entity-component structure. While we only created three goals in this tutorial, there are many more available to you, which you can read more about in the GKGoal Class Reference.

I also showed you how to implement some advanced pathfinding in your game by creating a graph, a set of obstacles, and goals to follow these paths.

As you can see, there is a vast amount of functionality made available to you through the GameplayKit framework. In the third and final part of this series, I will teach you about GameplayKit's random value generators and how to create your own rule system to introduce some fuzzy logic into your game.

As always, please be sure to leave your comments and feedback below.