8

I have two nodes, and I want to detect a collision between them, but for some reason

func didBegin(_ contact: SKPhysicsContact) {

is not being called.

It is a ball and a paddle:

ball.physicsBody?.categoryBitMask = 2
ball.physicsBody?.contactTestBitMask = 2        
ball.physicsBody?.isDynamic = true

main.physicsBody?.categoryBitMask = 1
main.physicsBody?.contactTestBitMask = 1
main.physicsBody?.isDynamic = false

_

func didBegin(_ contact: SKPhysicsContact) {
        print("Collision") //Obviously this will be better in future, but I need to detect collision for a start
}

When the ball moves around, it DOES bounce off the paddle, but I need to be able to detect that.

Thanks

Will
  • 81
  • 2
  • Check out how they do it at [Ray Wenderlich's](https://www.raywenderlich.com/1161-how-to-make-a-breakout-game-with-spritekit-and-swift-part-1) – bobobobo Mar 12 '21 at 17:29

2 Answers2

4

check these things:

Make sure you set the physics world contact delegate to itself class GameScene: SKScene, SKPhysicsContactDelegate{

override func didMove(to view: SKView) {
    physicsWorld.contactDelegate = self
    self.backgroundColor = .white
    }

if you had specified a physics body eg:

box.physicsBody = SKPhysicsBody(rectangleOf: CGSize)

make sure it's definitely unwrapped (! not ?)

box.physicsBody!.affectedByGravity = true

Make the physics bodies dynamic:

    box.physicsBody!.isDynamic = true
Smilez
  • 113
  • 7
0

In the init() method of your GameScene: SKScene, SKPhysicsContactDelegate object, make sure to assign the contactedDelegate attribute of the physicsWorld variable to your scene (here self):

class GameScene: SKScene, SKPhysicsContactDelegate {
    override func sceneDidLoad() {
        physicsWorld.contactDelegate = self // Most important part!
    }

    internal func didBegin(_ contact: SKPhysicsContact) {
        print("Collision!") // Now every objects colliding within self will call didBegin()
    }
}

Hope this help and is more self-explanatory, have a nice day ma bro.

SHANNAX
  • 322
  • 3
  • 5