Problem with camera rotation and movement

Hello,
The part where camera follows object (moving object) is working fine, but it’s not rotating properly - seems like its rotating around itself.
I have tried separating camera rotation script and movement script, and rotation script is working like I wanted but only with movement script OFF. When ON cam rotating around itself.

I could probably download similar script, and learn nothing. Spend 2h on Google and didn’t help.
I have feeling I missing something, but can’t figure it out. I’m just starting my adventure with Unity.

public class CameraFollowObject : MonoBehaviour
{
    public Transform targetTransform;
    private Vector3 cameraOffset;
    float rotationSpeed = 1.0f;

    [Range(0.01f, 1f)]
    public float smoothFactor = 0.5f;

    [Range(5f, 20f)]
    public float cameraAltitude = 10.0f;

   
    void Start()
    {
        cameraOffset = transform.position - targetTransform.position;   //vector camera -> target
        transform.LookAt(targetTransform);                              //aim camera to target
    }

   
    void LateUpdate()
    {
        Vector3 newPosition = targetTransform.position + cameraOffset;  //update camera->target vector
        newPosition.y = cameraAltitude;                                 //fix camera altitude

        transform.position = Vector3.Slerp(transform.position, newPosition, smoothFactor); //follow player - gently

        RotateCamera();
    }



    void RotateCamera()
    {
        if (Input.GetKey(KeyCode.E))
        {
            transform.RotateAround(targetTransform.position, Vector3.up, rotationSpeed);
        }

        if (Input.GetKey(KeyCode.Q))
        {
            transform.RotateAround(targetTransform.position, Vector3.up, -rotationSpeed);
        }
    }

}

You can’t deal with these separately. Right now you have RotateCamera setting the transform position (via transform.RotateAround), and you also have LateUpdate setting the transform position (by abusing Slerp). You’re telling your object to be in two places at once.

Instead you should have properties that keep track of (1) the desired altitude, and (2) the desired angle in the XZ plane. Adjust these based on key inputs. Then in LateUpdate, you must calculate the correct position using both of these bits of information at once.

1 Like