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

1

5

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.

Forfeit answered 4/8, 2015 at 14:31 Comment(0)
W
8

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.

Weatherman answered 10/8, 2015 at 14:30 Comment(1)
Finally someone gave me the right solution - thank you alot. I am using now this line 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

© 2022 - 2024 — McMap. All rights reserved.