简体   繁体   中英

Collision detection not working using spritekit

I am unable to detect collision with using SKPhysicsContactDelegate. In the console nothing is printing when the objects collide.

I have two spritenodes in gamescene

Any solution?

Thanks very much

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")
        }
    }

}

您忘记将contactDelegate设置为GameScene。

 physicsWorld.contactDelegate = self

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM