Add Code to Destroy Collectibles

Switch back to the Player.swift file, and in the attack() method, above the line that reads var throwDirection = CGVector(dx: 0, dy: 0), add the following code:

 // Set up physics for projectile
 let​ physicsBody = ​SKPhysicsBody​(rectangleOf: projectile.size)
 
 physicsBody.affectedByGravity = ​false
 physicsBody.allowsRotation = ​true
 physicsBody.isDynamic = ​true
 
 physicsBody.categoryBitMask = ​PhysicsBody​.projectile.categoryBitMask
 physicsBody.contactTestBitMask = ​PhysicsBody​.projectile.contactTestBitMask
 physicsBody.collisionBitMask = ​PhysicsBody​.projectile.collisionBitMask
 
 projectile.physicsBody = physicsBody

This sets the projectile’s physics body to use the projectile category.

Next, back in the GameScene+PhysicsContact.swift file, add the code necessary to handle the contacts between the projectile and collectible categories:

 // MARK: - Projectile | Collectible
 
 case​ ​PhysicsBody​.projectile.categoryBitMask |
 PhysicsBody​.collectible.categoryBitMask:
 let​ projectileNode = contact.bodyA.categoryBitMask ==
 PhysicsBody​.projectile.categoryBitMask ?
  contact.bodyA.node : contact.bodyB.node
 
 let​ collectibleNode = contact.bodyA.categoryBitMask ==
 PhysicsBody​.collectible.categoryBitMask ?
  contact.bodyA.node : contact.bodyB.node
 
 if​ ​let​ collectibleComponent =
  collectibleNode?.entity?.​component​(ofType: ​CollectibleComponent​.​self​) {
  collectibleComponent.​destroyedItem​()
  }
  projectileNode?.​removeFromParent​()

Build and run the project. Try shooting the key, the treasure, and the food. Notice you’re able to shoot and destroy only the food.

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

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