Clamp smooth limit camera

Hello everyone,

My camera is in top-down view with 50X rotation degrees. I have 2 problems.

1. My camera follow the player and I have defined the limits of the camera so that it does not go beyond certain values. Currently the X limit working well and my camera X axis is center on the player. BUT for the Z axis does not work.

My start camera value is: -29, 20 (height, never changes), -23.
When I press play button, my camera value is: -29, 20, -11. Why -11?
-11 is my bottom limit and -43 my top limit.

1. How to use a smoothing camera code like â€ślerpâ€ť with â€śclampâ€ť? I want to have a smooth camera move, who not move instantly when the player move.

The code:

``````using UnityEngine;
/*---------------*/
public class CameraFollow : MonoBehaviour {
/*---------------*/
public Transform Target;
/*-----------------------------------------------------*/
void FixedUpdate () {
transform.position = new Vector3(Mathf.Clamp(Target.position.x, -70, -17), 20, Mathf.Clamp(Target.position.z, -11, -43));
}
/*-----------------------------------------------------*/
}
``````

Best regards,

Alexandre

Mathf.Clamp doesnâ€™t like it when the arguments are reversed, -11 is the minimum but is bigger than the maximum of -43.

Reverse the arguments and it should work as expected:

``````Mathf.Clamp(Target.position.z, -43, -11)
``````

First of all, never move the camera in FixedUpdate. That does not run as often as update, so your camera will jump around.

Generally you want to use LateUpdate, as thatâ€™ll always move the camera after the player has moved, but before the screen updates.

Smoothing is pretty straight-forwards. Instead of:

``````transform.position = new Vector3(...);
``````

You do:

``````var currentPosition = transform.position;
var targetPosition = new Vector3(...);
transform.position = Vector3.Lerp(currentPosition, targetPosition, Time.deltaTime * X);
``````

Where you have to figure out what X works best for you - higher X means faster camera movement.

1 Like

Thank you guys. Yes Baste, but I use velocity for the movement of my main character and the camera jitter/jerk this is why I put my code on Fixed

Thatâ€™s because youâ€™ve got bad settings on your character. Set itâ€™s rigidbody to interpolate or extrapolate, as otherwise it only moves the player object in FixedUpdate - which will cause it to visibly jump around.

1 Like

Thank you Baste and Adrian, I forgot to put in interpolate -_-.

Did you manage to make the clamp and lerp work? how did you do it?