How to make camera follow SKNode in Sprite Kit?
Something like this should help. I call the following from my didSimulatePhysics.
-(void)centerOnNode:(SKNode*)node {
CGPoint cameraPositionInScene = [node.scene convertPoint:node.position fromNode:node.parent];
cameraPositionInScene.x = 0;
node.parent.position = CGPointMake(node.parent.position.x - cameraPositionInScene.x, node.parent.position.y - cameraPositionInScene.y);
}
I realize this is similar to Stuart Welsh's answer; however, I'd like to make his good answer a bit more comprehensive.
Basically, Apple recommends that you create a "world" node to contain all of your other nodes, with the world being a child of the actual scene; and further that you create a "camera" node as a child of the world node.
Then, from your scene, you can do something like:
[self centerOnCameraNamed:myCameraName];
Which calls the method (also in your scene):
- (void)centerOnCameraNamed:(NSString*)cameraName
{
SKNode* world = [self childNodeWithName:worldName];
SKNode* camera = [world childNodeWithName:cameraName];
CGPoint cameraPositionInScene = [camera.scene convertPoint:camera.position fromNode:world];
world.position = CGPointMake(world.position.x - cameraPositionInScene.x, world.position.y - cameraPositionInScene.y);
}
The new SKCameraNode seems like a very easy way to do this.
https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKCameraNode/
Simply
1) create an SKCameraNode
// properties of scene class
let cam = SKCameraNode()
let player = SKSpriteNode()
2) add it to your scene camera property
// In your scene, for instance didMoveToView
self.camera = cam
3) make the camera follow your player position
override func update(currentTime: CFTimeInterval)
{
/* Called before each frame is rendered */
cam.position = player.position
}
Using SKCameraNode
with SKConstraint
in Swift 5.1
let camera = SKCameraNode()
camera.constraints = [.distance(.init(upperLimit: 10), to: node)]
scene.addChild(camera)
scene.camera = camera