Search code examples
xcodeswift2d-gamesskphysicsbody

How to centre world on position when world is physics body?


All my sprites are child nodes of the world. I want the camera to centre on my character (which is a member of the world), so i feed my characters position into this function and the world is moved so that the character is once again centered:

func centerWorldOnPosition(position: CGPoint) {
    world.position = CGPoint(x: -position.x + CGRectGetMidX(frame),
        y: -position.y + CGRectGetMidY(frame))
}

However, when I later gave my character a physics body this led to a jitter image because the character was being move both by the phsics simulation and by the centerWorldOnPosition function because it is a child node of the world. the centerworldOnPosition function was interfering with the physics simulation

To solve this i attempted to move my world by giving it a physics body so that the movement would only occur in the physics simulation by altering the centerWorldOnPositionFunction to what you see below. I have an issue because physics bodys don't have an equivalent to:

    world.position = CGPoint(x: -position.x + CGRectGetMidX(frame),
        y: -position.y + CGRectGetMidY(frame))

so what do you suggest to solve this issue. This is what I tried. I found that the world followed my character somewhat but my character was not near centre, sometimes going off the screen and sometimes the world would run away. using velocity does not seem to have the units of cgpoints.

func centerWorldOnPosition(position: CGPoint) {


    let disired_position = CGPoint(x: -position.x + CGRectGetMidX(frame),
        y: -position.y + CGRectGetMidY(frame))

    let vectorOfChange = CGVector(dx: disired_position.x - world.position.x, dy: disired_position.y - world.position.y)

    world.physicsBody!.velocity = vectorOfChange


}

Solution

  • https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Actions/Actions.html

    the code to centre the world must be located in the didFinishUpdate

    override func didFinishUpdate() {
                centerWorldOnPosition(devilfish.position)
    }