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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to rotate a game object pivoting by the center, and not by the corner?

Discussion in 'Scripting' started by asperatology, Aug 14, 2015.

  1. asperatology

    asperatology

    Joined:
    Mar 10, 2015
    Posts:
    981
    Note that I'm using Unity UI to help visualize what I'm doing.

    This is how the arrow rotates when just applying a new Quaternion value to its local rotation:



    And this is what I plan to understand Quaternion rotations by adding an offset, in order to get this result (not yet happening at the moment):



    This is my pseudo-code that doesn't seem to work like I expected:

    Code (CSharp):
    1. Transform transform = GetComponent<Transform>();
    2. transform.position += new Vector3(arrow.GetWidth() / 2f, arrow.GetHeight() / 2f, 0f);
    3. transform.localRotation = Quaternion.Euler(0f, 0f, angle) * Vector3.one;
    4. transform.position -= new Vector3(arrow.GetWidth() / 2f, arrow.GetHeight() / 2f, 0f);
    How do you rotate a game object by offsetting its pivot point (non Unity UI wise), like the green arrow in the second GIF?
     
  2. Wheresmind

    Wheresmind

    Joined:
    Oct 31, 2013
    Posts:
    5
    You could use RotateAround

    Code (CSharp):
    1. transform.rotation = Quaternion.identity;
    2. transform.RotateAround(transform.position + new Vector3(arrow.GetWidth() / 2f, arrow.GetHeight() / 2f, 0f), Vector3.forward, angle);
    ]
     
  3. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    You have three options.

    1. RotateAround
    2. Fix the pivot of your mesh in 3d tool
    3. Make mesh a child of gameobject and rotate parent.
     
    NemoBemo25 and QQQ_QQQ like this.
  4. asperatology

    asperatology

    Joined:
    Mar 10, 2015
    Posts:
    981
    Thank you.

    Where can I look up Quaternion math involving rotating game objects? It's okay if there's no answer.
     
  5. QQQ_QQQ

    QQQ_QQQ

    Joined:
    Jul 12, 2019
    Posts:
    15
    Third solution is so simple and makes the job done! Thanks!
     
    NemoBemo25 likes this.
  6. Thiddious

    Thiddious

    Joined:
    Mar 8, 2020
    Posts:
    1
    https://eater.net/quaternions
     
    Olipool likes this.