Add Agents to Monsters

Switch to the GeneratorComponent.swift file. In the spawnMonsterEntity(), add the following code below the line that reads monsterEntity.addComponent(healthComponent):

 let​ agentComponent = ​AgentComponent​()
 monsterEntity.​addComponent​(agentComponent)

While you’re here, also add the physics component not only to the monsters being spawned, but also to the generator itself. By adding the physics component here, you won’t need to worry about adding it to your generators when you add them to the scene using the Scene Editor, saving you an additional step.

Below the code you just added, add the following code:

 let​ physicsComponent = ​PhysicsComponent​()
 physicsComponent.bodyCategory = ​PhysicsCategory​.monster.rawValue
 monsterEntity.​addComponent​(physicsComponent)

Then, inside the didAddToEntity() method, add this code:

 let​ physicsComponent = ​PhysicsComponent​()
 physicsComponent.bodyCategory = ​PhysicsCategory​.monster.rawValue
 componentNode.entity?.​addComponent​(physicsComponent)

Build and run the program, then start the game by moving the player. Notice how all of the monsters are now wandering around. Pretty neat, right? Well, except for the lack of randomness with regard to the spawn location. Let’s make that a little more random.

Still inside the GeneratorComponent.swift file, find the following line (located in the spawnMonsterEntity() method):

 monsterNode.​run​(​SKAction​.​moveBy​(x: 100, y: 0, duration: 1.0))

Remove it and replace it with this code instead:

 // Initial spawn movement
 let​ randomPositions: [​CGFloat​] = [-50,-50,50]
 let​ randomX = randomPositions.​randomElement​() ?? 0
 monsterNode.​run​(​SKAction​.​moveBy​(x: randomX, y: 0, duration: 1.0))

Here, you’re grabbing a random element from the randomPositions array, giving a slight advantage to the -50 value by including that value twice in the array.

Build and run the project again. This time around, watch as the monsters shoot out in different directions—remember, though, you need to touch the scene to start the game.

A game with wandering monsters is certainly more challenging, but a game with monsters that actively hunt the player is even more challenging. However, for that to happen, the player also requires an agent.

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

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