- Home /
Camera follow
Hi! It's my first time making a CameraFollow script. It's just a simple one. I used this code:
public class CameraFollow : MonoBehaviour { public GameObject player;
private void Update()
{
Vector2 playerPosition = new Vector2(player.transform.position.x, player.transform.position.y);
//follow player
transform.position = playerPosition;
}
}
But when I enable the script and play the game, I no longer see the game, just a solid color. And if I disable the script, it goes back to normal and I see the game again. I don't get it. I didn't change anything else and it did the same thing on another tutorial project I was working on. Does anyone know why this happens?
Answer by logicandchaos · Feb 15, 2021 at 04:40 PM
It's because you are setting your camera to the exact position of your character. Your camera is probably inside your player, this is more how to do 1st person camera. If you want 3rd person or 2d sidescroll you need to position your camera away from player but pointing at them. There is look at for just this purpose. Alos moving your camera in update will look terrible! You need to move your camera in LateUpdate().
Yes, LateUpdate() is better, to make the camera keep a distance you do a public Vector3(or Vector2 depending or 3d or 2d games) for example call it CameraDistance and now, you need to create a transform called something like player and add your player in the inspector. now you do: transform.postion = player.position - CameraDistance (I think is like this, if not please tell me every mistake i will apreciate it
Answer by DJcrafter5606 · Feb 15, 2021 at 04:42 PM
Maybe you aren't keeping a distance between the player and the camera
Answer by mariannabell · Feb 15, 2021 at 04:50 PM
Thank you both so much!! I really appreciate it. That was the exact problem. I had to move the camera back on the z axis so that it wasn't on top of the player. For any newbies like me, if you ever get this problem, this is the corrected code I used:
{ public GameObject player;
private void LateUpdate()
{
Vector3 playerPosition = new Vector3(player.transform.position.x, player.transform.position.y, -10);
//follow player
transform.position = playerPosition;
}
}
Your answer
Follow this Question
Related Questions
Can't use camera.main [SOLVED] 1 Answer
Camera Problem 0 Answers