How to get SKSpriteNode by physicsBody?

梦想与她 提交于 2019-12-19 11:35:44

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31772869/how-to-get-skspritenode-by-physicsbody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!