I think this is a really basic question and to make it easier to understand what I do not understand, I use the following scenario.
Scenario: I have two or more ships in my game. They should have different attributes like name, hitpoints and score. I want shoot at them and get score points for it.
My approach: I extended SKSpriteNode to get my own ship class
. And when I fire a bullet collision detection will tell me when it hits.
import SpriteKit
class ship: SKSpriteNode {
var hitpoints: Int = nil?
var score: Int = nil?
func createPhysicsBody(){
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
self.physicsBody?.dynamic = true
...
}
}
func didBeginContact(contact: SKPhysicsContact){
switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
case shipCategory + bulletCategory:
contactShipBullet(contact.bodyA, bodyB: contact.bodyB)
break;
default:
break;
}
}
Problem: Swifts collision detection returns physicsBody objects and their parent is the game scene. So I do not know the SKSpriteNode of this physicsBody nor ship's hitpoints (to decrease it by 1) or score.
Thought: At the end I am not sure if my approach is a good one. What should be the best way to give objects on screen attributes and how can I get/change those attributes after a collision is detected by the physics engine?
physicsBody
and add it to SKSpriteNode. Like here in the example I gave. But instead ofself.physicsBody = SKPhysicsBody
I would useself.physicsBody = ship(<some variables>)
. \$\endgroup\$