I’m currently doing a runner 2D where the Camera follow the player on axis X, but when the game is running, I see a kind of lag, but that’s not it, it seems that my camera lag…
Here is my code :
public PlayerController thePlayer;
private Vector3 lastPlayerPosition;
private float distanceToMoveX;
// Use this for initialization
void Start () {
thePlayer = FindObjectOfType<PlayerController> ();
lastPlayerPosition = thePlayer.transform.position;
}
// Update is called once per frame
void FixedUpdate () {
// The camera follow the player on X axis
distanceToMoveX = thePlayer.transform.position.x - lastPlayerPosition.x;
transform.position = new Vector3 (transform.position.x + distanceToMoveX, transform.position.y, transform.position.z);
lastPlayerPosition = thePlayer.transform.position;
}
Don’t use FixedUpdate, that should only be used to update physics components such as Rigidbody, because physics components update at a different rate than the rest of the game.
Camera updates are best done in LateUpdate, so that the camera can adjust only after everything else in the scene has updated, but still before rendering at the end of the frame.
You can simplify your following code by not keeping track of previous positions and just setting the camera to the current player X position, which should have the same result as applying the difference since last frame:
but if i don’t put the last position, my player move forward, and i don’t need him to move on the camera but the camera follow the player at the left side…
I would suggest then adding an offset to the current position of the player each update as well, rather than relying on the starting position of the player to be the correct offset to keep, that way you are free to change the offset however you like, or start the camera centered on the player, etc.