How would I use sprite kit physics in my endless runner game?
An endless runner fakes motion by keeping the player stationary but moving the background and all the other objects by a set speed.
BUT, I want to simulate physics.
What if I let my player move with the physics engine, move the background by the displacement of the player from the original position, and then move the player back to it's original position?
Would this be smooth and look good? If so, then what methods of sprite kit do I use so no visual errors show to the user.
What's the proper solution?
Thank you.
The proper way is to center the scene on a node. The best way to learn how to do so is to go ahead and visit the docs here (go to section titled 'Centering Scene on a Node'), but if you encounter any problems with the implementation let us know!
In case you're wondering how it works, the background stays stationary (unless you want parallax scrolling), while the character moves. However, every frame the camera 'follows' a player, meaning wherever you moved your player with the physics, the screen will follow and keep the character at the center.
Edit
Here is the code I use in one of my games to center on the sprite (which is a plane controlled by buttons):
-(void)didSimulatePhysics {
... #Code here to simulate plane movement and such
SKNode *camera = [self childNodeWithName:@"//camera"];
SKNode *player = [self childNodeWithName:@"//sprite"];
if (player.position.y >= 0) camera.position = CGPointMake(player.position.x, player.position.y);
else camera.position = CGPointMake(player.position.x, 0);
[self centerOnNode:camera];
if (velocity>1){
self.directionMeter.zRotation = -M_PI/2 + mdirectionOfTravel;
}
}
-(void)centerOnNode:(SKNode *)node {
CGPoint cameraPositionInScene = [node.scene convertPoint:node.position fromNode:node.parent];
node.parent.position = CGPointMake(node.parent.position.x - cameraPositionInScene.x, node.parent.position.y - cameraPositionInScene.y);
}
Basically, when the player is above a certain position, I move the camera up with the player. When the player moves anywhere on the x-axis, the camera always moves with them. I have contact detection to find where the player hits the ground (and thus loses), and the background color (the sky) changes according to the altitude of the plane (the higher the plane, the darker the blue).