Add the Player Agent to the Component System

Switch to the GameScene.swift file and look at the didMove(To:) method. Notice there’s a lot of player-related code stuffed into this method. Let’s tidy up this method by moving the player-related code into its own set-up method.

Below the setupCamera() method, add the following code:

 func​ ​setupPlayer​() {
  player = ​childNode​(withName: ​"player"​) ​as?​ ​Player
 
 if​ ​let​ player = player {
  player.​move​(.stop)
  agentComponentSystem.​addComponent​(player.agent)
  }
 }

Essentially, this is the same code that’s currently in the didMove(to:) method with one exception: you’re adding the player.agent component to the agent component system so that it participates in the update routine.

You’re almost done and ready to test. In the didMove(to:) method, remove the following two lines of code:

 player = ​childNode​(withName: ​"player"​) ​as?​ ​Player
 player?.​move​(.stop)

and replace them with this one-liner instead:

 setupPlayer​()

Excellent, the didMove(to:) method is cleaner, but there’s still one more thing you need to do: get the monster entities to participate in the updates.

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

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