Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent my character controller from rotating on x or z axis?

I am using the in-built character controller and when I rotate my character towards an enemy target, my whole character object (I have a capsule) will also rotate so then my character ends up standing diagonal rather than vertical and if I look at the enemy target again, my character object will turn completely horizontal.

public class LookAt : MonoBehaviour
{
    public Transform lookAtOpponent;

    void Update()
    {
        Vector3 relativePosition = lookAtOpponent.position - transform.position;

        Quaternion rotation = Quaternion.LookRotation(relativePosition, Vector3.up);
        transform.rotation = rotation;
    }
}

I know rigidbody has contraints for each axis that you can tick but I can’t figure this out with a controller.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This way x,z don’t change they are always set to 0

public class LookAt : MonoBehaviour
{
   public Transform lookAtOpponent;

   void Update()
   {
      Vector3 relativePosition = lookAtOpponent.position - transform.position;

      Quaternion rotation = Quaternion.LookRotation(relativePosition, Vector3.up);
      transform.localEulerAngles = new Vector3(0,rotation.eulerAngles.y,0);
   }
}
 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading