0

I am relatively new to Swift and Sprite kit but have ran across an issue where I have changed the physics body of an SKSpriteNode to be:

bucket50.physicsBody = SKPhysicsBody(circleOfRadius: bucket50.size.width / 4.0)

Originally it was -

bucket50.physicsBody = SKPhysicsBody(texture: bucket50.texture!, size: bucket50.texture!.size())

Since making this change the collision detection I have put in place no longer works however as far as I am concerned I have just made the physics body smaller. The ball I am sending towards the bucket does collide but the score isn't registered.

Code is also below that I a using for detection.

func didBegin(_ contact: SKPhysicsContact) {

    if contact.bodyA.node?.name == "bucket_50" {

        ball.isHidden = true
        
        //Add score for hitting bucket
        highScore = highScore + 50
        
        //Display Text
        score.text = "Score - \(highScore)"

    }

Thanks in advance

Matthew P
  • 87
  • 1
  • 1
  • 4
  • 2
    You've only changed that 1 line of code and the contacts are no longer registering? I assume if you change it back then it starts working again? – Steve Ives Mar 28 '22 at 14:07
  • Indeed, if I change the physicsbody = SKPhysicsBody(texture: bucket50.texture!, size: bucket50.texture!.size()) everything starts working again. Only real difference I can see it that I am going from texture: to circleOfRadius: – Matthew P Mar 28 '22 at 14:25
  • 1
    Print `contact.bodyA` and `contact.bodyB` while keeping circular physics body, and see what it says. I am not sure how your didBegin looks completely, but I think you are not handling contact detection properly (usually there is no need to use node names, cause you have `contactTestBitMask properties`...) – Whirlwind Mar 28 '22 at 14:39
  • Solved - Silly me, turns out that bodyB was the contact with the bucket hence my if statement on the node name to add a score didn't work. – Matthew P Mar 29 '22 at 12:59
  • 1
    Just search how to implement didBegin contact. It will help you to avoid these kind of errors. I am sure there are already plenty of answers like that. Just search solution without node names. – Whirlwind Mar 29 '22 at 15:45
  • 2
    @MatthewP This answer gives an example of how I like to structure my `didBegin()`. There are other ways that work, but I think this way makes it clear what's going on and also easy to add new contacts: https://stackoverflow.com/a/51041474/1430420 – Steve Ives Mar 30 '22 at 09:23

1 Answers1

0

First you need to assign the mask value to the nodes you are going to use, then you need to use the mask category of the two nodes to compare at contact time, and when you get it you can perform an action.

Something like this:

let contacting: UInt32 = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if contacting == bucket50.categoryBitMask | other.categoryBitMask {
    setAction
}

All within didBegin

user16217248
  • 3,119
  • 19
  • 19
  • 37