Hi there. I’m trying to make a smooth following camera, that will follow the player along a 2d plane. I want something that will actually change it’s position to maintain a view behind the player, instead of just looking at the player. So far I have tried smoothDamp, iTween’s moveTo and moveUpdate, in both the Update and LateUpdate main functions, as well as a simple Lerp expression which is what I have settled on for now. While some work better than others, I find there is still a jitter present when the camera moves. If anyone has any suggestions on how to achieve the effect I am after, without jitter, please let me know. Here is the code I have settled on for now, which seems to suffer the least out of all the things I have tried thus far.
using UnityEngine;
using System.Collections;
public class heroCamera : MonoBehaviour {
GameObject scriptCamera;
public Transform heroShip;
public float smooth = 2.5F;
public float distance = -70.0F;
public float minHorizontal = 0.0F;
public float maxHorizontal = 0.0F;
public float minVertical = 0.0F;
public float maxVertical = 0.0F;
void Start () {
scriptCamera = gameObject;
}
void LateUpdate () {
float newTargetX = Mathf.Lerp (scriptCamera.transform.position.x, heroShip.position.x, (smooth * Time.deltaTime));
float newTargetY = Mathf.Lerp (scriptCamera.transform.position.y, heroShip.position.y, (smooth * Time.deltaTime));
scriptCamera.transform.position = new Vector3(
(Mathf.Clamp(newTargetX,minHorizontal,maxHorizontal)),
(Mathf.Clamp(newTargetY,minVertical,maxVertical)),
distance);
}
}
Keep in mind that Physics and frames run independently. If you move objects with physics (including FixedUpdate()), you need to move your camera with physics (and/or in FixedUpdate()) otherwise you will get jitter. If you move everything on a per frame basis, you need to move your camera the same way (in Update()). If by any reason you must use both physics and frame based movement in your scene, that’s when you can look at interpolation, otherwise you are just tolling on performance with it.
Try this:
using UnityEngine;
using System.Collections;
public class heroCamera : MonoBehaviour {
public Transform heroShip;
public float smooth = 2.5F;
public float distance = -70.0F;
public float minHorizontal = 0.0F;
public float maxHorizontal = 0.0F;
public float minVertical = 0.0F;
public float maxVertical = 0.0F;
Vector3 position;
void Start() {
position = transform.position;
}
// You would use Update()/LateUpdate() if your game is completely frame based
void FixedUpdate() {
position = Vector3.Lerp(position, heroShip.position, (smooth * Time.fixedDeltaTime));
position = new Vector3(
(Mathf.Clamp(position.x, minHorizontal, maxHorizontal)),
(Mathf.Clamp(position.y, minVertical, maxVertical)),
distance);
transform.position = position;
}
}
Btw if your game jitters, it could be because you have too many Debug.Log statements, or you may be missing a Time.deltaTime somewhere. Just a thought.