Add Code to Destroy Collectibles
Apple Game Frameworks and Technologies — by Tammy Coron (119 / 193)
Published in
2 min readSep 29, 2021
👈 Place Collectibles and Doors | TOC | Next Steps 👉
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 ==
…