Hello,
I have a 2D top-down shooter. My player is a spaceship that moves up, down, left, right. My camera follows my player. My problem is that the sorrounding objects appear jittery or jumpy during movement. My code is shown bellow. My camera is in a separate object and I would like to have it lag behind with a Lerp or SmoothDamp eventually. Any ideas? thanks.
public Rigidbody2D rb;
public Transform camera2;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
if (Input.GetButton("Up"))
{
rb.AddForce(Vector2.up * 50);
}
if (Input.GetButton("Down"))
{
rb.AddForce(Vector2.down * 50);
}
if (Input.GetButton("Right"))
{
rb.AddForce(Vector2.right * 50);
}
if (Input.GetButton("Left"))
{
rb.AddForce(Vector2.left * 50);
}
mainCamera.position = new Vector3(transform.position.x, transform.position.y, -10f);
}
This issue can come up when moving the camera directly in FixedUpdate
because it may be called more or less often than once per frame. This means you may be updating the camera position several times before the frame is drawn, or be updating after several frames are drawn. Worse still, since the two Update
methods aren’t synchronized, you may be moving the camera while the frame is being drawn. Needless to say, weirdness ensues.
You should be fine to keep your physics code where it is, but the code for setting your camera position should be moved to the Update
method. Your object’s physics will still work as it should, but its position will only be queried before the camera draws.
Enabled VSync. Problem solved.
I suggest you see the following video, it might help you.
In general i suggest the following
- Use LateUpdate event fucntion to update the camera position.
- Use smoothdamp.
- Make sure to use “Screen Space - Overlay” on the canvas “Render Mode” since “Screen Space - Camera” will rebuild the layout of the canvas at any camera movement.
I think you should use vector3.lerp to smoothly moving camera
public class CameraController : MonoBehaviour
{
public Transform Target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
private Vector3 velocity = Vector3.zero;
private void LateUpdate()
{
Vector3 desiredPosition = Target.position + offset;
Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed);
transform.position = smoothedPosition; //transform is the camera
}
}
Also set your rigidbody of your target to use ‘Interpolate’