Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity camera follows player script

I'm pretty new to Unity. I tried to create a script that the camera would follow the actor (with a little difference). Is there a way to improve the code? It works just fine. But I wonder if I did it the best way. I want to do it about as I wrote, so if you have any tips. Thank you

Maybe change Update to FixedUpdate ?

public GameObject player;

// Start is called before the first frame update
void Start()
{
    player = GameObject.Find("Cube"); // The player
}

// Update is called once per frame
void Update()
{
    transform.position = new Vector3(player.transform.position.x, player.transform.position.y + 5, player.transform.position.z - 10);
}
like image 741
Ziv Sion Avatar asked Apr 14 '26 03:04

Ziv Sion


2 Answers

Making the camera following the player is quite straight forward.

Add this script to your main camera. Drag the reference of the player object to the script and then you are done.

You can change the values in the Vector 3 depending on how far you want the camera to be from the player.

using UnityEngine;

public class Follow_player : MonoBehaviour {

    public Transform player;

    // Update is called once per frame
    void Update () {
        transform.position = player.transform.position + new Vector3(0, 1, -5);
    }
}
like image 65
Zaphod Avatar answered Apr 15 '26 15:04

Zaphod


Follows player in the back constantly when the player rotates, no parenting needed, with smoothing.

Piece of Knowledges:

  • Apparently, Quaternion * Vector3 is going to rotate the point of the Vector3 around the origin of the Vector3 by the angle of the Quaternion
  • The Lerp method in Vector3 and Quaternion stand for linear interpolation, where the first parameter gets closer to the second parameter by the amount of third parameter each frame.
using UnityEngine;

public class CameraFollow : MonoBehaviour

{
    public Transform target;
    public float smoothSpeed = 0.125f;
    public Vector3 locationOffset;
    public Vector3 rotationOffset;

    void FixedUpdate()
    {
        Vector3 desiredPosition = target.position + target.rotation * locationOffset;
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
        transform.position = smoothedPosition;

        Quaternion desiredrotation = target.rotation * Quaternion.Euler(rotationOffset);
        Quaternion smoothedrotation = Quaternion.Lerp(transform.rotation, desiredrotation, smoothSpeed);
        transform.rotation = smoothedrotation;
    }
}
like image 26
antane Avatar answered Apr 15 '26 17:04

antane