使用Spritekit进行碰撞检测无效

时间:2018-07-27 06:36:35

标签: ios swift sprite-kit gamekit

使用SKPhysicsContactDelegate无法检测到碰撞。在控制台中,当对象碰撞时,没有任何打印内容。

我在游戏场景中有两个spritenodes

有解决方案吗?

非常感谢

class GameScene: SKScene,SKPhysicsContactDelegate {


    var player :SKSpriteNode?
    var block :SKSpriteNode?


    override func didMove(to view: SKView) {
        player = self.childNode(withName: "Player") as? SKSpriteNode
        player?.name = "Player"

        block = self.childNode(withName: "block") as? SKSpriteNode
        block?.name = "Block"

        }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {

            let location = touch.location(in: self)
            player?.position.x = location.x
            player?.position.y = location.y
        }
    }
    func didBegin(_ contact: SKPhysicsContact) {
        var firstbody = SKPhysicsBody()
        var secondbody = SKPhysicsBody()

        if contact.bodyA.node?.name == "Player"
        {
            firstbody = contact.bodyA
            secondbody = contact.bodyB

        }else {
            firstbody = contact.bodyB
            secondbody = contact.bodyB

        }
        if firstbody.node?.name == "Player" && secondbody.node?.name == "Block"
        {
            print("Collosion detected")
        }
    }

}

1 个答案:

答案 0 :(得分:0)

您忘记将contactDelegate设置为GameScene。

 physicsWorld.contactDelegate = self