SKCameraNode follow node

Hi All,


I'm trying to setup a SKCameraNode to follow another node like so:


SKCameraNode *cameraNode = [SKCameraNode node];
[self addChild:cameraNode];
[self setCamera:cameraNode];


[self setPlayer:[[SKSpriteNode spriteNodeWithColor:color size:CGSizeMake(60, 60)]];
[self addChild:[self player]];

[[self player] setPosition:CGRectGetMidX(self.frame),CGRectGetMidY(self.frame)];
[[self camera] setPosition:[[self player] position]];

SKConstraint *con = [SKConstraint distance:[SKRange rangeWithLowerLimit:0 upperLimit:0] toNode:[self player]];
[[self camera] setConstraints:@[con]];


However, the camera isn't centered over the player as I'd expected. I'm assuming this has something to do with the fact that the camera has applied an opposite position to the player and therefore 'pushed' it out of view. After hardcoding some positions to the camera I managed to get the player centered in the camera and the following works, however I'm wondering how I can center the camera on the player without having to hardcode the starting position.


Thanks in advance.

In GameScene.sks, set the parent of your SKCamera to the character name. Then write this code in GameScene.m

SKCameraNode *camera = (SKCameraNode *)[self childNodeWithName:@"your camera name"];
   
    id horizConstraint = [SKConstraint distance:[SKRange rangeWithUpperLimit:100] toNode:character name];
    id vertConstraint = [SKConstraint distance:[SKRange rangeWithUpperLimit:50] toNode:character name];
   
    id leftConstraint = [SKConstraint positionX:[SKRange rangeWithLowerLimit:camera.position.x]];
    id bottomConstraint = [SKConstraint positionY:[SKRange rangeWithLowerLimit:camera.position.y]];
    id rightConstraint = [SKConstraint positionX:[SKRange rangeWithUpperLimit:character.position.x]];
    id topConstraint = [SKConstraint positionY:[SKRange rangeWithUpperLimit:character.position.y]];
   
    [camera setConstraints:@[horizConstraint,vertConstraint,leftConstraint,bottomConstraint, rightConstraint, topConstraint]];

Build and run your game, it will work fine.

SKCameraNode follow node
 
 
Q