# How do I keep the camera behind the player?

I am developing a Third Person Shooter.

Until now, I had parented the camera to player. It would therefore automatically stay behind the player.

Because this would not work well with Root Motion, I need to use a different approach:

In my script, I need to make it so that the camera follows the player.

How could I make it so that the camera stays behind the player at always the same position (and with the same rotation)?

This is my current code, but it doesn't work:

    _camera.transform.rotation = Quaternion.Euler(0, this.transform.rotation.eulerAngles.y, 0);
_camera.transform.position = _InitialCamPos + this.transform.position;


Can anybody help?

Thank you!

• Can you describe what problem you have with root motion? Commented Aug 13, 2021 at 11:46

It looks like you want something like this:

// Get a "yaw-only" rotation without relying on Euler angles.
var forward = transform.forward;
forward.y = 0;
_camera.transform.rotation = Quaternion.LookRotation(forward);

// Map the camera position from the player's local space to world space.
_camera.transform.position = transform.TransformPoint(_InitialCamPos);


Here _InitialCamPos is measured in the local coordinate system of this object. So for instance if the character's origin is at its feet, and you want the camera to be 1 m above that and nudged 0.1 m forward, that's (0, 1, 0.1). The TransformPoint method will automatically handle adjusting this based on the character's rotation and translation.

If you need to determine _InitialCamPos dynamically based on where the camera was at scene load time, you can use something like this:

void Awake() {
_InitialCamPos = transform.InverseTransformPoint(_camera.transform.position);
}


This maps a world space point into the object's local coordinate system.

Create an empty gameobject as a child of your player then attach the camera to the empty gameobject and reposition camera as per your need. Hierarchy would look something like:

 Player
|- EmptyGO
|- Camera


Why don't you use unity cinemachine it has a lot of different camera options and you can do most of the thing without coding and it is really flexible. Here are the docs: https://docs.unity3d.com/Packages/[email protected]/manual/index.html

• I have spent so much time on my own camera logic already... :( It breaks my heart to use cinemachine. Commented Sep 5, 2021 at 20:10
• I know the feeling but it goes down to why would you invest time in a complicated way to set up your camera when you can yust use cinemachine and invest that time in something more inportant in your project. You said that you already spend a lot of time in creating that script now you will spend more time in fixing it, plus if you get new problems down the road that is more time spent trying to fix something that you could do in like 5 minutes with cinemachine.
– Ivan
Commented Sep 6, 2021 at 7:43