Search code examples
c#unity-game-engineaxes

Make GameObject's Y Rotation be the same as the camera's


I have a Cinemachine Freelook camera and i want it similar to Skyrim, where the character's rotation follows where the camera is pointing, but only on the Y axis so that i can move my mouse and look at the character from up and down; This video demonstrates how MrKrabs can move in 3 dimensions, but won't turn. I already tried creating a blank object and putting it at the center of the character, then using transform.LookAt(Camera) to make it point to where the camera is, and finally getting the Y value of the object's rotation, inverting it with -transform.position.y and applying it to MrKrabs, but it didn't work: it was jittery and overall just a bad user experience, is there a way to turn the gameobject based on the camera's rotation? (having the camera always watching his back)


Solution

  • Something like this should do the trick.

    transform.rotation = Quaternion.Euler(0, Camera.main.transform.eulerAngles.y, 0);
    

    Beware that if your camera is a child of your object it will rotate with it.