- Home /
Camera Follow for top down 2d shooter game
//Relatively new to C# and unity, can you guys analyse what I've done wrong with my script, when playing the game the camera doesn't seem to follow the player...? Thank you.
public class cameraFollow : MonoBehaviour {
private Vector3 playerTransform;
private float cameraTransformX;
private float cameraTransformY;
private Vector3 cameraVector;
private Vector3 playerVector;
public float cameraSpeed;
void Update ()
{
playerTransform = GameObject.Find ("Player").transform.position;
cameraTransformX = transform.position.x;
cameraTransformY = transform.position.y;
cameraVector = new Vector3 (cameraTransformX, cameraTransformY, -10);
playerVector = new Vector3 (playerTransform.x, playerTransform.y, -10);
Vector3.Lerp (cameraVector, playerVector, cameraSpeed * Time.deltaTime);
}
Answer by robertbu · Jul 28, 2014 at 11:32 PM
This code can be simplified, but the main problem is that you are not assigning the results from the Vector3.Lerp() back to the transform of the camera. It should be:
transform.position = Vector3.Lerp (cameraVector, playerVector, cameraSpeed * Time.deltaTime);
In addition, you should be doing GameObject.Find() inside of Update(). Create a class instance variable at the top of the file and initialize it in Start(), or if the player object can change during play, tag the player and use GameObject.FindWithTag().
Used this script with your fix, works great and is smooth.
Answer by james_170482 · Jul 28, 2014 at 11:42 PM
i think
cameraTransformX = transform.position.x;
cameraTransformY = transform.position.y;
Should Be
cameraTransformX = playerTransform.transform.position.x
cameraTransformZ = playerTransform.transform.position.z
yes sorry i did not notice my mistake
but does changing my example to y ins$$anonymous$$d of z not work?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I need help knowing if Im doin this Right 1 Answer
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index System. 0 Answers
Simple OnGui does not work 1 Answer