Search code examples
swiftmacossprite-kitskspritenodeskphysicsbody

SKSpriteNode's position changes after placement


I got a problem with SKSpriteNode. After I place it in the scene on a certain position, it's position starts to change very slowly. This only happens when I attach a SKPhysicsBody to it, but not without it so it's related to that.

Here is the code for my tile that is placed:

import Foundation
import SpriteKit

class Tile : SKNode {

    var sprite = SKSpriteNode(imageNamed: "grassMid")

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented");
    }


    override init() {
        super.init();
        self.sprite.physicsBody = SKPhysicsBody(texture: self.sprite.texture!, size: CGSize(width: 32.0, height: 32.0))
        self.sprite.physicsBody?.dynamic = false
        self.sprite.physicsBody?.collisionBitMask = 0x0
        self.addChild(sprite)
    }
}

Here is the code that places the object:

func addNewTile(position: CGPoint) {
        let t = Tile()
        t.sprite.position = getClosestPointInGrid(position)
        t.sprite.size = CGSize(width: 32.0, height: 32.0)
        if(!doesPositionContainTile(t.sprite.position)) {
             self.addChild(t)
        }
        print(t.sprite.position)
}

For example: I place a tile at position (256, 32) and soon the position has changed to (255.990264892578, 31.9987831115723) and it keeps changing slowly? I don't understand it. Why does this behavior happen?


Solution

  • Alright.

    I have done some research regarding this issue and have come to a conclusion that if a SKSpriteNode is parented to a SKNode and you set the SKSpriteNode's SKPhysicsObject's dynamic property to false, the object will still slowly keep drifting down. It shouldn't move at all with the dynamic property set to false. This bug doesn't occur if SKSpriteNode's parent is the SKScene.

    This bug was reported in Apple developer forums thread at November 27th in 2015. It was said to be still existing on December 20th. I can now say that it still exists on 10th of July 2016. I have Xcode 7.0 and OS X 10.11.5 and I am only familiar with the OS X version of the spritekit, I don't know if the bug is on iOS also.

    Originally my map system was designed so that the map is SKNode and the tiles are SKSpriteNodes. As a result of this bug, I changed it so that the SKSpriteNodes(tiles) are directly added to the SKScene. Now the bug doesn't occur.