- Home /
C# Smooth Follow Script Causes Camera "Jitter"
With the help of a few camera scripting tutorials I managed to write up a script for the camera that lets you rotate it around a character when you hold down the left mouse button, but also has the functionality of the Smooth Follow javascript that comes in unity's scripts package.
The only problem is that it causes a jitter with the rotation and y position of the camera every frame. The jitter is usually less than 1, but it is noticeable. I'm still learning some of the functionality of Mathf.Lerp and Quaternions, so I don't really know what the problem is.
Here's the code, if anyone can help me figure it out:
using UnityEngine; using System.Collections;
public class WitchCamera : MonoBehaviour
{
// The target we are following
public GameObject target;
// the height we want the camera to be above the target
public float height = 5f;
// The distance in the x-z plane to the target
public float distance = 10f;
//public float frameOffset = 5f;
public float rotateSpeed = 5f;
// How much we
public float heightDamping = 2f;
public float rotationDamping = 3f;
// Vector3 offset;
void Start()
{
}
void LateUpdate()
{
// Early out if we don't have a target
if (!target)
return;
float wantedRotationAngle = target.transform.eulerAngles.y;
float wantedHeight = target.transform.position.y + height;
float currentRotationAngle = target.transform.eulerAngles.y;
float currentHeight = target.transform.position.y;
//Rotates target attached to play character if the left mouse button is pressed.
if(Input.GetButton("Fire2"))
{
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
target.transform.Rotate(0, horizontal, 0);
}
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
Quaternion currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.transform.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
Vector3 temp = transform.position;// copy to an auxiliary variable...
temp.y = currentHeight;// modify the component you want in the variable...
transform.position = temp;// and save the modified value
// Always look at the target
transform.LookAt(target.transform);
}
}
Your answer
Follow this Question
Related Questions
3D Gravity towards one object 3 Answers
How to Load from an external file, sound 0 Answers
Clamping a Manipulated Camera 0 Answers
c# Adjust In-Game audio 1 Answer