如何知道Swift中哪个SKSpriteNode受到了碰撞检测的影响?

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

情况:我的iOS屏幕上有两艘或更多飞船。两者都有不同的属性,如名称、大小、生命值和得分点。它们显示为SKSpriteNodes并且每一个都添加了一个physicsBody.

目前这些额外的属性是扩展SKSpriteNodeclass.

的变量
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
            ...
        }
    }

在这个 'game' 中,您可以向那些船只射击,一旦子弹击中船只,您就会获得分数。 'Hits a ship' 被碰撞检测到。

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

问题: 碰撞检测只是 returns 一个 physicsBody,我不知道如何通过这个扩展 SKSpriteNode class physicsBody.

思考: 扩展 SKSpriteNode 让我的对象像一艘船一样栩栩如生是正确的方法吗?当我在屏幕上添加一艘船时,它看起来像:

var ship = Ship(ship(hitpoints: 1, score: 100), position: <CGPosition>)
self.addChild(ship)

或者这只是一种错误的方法,还有更好的方法可以通过碰撞检测找出哪个具有某某统计数据的对象被子弹击中?

这个问题与我的另一个问题相似question - 我只是想从更广泛的意义上问这个问题。

SKPhysicsBody 有一个 属性 node,它是与正文关联的 SKNode。您只需要对 Ship class.

执行 conditional cast
    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)!!!")
    }

请注意 Ship 节点可能是与 bodyB 关联的节点。

    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...
    }

希望对您有所帮助。