Build a Better Health Component

In the Project Navigator, select the HealthComponent.swift file and add two new properties:

 private​ ​var​ hitAction = ​SKAction​()
 private​ ​var​ dieAction = ​SKAction​()

You’ll use these properties to preload the actions needed to handle hits and “deaths” for both the monsters and the player. While you can preload these actions in other ways, you’ll opt for simplicity over versatility.

In the didAddToEntity() method, add the following code below the line that reads updateHealth(0, forNode: componentNode):

 if​ ​let​ _ = componentNode ​as?​ ​Player​ {
  hitAction = ​SKAction​.​playSoundFileNamed​(​"player_hit"​,
  waitForCompletion: ​false​)
 
 let​ playSound = ​SKAction​.​playSoundFileNamed​(​"player_die"​,
  waitForCompletion: ​false​)
  dieAction = ​SKAction​.run {
 self​.componentNode.​run​(playSound, completion: {
 // TODO: Add code to restart the game
 // but for now, reset the player's health
 self​.currentHealth = ​self​.maxHealth
  })
  }
 
 } ​else​ {
  hitAction = ​SKAction​.​playSoundFileNamed​(​"monster_hit"​,
  waitForCompletion: ​false​)
 
 let​ playSound = ​SKAction​.​playSoundFileNamed​(​"monster_die"​,
  waitForCompletion: ​false​)
  dieAction = ​SKAction​.run {
 self​.componentNode.​run​(playSound, completion: {
 self​.componentNode.​removeFromParent​()
  })
  }
 }

This code determines if the attached node is a player or something else—presumably a monster. If the node is a player, you define one set of actions; whereas if it’s something else, such as a monster, you define an entirely different set of actions.

The next step is to run those actions at the appropriate time. In the updateHealth(_:forNode:) method, above the line that reads if let _ = node as? Player {, add the following code:

 // Run hit or die actions
 if​ value < 0 {
 if​ currentHealth == 0 {
  componentNode.​run​(dieAction)
  } ​else​ {
  componentNode.​run​(hitAction)
  }
 }

Because you’re using this method to also set the initial value of the health bar, you need to ensure this call to updateHealth(_:forNode:) is a result of a hit. You do this by making sure the value amount is less than zero. If it is, you then check to see if the monster (or player) is still alive by checking the value in the currentHealth property.

Build and run the project. Notice how the monsters make a sound with every hit; they also disappear when they’re out of health. Val also makes noise when she’s hit, but she never dies (at least not yet—you’ll deal with that in the next chapter).

Your final task for this chapter is to implement pathfinding using navigation graphs. Specifically, you’ll give Val a little challenge by moving the Key collectible along a set path.

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

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