Add an Agent to the Player

Rather than use the same agent component for the player that you’re using for the monsters, you’ll add an agent property directly to the Player class.

Switch to Player.swift file and add a new property, placing it directly above the currentDirection property:

 var​ agent = ​GKAgent2D​()

Next, inside the init(coder:) method, and at the end of that method, set the delegate for your new agent:

 agent.delegate = ​self

Because you created an SKNode extension to handle the agent delegate methods, you’re able to set the Player class as the delegate without having to add those methods here. Remember, the Player class is a subclass of the SKSpriteNode class, which, itself, is a subclass of the SKNode class.

All right, switch back to the AgentComponent.swift file and add a new lazy property:

 lazy​ ​var​ interceptGoal: ​GKGoal​ = {
 guard​ ​let​ scene = componentNode.scene ​as?​ ​GameScene​,
 let​ player = scene.​childNode​(withName: ​"player"​) ​as?​ ​Player​ ​else​ {
 return​ ​GKGoal​(toWander: 1.0)
  }
 
 return​ ​GKGoal​(toInterceptAgent: player.agent, maxPredictionTime: 1.0)
 }()

Here, you’re getting the player node (and subsequently its agent) from the scene. You’re then creating and returning a GKGoal object designed to intercept another agent; in this case, the player’s agent. If for some reason the player object is nil, you return a simple wander goal instead.

Now it’s time to add this new goal to the monster’s agent behavior.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.204.216