- Home /
Need help/advice with 2D Camera follow script.
I want to make a script so that the camera will follow the player. I need a variable for X amount. Then, if the player is moving right, it will be -Xamount. Then if the player is moving left, it will be +Xamount. So the player will always be off center of the screen. That way he can see what is in front of him. I also want the damping involved to make a smooth transition. This is what I have but Its not working properly.
using UnityEngine;
using System.Collections;
public class SmoothCamV2 : MonoBehaviour
{
public Transform target;
public float zDistance = 3.0f;
public float height = 3.0f;
public float damping = 5.0f;
public float xDistance;
private float dist = 0;
public bool followBehind = true;
public bool facingRight = true;
void Awake()
{
var t = GameObject.Find("Player2D");
target = t.gameObject.transform;
}
void FixedUpdate()
{
float dir = CrossPlatformInput.GetAxis("Horizontal");
if (dir < 0) { dist = -xDistance; }
if (dir > 0) { dist = xDistance; }
}
void Update()
{
Vector3 wantedPosition;
if (followBehind)
wantedPosition = target.TransformPoint(dist, height, -zDistance);
else
wantedPosition = target.TransformPoint(dist, height, -zDistance);
transform.position = Vector3.Lerp(transform.position, wantedPosition, Time.deltaTime * damping);
}
}
Did you assign a value for xDistance? Also its better to get input in your Update(), not FixedUpdate(). Otherwise your code looks alright.
Just a word of advice, put all your camera movement code in LateUpdate() ins$$anonymous$$d of Update().
Also kindly specify what behaviour you expect and what behaviour you are getting when you specify that it is not working properly.
Answer by Jeff-Rosenberg · Sep 02, 2014 at 05:10 AM
Try Vector3.MoveTowards.
float cameraMoveSpeed = 5f; // m/s
void Update()
{
Vector3 desiredCameraPosition = GetDesiredCameraPosition(); // However you want to do that
transform.position = Vector3.MoveTowards(transform.position, desiredCameraPosition, cameraMoveSpeed * Time.deltaTime;
}
This will move the camera towards your desired position at a fixed speed. You could also use Vector3.Lerp instead if you want the camera to move in a smoother way.
Your answer
Follow this Question
Related Questions
How can I get my camera to reset its position behind the player? 1 Answer
Camera Smooth Follow 2 Answers
Camera Follow sphere with ridgidbody? 4 Answers