Camera follow with rotation but there is a problem if you hold the S key

Hello Community, this is my script:

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    // Player reference
    private GameObject player;

    private void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
    }

    // Follow the player after his movement is completed.
    private void LateUpdate()
    {
        transform.position = player.transform.position;
        transform.rotation = player.transform.rotation;
    }
}

This works fine, if I press and hold W, A or D it keeps following the player as he moves or rotates, however holding the S key makes the movement to stutter, maybe there is a collision with something but both camera arm and camera are away from player so I don’t know why this happens.

The camera arm’s position is (0.5, 0.5, 0.5) and the child MainCamera is (0.23, 1.56, -1.58), it should look like this

I appreciate anyone please explain me why this happens. Thank you!

Hi Mauro, what do you mean by stutter? I’ve tried your script and pressing “S” makes mine rotate wildly - is this what you are experiencing?

Hi Samuel, sorry for the late reply. Indeed that was I was experiencing (I used incorrect word, sorry).

From my understanding, when you press the S or down key, unity registers the code quicker than you can let go. What i did to avoid this is made an if statement:
if( Input.GetAxisRaw(“Vertical”) >= 0)
transform.rotation = player.transform.rotation;
Essentially what this means is, unity will check which way you are moving on the vertical and if it’s not negative (backwards/S key/ down on num pad) it will rotate the camera to the players rotation. This eliminating the camera freakout, at least for this problem. Probably better ways, but that’s what I thought of.

Privacy & Terms