Situation: I have two or more ships on my iOS screen. Both have different attributes like name, size, hitpoints and score points. They are displayed as SKSpriteNodes
and each one has added a physicsBody
.
At the moment those extra attributes are variables of an extended SKSpriteNode
class.
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
...
}
}
In this 'game' you can shoot at those ships and as soon as a bullet hits a ship, you get points. 'Hits a ship' is detected by collision.
func didBeginContact(contact: SKPhysicsContact){
switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
case shipCategory + bulletCategory:
contactShipBullet(contact.bodyA, bodyB: contact.bodyB)
break;
default:
break;
}
}
Problem: Collision detection just returns a physicsBody and I do not know how to get my extended SKSpriteNode
class just by this physicsBody.
Thoughts: Is it a correct way to extend SKSpriteNode
to get my objects like a ship to life? When I add a ship to my screen it looks like:
var ship = Ship(ship(hitpoints: 1, score: 100), position: <CGPosition>)
self.addChild(ship)
Or is this just a wrong approach and there is a much better way to find out which object with stats so and so is hit by a bullet thru collision detection?
This question is similar to my other question - I just want ask this in broader sense.
var ship = bodyA.categoryBitMask == bubbleCategory ? bodyA.node as? Ship : bodyB.node as? Ship
. And this is the correct approach to save game object relevant data like score and hitpoints? I will test solution with several different game objects and as soon as everything works I will mark this as correct answer. – Forfeit