Home > other >  How to make the camera follow the player in unity
How to make the camera follow the player in unity

Time:02-23

Hey i am making a unity game called Cube-Runner. There is a cube and obstacles and you have to go between them. Not going into the game a lot but the problem is how to follow the player. I can't parent it as if i do that while the cube falls the camera will also move with the rotating cube and will make the player(At least myself) dizzy.

Please give me a script

There needs to be a offset Vector3 which i can change from the inspector.

The offset Vector3 may work.

It should be written in C#.

NOTE: I AM NEW TO C# AND UNITY DO NOT JUDGE BY QUESTION

CodePudding user response:

You could try using the cinemachine tool, it will make you camera follow smoothly to the player. You could check any tutorial on youtube but I recommend you to check the one "Brackeys" did.

CodePudding user response:

if you dont want to make the player the parent of the camera, then you can do this :

  1. Create a C# script called CameraMovement and attach it to the camera
  2. add this to CameraMovement
using UnityEngine

class CameraMovement : MonoBehavior
{
   public Transform player;
   public Vector3 offset;
   void Start()
  {
     
  }
  void Update()
  {
     //get the players position and add it with offset, then store it to transform.position aka the cameras position
     transform.position = player.position   offset
  }
}
  1. click on the camera and look at the inspector, you should see that there is a script called CameraMovement and 2 fields : player and offset. assign player with your player (drag and drop) and offset with the relative position between your camera and the player (where the camera is with the player being the center).

and you're done, play the game and see the results

  • Related