paracetamolo
paracetamolo

Reputation: 11

Smooth camera movement in Unity 2d

I am working on a 2d RPG game in unity and I wanted to add a smooth camera movement like Brackeys did in this video.

I already tried to use FixedUpdate(), Update() and LateUpdate(), but nothing when I hit play the camera is like lagging behind the player. The strange thing is that when I turn off the camera script the player moves fluidly.

I even tried Vector3.SmoothDamp() and Vector3.Lerp() but nothing it's still a bit laggy.

How do i solve it??

My code by far:

public class CameraMovement : MonoBehaviour

{

public Transform target;
public float smoothing;

void FixedUpdate()
{
    if(transform.position != target.position)
    {
        Vector3 targetPosition = new Vector3
        (target.position.x, target.position.y, 
        transform.position.z); 

        transform.position = Vector3.Lerp
        (transform.position, 
        targetPosition, smoothing);
    }
}

}

Target is the Player Transform.

Upvotes: 1

Views: 3065

Answers (1)

Owais Shaikh
Owais Shaikh

Reputation: 21

Try Removing this - if(transform.position != target.position) Statement.

And also multiply smoothing with time.deltatime. Here-

public Transform target;
public float smoothing;

    void FixedUpdate()
    {
    Vector3 targetPosition = new Vector3
    (target.position.x, target.position.y, 
    transform.position.z); 

    transform.position = Vector3.Lerp
    (transform.position, 
    targetPosition, smoothing*Time.deltatime);
    }
}

Upvotes: 1

Related Questions