Search code examples
swiftsprite-kitcollision-detection

Player won't detect collision when enemies get close


I've managed to make contact between the bullets and enemies but for some reason the main character won't make contact with the enemies.

    func didBegin(_ contact: SKPhysicsContact) {
    var firstBody:SKPhysicsBody
    var secondBody:SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    }else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if (firstBody.categoryBitMask & Bullet) != 0 && (secondBody.categoryBitMask & Enemy) != 0{

        bulletDidCollideWithEnemy(bulletNode: firstBody.node as! SKSpriteNode, Zombie: secondBody.node as! SKSpriteNode)

    }else{
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }
    if (firstBody.categoryBitMask & Player) != 0 && (secondBody.categoryBitMask & Enemy) != 0{

        playerCollideWithEnemy(playerNode: firstBody.node as! SKSpriteNode, Zombie: secondBody.node as! SKSpriteNode)

        }

}

Solution

  • For anyone who is having this same problem as I did, here is the solution to the problem. I just had to make sure that "Enemy" was visible to other objects. Huge importance! Hope this helps somebody out.

    Enemy.physicsBody?.affectedByGravity = false
    Enemy.physicsBody?.isDynamic = true