genericguy25
genericguy25

Reputation: 602

How can I set an SKCameraNode's position x and y relative to a node?

I'm setting up my camera node programatically. My goal is to have the camera follow the player node's x axis, but have the y axis of the camera higher than "player.position.y", something like "player.position.y + 300".

I found this after googling a while about this issue:

cam.position = CGPoint(x: player.position.x, y: player.position.y + 500)

I put this in didMove(to:) along with the setup of the camera:

cam = SKCameraNode() //initialize and assign an instance of SKCameraNode to the cam variable.
    self.camera = cam //set the scene's camera to reference cam
    //cam.setScale(1.3)

cam.position = CGPoint(x: player.position.x, y: player.position.y + 500)
    addChild(cam) //have cam be a child

I've tried putting it before and after the add child(cam) line, but the cam.position line had no effect.

I've tried both setting my camera up as a child of the player node and the scene, but with either method I can get the camera to follow the player but I can't figure out how to manipulate the X and Y separately. The only way Ive been able to affect the cameras position is using "set scale" but thats more of a global zoom in/out.

Any advice would be greatly appreciated.

EDIT: The first part of the answer is all I needed:

cam = SKCameraNode()
player.addChild(cam)
cam.position = CGPoint(x:0,y:500)
self.camera = cam

Upvotes: 1

Views: 368

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16837

Why not just make camera a child of player, then set the relative position to +500, so that you never have to worry about setting the camera x position again

cam = SKCameraNode()
player.addChild(cam)
cam.position = CGPoint(x:0,y:500)
self.camera = cam

Then on your end update, set your camera y based on what you need:

let cam = player.childNode[0] as! SKCameraNode //Do whatever you need to do to find the camera
cam.position.y = 500 - player.position.y //This way if the player goes up 1 point, the camera moves down one point thus keeping it on the same spot

Upvotes: 2

Related Questions