1

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.

Zek
  • 155
  • 7
  • 1
    You need to provide an example that we can verify is not working, your code shows nothing – Knight0fDragon Jan 06 '17 at 19:57
  • Generally if didBegin(contact:) is triggered, there's a good reason for it. As KoD has saud, we'll need more code (physics body definition, category & contactTest bitMasks plus your didBegin(contact:) code. Also an exact description of which node are purportedly erroneously contacting which others. – Steve Ives Jan 06 '17 at 21:47
  • 1
    'let height = size.height' and 'let difference = size.height - height' makes 'difference' always 0. – Emptyless Jan 06 '17 at 22:55
  • yScale changes height, so size.height is different than the height of the object before. It gets the difference between the old and new height so I can move it half as much so 1 endpoint of the laser stays in the same spot. – Zek Jan 07 '17 at 16:04
  • possibly related (no solution though) http://stackoverflow.com/questions/29763240/spritekit-physics-false-positive – CupawnTae Jan 07 '17 at 17:02

1 Answers1

1

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.

Zek
  • 155
  • 7