Question by
sasyimmagoat · Feb 13 at 10:42 PM ·
rotationclampx-axis3rd person cameraclamped rotation
How to Clamp a 3rd Person Camera's x-axis Rotation?
public Transform player;
public float moveSmoothTime = 1f; // Lower is slower
public float heightSmoothTime = 1f; // Lower is slower
public float rotationSmoothTime = 0.1f; // Lower is slower
public float followBehindDst = 5f;
public float lookThisFarInFront = 5f;
public float height = 12f;
Vector3 lastPlayerPos;
Vector3 moveCurrentVelocity;
float heightCurrentVelocity;
void Start()
{
lastPlayerPos = player.transform.position;
}
void FixedUpdate()
{
// This allows the player to be removed from the scene without breaking this script
if (player != null)
{
lastPlayerPos = player.transform.position;
}
// Movement
// X- and Z-axis smooth follow
Vector3 moveSmoothed = Vector3.SmoothDamp(transform.position, lastPlayerPos - Vector3.back * -followBehindDst, ref moveCurrentVelocity, moveSmoothTime);
// Y-axis smooth follow
float heightSmoothed = Mathf.SmoothDamp(transform.position.y, height, ref heightCurrentVelocity, heightSmoothTime);
// Apply X-,Y-,Z-axis smoothing
transform.position = new Vector3(moveSmoothed.x, heightSmoothed, moveSmoothed.z);
// Rotation
// Find the point we are rotating around
Vector3 toTarget = lastPlayerPos + Vector3.back * lookThisFarInFront - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(toTarget);
// Find and apply a lerped rotation
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, rotationSmoothTime);
}
I was thinking to add Mathf.Clamp(transform.rotation.x, -20, 43); in rotation, but that didn't work, it just makes the camera jitter.
Comment
Your answer
Follow this Question
Related Questions
Object don't rotate correctly 1 Answer
MathF clamp look toward mouse pointer not working correctly 0 Answers
Clamp a 2D object controlled by the mouse 0 Answers
Euler angles clamping issue 0 Answers
Is this a good way to Clamp a Rotation? 2 Answers