Don_Huan
Don_Huan

Reputation: 85

Camera Controller in Unity

There are two similar scripts that makes the same thing(The Camera is following the player).The first, is what I wrote and the second one, is from the unity tutorial.Which one is more reliable and why?

1st

   public class CameraController : MonoBehaviour {

   public GameObject player;

   void LateUpdate () {

    transform.position = new Vector3 (player.transform.position.x,  player.transform.position.y,-10f);

   }
   }

2nd

    public GameObject player;       

    private Vector3 offset;

    void Start () 
    {
    offset = transform.position - player.transform.position;
    }

    void LateUpdate () 
    {

    transform.position = player.transform.position + offset;
    }

Upvotes: 1

Views: 6643

Answers (2)

Programmer
Programmer

Reputation: 125245

There is no such thing as reliability between the two scripts. Although, I would encourage you to use the second script.

The first script is assigning the camera's position with the position of the player. The only thing it doesn't assign is the z-axis which you hard-coded to -10. When game starts, the camera will be moved to where the player is. The z- axis of the camera will be set to -10. This happens every late update.

The second script is assigning the camera's position with the position of the player and offset value taken in the start function. When game starts, the offset distance between the camera and the player is retrieved in the Start function. In the LateUpdate function, the player's position is retrieved and the offset is added to it and is then applied to the camera's position.


The result of the first script is that the camera will always be position where the player is but the z axis will always be set to -10. I am sure you don't want the z axis to not be moving.

The result of the second script is that the camera will always have the-same distance between it and the player. Even if you move the camera or player from the Editor, the second script will automatically adjust the position and make sure that the distance between the camera and the player before the game started is always the-same. I am sure this is what you are looking for but I wouldn't call this reliable. The first code is simply not appropriate for what you are doing , the second code is.

Upvotes: 3

André Marques
André Marques

Reputation: 178

I would bet that the second one is more reliable because it doesn't have any hardcoded variables. But it's also easy to use to programmers and none programmers since it calculates the offSet you want to give in any direction based on the position you set on the scene.

Upvotes: 1

Related Questions