Cant quite get this right. I’m using this camera to follow my in-game object and it works perfectly but I want to stop the followed object going too far from the camera.
Any ideas?
(I know its simple but I have brainfog)
using UnityEngine;
using System.Collections;
public class DungeonCamera : MonoBehaviour {
public GameObject target;
public float damping = 1;
Vector3 offset;
void Start() {
offset = transform.position - target.transform.position;
}
void LateUpdate() {
Vector3 desiredPosition = target.transform.position + offset;
Vector3 position = Vector3.Lerp(transform.position, desiredPosition, Time.deltaTime * damping);
transform.position = position;
transform.LookAt(target.transform.position);
}
}
The issue you may be having could be caused by your character being able to constantly accelerate which means your camera is always lagging behind and the lag gradually increases over time. You can fix it by preventing the character from being able to constantly accelerate by increasing its drag (linear damping) setting, assuming it’s a rigidbody.
Or if you want the character to be able to constantly accelerate then you can have the camera take the target’s velocity into account like so:
public Rigidbody target; // switch to referencing the target's rigidbody instead of its gameObject
void LateUpdate() {
Vector3 desiredPosition = target.position + offset + target.velocity;
Vector3 position = Vector3.Lerp(transform.position, desiredPosition, Time.deltaTime * speed);
transform.position = position;
transform.LookAt(target.transform.position);
}
Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations. As long as you move those positions smoothly, the camera will be nice and smooth as well, both positionally and rotationally.