HeeysamH HeeysamH - 3 months ago 38
Swift Question

Swift Spritekit Camera Follow skspritenode(Player)

I started making a game some time ago.
but there is something i can't fix.

I wan the Camera to Follow the Player,
I have tryed a lot of code like setting the position of the SkCamera to the Player Position. But the camera always end up looking another place.

What other alternatives do i have to making the camera follow the player node in the y axis?

Answer

The easiest way to make the camera always follow the player, is to make the camera a child of the player, that just assign this camera to the scene. Then if you need to take focus away from the player, have another camera set up, so that you can swap.

If you want the camera to only follow the player on the y axis, then make sure that player and camera are siblings to the same parent node, and on your didEndUpdate method, just add camera.position.y = player.position.y

Alternative: If player is a subclass of SKSpriteNode, you could always override the position property, and set the camera in there:

override var position : CGPoint
{
    didSet
    {
        scene?.camera?.position.y = position.y //Yes we want to use ? because we do not know if there is a scene when changing the position of this sprite
    }
}