Jurik Jurik - 2 months ago 11
iOS Question

How to know which SKSpriteNode is affected by collision detection in Swift?

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.

Answer

The SKPhysicsBody has a property node which is the SKNode associated to the body. You just need to perform a conditional cast to your Ship class.

    if let ship = contact.bodyA.node as? Ship {
        // here you have your ship object of type Ship
        print("Score of this ship is: \(ship.score)!!!")
    }

Please note that the Ship node could be the one associated with bodyB so.

    if let ship = contact.bodyA.node as? Ship {
        // here you have your ship...
    } else if let ship = contact.bodyB.node as? Ship {
        // here you have your ship...
    }

Hope this helps.