Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Resolved How to make rotation with quaternions along one axis? So that the character does not lean.

Discussion in 'Scripting' started by Gamadrila, Sep 25, 2022.

  1. Gamadrila

    Gamadrila

    Joined:
    Sep 5, 2021
    Posts:
    126
    Hello everyone.
    Here is my script.
    Code (CSharp):
    1. void povorotNaVraga()
    2.         {
    3.             Vector3 relativePos = Personag_vrag.teloPersonaga.transform.position - transform.position;
    4.             rot = Quaternion.LookRotation(relativePos);
    5.             transform.rotation = Quaternion.RotateTowards(transform.rotation, rot, Time.deltaTime * 400);
    6.             if (Mathf.Abs(Quaternion.Dot(transform.rotation, rot)) <0.99f)
    7.             {
    8.                 povorotBool = false;
    9.             }
    10.             else
    11.             {
    12.                 transform.rotation = rot;
    13.                 povorotBool = true;
    14.             }
    15.         }
    What needs to be fixed in my function? Or maybe a better way?
     
    Last edited: Sep 25, 2022
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    2,408
    Well, the issue is probably your "relativePos". If the two objects are not exactly at the same height, you get a vector that is tilted up or down. So you probably want to get rid of any "y" offset. You can simply do:
    Code (CSharp):
    1. Vector3 relativePos = Personag_vrag.teloPersonaga.transform.position - transform.position;
    2. relativePos.y = 0f;
    3. rot = Quaternion.LookRotation(relativePos);
    4. // [ ... ]
     
    Gamadrila likes this.
  3. Gamadrila

    Gamadrila

    Joined:
    Sep 5, 2021
    Posts:
    126
    Thank you. This is what I need.