I am making a game where the player controls a spaceship and I wanted to add a smooth follow camera. I tried some code, but I am having some trouble. Whenever I tilt the ship down, the camera zooms out and the opposite when I tilt the ship up. Whenever I raise the position damping, the camera no longer moves smoothly with the ship. If anyone could help me with this that would be greatly appreciated. Here is my code:
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform target; // The target we are following
public float distance; // The distance from the target along its Z axis
public float height; // the height we want the camera to be above the target
public float positionDamping; // how quickly we should get to the target position
public float rotationDamping; // how quickly we should get to the target rotation
// Use this for public variable initialization
public void Reset() {
distance = 1.75f;
height = 0.5f;
positionDamping = 10f;
rotationDamping = 80f;
}
// LateUpdate is called once per frame
public void LateUpdate () {
ensureReferencesAreIntact();
#region Get Transform Manipulation
// The desired position
Vector3 targetPosition = target.position + target.up * height - target.forward * distance;
// The desired rotation
Quaternion targetRotation = Quaternion.LookRotation(target.position-transform.position, target.up);
#endregion
#region Manipulate Transform
transform.position = Vector3.MoveTowards(transform.position, targetPosition, positionDamping * Time.deltaTime);
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotationDamping * Time.deltaTime);
#endregion
}
// Checks to make sure all required references still exist and disables the script if not
private void ensureReferencesAreIntact() {
if (target == null) {
Debug.LogError("No target is set in the SmoothFollow Script attached to " + name);
this.enabled = false;
}
}
}
↧