0
votes

I have a Swift / SpriteKit game in which a whole bunch of sprites have physics bodies to detect collision with the player - but otherwise they are not supposed to move.

My issue is that as soon as I add a physics body, the sprite appears to move fractionally. More specifically its position changes by a small fraction (like 0.0003). Initially such a small change does not matter, but it keeps changing like this until the sprite actually moves onscreen and messes up the game.

To narrow it down I created a simple project with just one sprite and I notice that as soon as I attach a physics body to my sprite its position shifts fractionally.

Things I've already tried:

  1. Check so see gravity is turned off
  2. Set the resting property of physics body to true
  3. set the affected by gravity property of physics body to false

Im coding using Xcode on OS X

But no luck.

Here's a code fragment which shows this in the test project:

import SpriteKit


class TestScene: SKScene, SKPhysicsContactDelegate {

  let sprite1 = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(50, 50))

override func didMoveToView(view: SKView) {

    physicsWorld.gravity = CGVectorMake(0.0, 0.0)
    physicsWorld.contactDelegate = self

    sprite1.position = CGPointMake(200, 200)
    sprite1.physicsBody = SKPhysicsBody(rectangleOfSize: sprite1.size)
    sprite1.physicsBody?.affectedByGravity = false
    sprite1.physicsBody?.resting = true

    self.addChild(sprite1)
    sprite1.position = CGPointMake(200, 200)

  }


  override func update(currentTime: NSTimeInterval) {
    print(sprite1.position)

    // position is not 200,200 as expected
    // it becomes 199.999938964844, 199.999938964844 after a few updates
    // In my real project the position will keep drifting like this until it moves on screen

  }

}
1
Try printing the velocity of the physics body to see if it is changingDieblitzen
Just checked, velocity is consistently zero.farid98

1 Answers

0
votes

I think its the dynamic property which is set to yes by default. Set it to false and the sprite should not move anymore

sprite1.physicsBody?.dynamic = false

I just tested this in a project and it still says 199.9.... but it doesnt seem to increase or decrease