Sergio Toledo Piza Sergio Toledo Piza - 3 years ago 590
Swift Question

Swift: Make control buttons not move with camera

I'm building a platform game, and I made the camera follow the player when he walks:

let cam = SKCameraNode()

override func didMoveToView(view: SKView) {
self.camera = cam
...
}

override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */

cam.position = Player.player.position
...


But, when the camera moves, the control buttons move as well
enter image description here

What should I do to keep the control buttons static?

Answer Source

See this note in the SKCameraNode docs:

A camera’s descendants are always rendered relative to the camera node’s origin and without applying the camera’s scaling or rotation to them. For example, if your game wants to display scores or other data floating above the gameplay, the nodes that render these elements should be descendants of the current camera node.

If you want HUD elements that stay fixed relative to the screen even as the camera moves/scales/rotates, make them child nodes of the camera.

By the way, you don't need to change the camera's position on every update(). Instead, just constrain the camera's position to match that of the player:

let constraint = SKConstraint.distance(SKRange(constantValue: 0), toNode: player)
camera.constraints = [ constraint ]

Then, SpriteKit will automatically keep the camera centered on the player without any per-frame work from you. You can even add more than one constraint — say, to follow the player but keep the camera from getting too close to the edge of the world (and showing empty space).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download