Home > Software engineering >  Why does the sprite following the camera with a delay and smoothness?
Why does the sprite following the camera with a delay and smoothness?

Time:12-08

I have a character, background and camera in my pet project. I want the background to follow the camera and i did it. But background moving soooo smoothly. I have a two scripts: for camera and for background.

public class CameraFollowScript : MonoBehaviour
{
[SerializeField]
public Transform player;
[SerializeField]
private float rightLimit;
[SerializeField]
private float leftLimit;
[SerializeField]
private float bottomLimit;
[SerializeField]
private float topLimit;

void FixedUpdate()
{
    if (player)
    {
        var targetPos = new Vector3(player.position.x, player.position.y, transform.position.z);

        Vector3 pos = Vector3.Lerp(transform.position, targetPos, 1f);
        transform.position = targetPos;
    }
    
    transform.position = new Vector3(
        Mathf.Clamp(transform.position.x, leftLimit, rightLimit),
        Mathf.Clamp(transform.position.y, bottomLimit, topLimit),
        transform.position.z);
}

private void OnDrawGizmos()
{
    Gizmos.color = Color.red;
    Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(rightLimit, topLimit));
    Gizmos.DrawLine(new Vector2(leftLimit, bottomLimit), new Vector2(rightLimit, bottomLimit));
    Gizmos.DrawLine(new Vector2(leftLimit, topLimit), new Vector2(leftLimit, bottomLimit));
    Gizmos.DrawLine(new Vector2(rightLimit, topLimit), new Vector2(rightLimit, bottomLimit));
}
}

and background

public class BackGroundScript : MonoBehaviour
{
[SerializeField] public Transform player;

void FixedUpdate()
{
    if (player)
    {
        var targetPos = new Vector3(player.position.x, transform.position.y, transform.position.z);

        Vector3 pos = Vector3.Lerp(transform.position, targetPos, 1f);
        transform.position = pos;
    }
}
}

and i have a small gif with my problem. click

it has a bad fps but i dont have any variant.

you can see that the background is moving in a delay from the camera and because of this, when the camera comes to a stop, it twitches

I tried removing Lerp, but it didn't help

CodePudding user response:

First, assing a constant value of 1f as lerp last argument is useless. This:

Vector3 pos = Vector3.Lerp(transform.position, targetPos, 1f);

Equals this:

Vector3 pos = targetPos

But this is not the problem. The problem is that you use FixedUpdate, which is supposed to be used to do physics manipulations (calculating forces etc). It is NOT synchronized with the frame rate. Hence you see this jitter. For moving background you don't need physics. Simply write your code inside Update which is synchronized with the frame rate.

  • Related