0
votes

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

}
1
look at your else statement in your didBegin, tell me what is wrong - Knight0fDragon
I am also assuming you make the physics bodies inside of your SKS file? you can remove your code from the didMove, none of that is needed (Your sprites already have those names, otherwise you wouldn't be able to assign them those names lol). I also think you have a capitalization error... you have "block" and "Block", swift is case sensitive. - Knight0fDragon

1 Answers

0
votes

you forgot to set contactDelegate to you're GameScene.

 physicsWorld.contactDelegate = self