- Home /
Follow camera in 2d game
Recently I am working on racing game. For that I am following camera with car. But using following code it creates jerk in movement.
I don't want any rotation, I just want to follow in y direction.
public class SmoothCameraFollow : MonoBehaviour
{
private Vector3 cameraOffset, playerOffset;
public float speed;
public Transform target;
void Start ()
{
cameraOffset = transform.position;
playerOffset = target.position;
}
void LateUpdate ()
{
if (GameManager.Instance.IsCarReady) {
Vector3 targetPosition = target.position + cameraOffset - playerOffset;
targetPosition.x = 0;
transform.position = targetPosition;
}
}
}
Please give some help in this.
Answer by Imtiaj Ahmed · Feb 03, 2015 at 03:27 PM
Try this-
Vector3 refVelocity = Vector3.zero;
float smoothTime = 0.5f;
.....
void Update () {
cameraOffset = transform.position;
}
void LateUpdate(){
//Your codes for targetPosition here and then,
transform.position = Vector3.SmoothDamp (cameraOffset, targetPosition, ref refVelocity, smoothTime);
}
It will smoothly follow your car. This is what I used once.
What is meaning of ref refVelocity because at initialization time you have set it only one? At present camera is not moving from its place. What next to do?
http://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html
Edited my answer. Get the camera position in Update()
No your modified code also not generating smooth result for me.
At present only above code generate good result for me. No Lerp() or Damp() function helping me. But I am expecting more smooth result compare to this. So I am here.
Well, sorry to hear that. There are a lot of things that may cause jerkiness and there are a lot of discussion threads out there. If you are using pro, you can find the spikes in the profiler that may cause you the jerk.
Answer by VOTRUBEC · Feb 04, 2015 at 10:08 AM
This code is working correctly for me:
public class CameraScript : MonoBehaviour
{
// Set Player in the Editor.
public GameObject Player;
// Set CamerOffset in the Editor.
public Vector2 CamerOffset;
Vector3 cameraPosition;
// Use this for initialization
void Start ( )
{
cameraPosition = new Vector3 ( 0, 0, -10.0f );
}
void Update ( )
{
cameraPosition.x = Player.transform.position.x + CamerOffset.x;
cameraPosition.y = Player.transform.position.y + CamerOffset.y;
this.transform.position = cameraPosition;
}
}