Search code examples
swiftsprite-kitskphysicsworld

didBeginContact falsely triggered


In my game, I have lasers that shoot forward from a point. I use this code to stretch out the laser sprite and move it to simulate the motion in an update function:

let height = size.height
yScale += travelSpeed * CGFloat(time)
let difference = size.height - height
let xMove = sin(-zRotation) * difference * 0.5
let yMove = cos(-zRotation) * difference * 0.5
position = CGPoint(x: position.x + xMove, y: position.y + yMove)

Everything LOOKS perfectly fine - the laser shoots out from a point, and the physics body outline from view.showPhysics follows exactly. However, didBeginContact is sometimes falsely triggered when the player is not in contact with the laser. Why does this happen?

Edit:

Laser Physics Body:

    physicsBody = SKPhysicsBody(texture: texture!, size: size)
    physicsBody!.affectedByGravity = false
    physicsBody!.linearDamping = 0
    physicsBody!.collisionBitMask = 0
    physicsBody!.categoryBitMask = 1

Player Physics Body:

    physicsBody = SKPhysicsBody(circleOfRadius: 5)
    physicsBody!.affectedByGravity = false
    physicsBody!.linearDamping = 0
    physicsBody!.collisionBitMask = 0
    physicsBody!.contactTestBitMask = 1

So they're set up so that didBeginContact is called when they collide, and it does. The problem I'm having is that didBeginContact is also called sometimes when the player is not in contact. My current assumption is that my movement code is misplacing the lasers' physics body for a non-visible instant or something.

I set a break point inside didBeginContact and took a screenshot. The objects that collided are the ship and the laser going across the corner.


Solution

  • It turns out that the physics body becomes slightly inaccurate if you try to stretch out a sprite to ~100 times it's original size. Oops.

    I tried just re-applying a new physics body in update, which seems to work.