How to get SKSpriteNode by physicsBody?
Asked Answered
G

1

1

I extended SKSpriteNode with my own class to have more functions.

But how can I get this extended node when something 'hits' this node and didBeginContact is called?

Because contact.bodyA and contact.bodyB are physicsBody and parent of this is the game scene.

This is my subclass of SKSpriteNode:

class Orange: SKSpriteNode {
    ...

    func createPhysicsBody(){
        self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2)
        self.physicsBody?.dynamic = true
        ...
    }
}

This is my didBeginContact code:

func didBeginContact(contact: SKPhysicsContact){    
    switch(contact.bodyA.categoryBitMask + contact.bodyB.categoryBitMask){
        case orangeCategory + bulletCategory:
            contactOrangeBullet(contact.bodyA, bodyB: contact.bodyB)
            break;
        default:
            break;
    }
}

In contactOrangeBullet is just code that handles everything when this case happens. But I need more than physicsBody. I need the 'Orange' which physicsBody is just a part of.

Or do I understand something wrong and this is not possible because physicsBody does not stick to 'Orange' although it was created in there?

Glucosuria answered 2/8, 2015 at 14:27 Comment(0)
E
2

So, here is an example of how you can get the node associated with the physics body.

var node = SKSpriteNode(imageNamed: "theimage")

node.physicsBody = SKPhysicsBody(circleOfRadius: 6)

var copy = node.physicsBody

Now, I will get the SKNode associated with copy

var node = copy.node

So, all you have to do is call the property node on the physicsBody. Remember that the node property returns an SKNode, not SKSpriteNode.

Eyewash answered 2/8, 2015 at 15:3 Comment(2)
Yes, that's what I am using at the moment. But this SKNode doesn't know anything about my Orange class functions and attributes.Glucosuria
I do it that way now: #31812608Glucosuria

© 2022 - 2024 — McMap. All rights reserved.