from Quaternion to RotateAround

Hey,

I am trying to rotate my object so that it’s Vector3.up points int the same direction as my Normal vector (so that the object stays parallel to the ground). So I have already calculated my normal and I use the following code to position my object:

transform.rotation = Quaternion.FromToRotation(transform.up, normalVector) * transform.rotation;

The problem is that for other reasons the pivot of my transform is not in it’s center, so the question is how can I rotate the object around it’s physical center to match the normalVector.

I thought about using something like transform.RotateAround(), but I kind of don’t know what to input as I would have to calculate some kind of angles and I do not know how to get those…

Also important I need to keep my current rotation around the Y-axis so that the object looks in the right direction.

Getting the true center of an object can be done using a collider attached to it, assuming the collider is proportional to the object itself. If that isn’t the case, you could also use an object’s sprite or mesh to get its true center. For example, if you have an object with a BoxCollider attached to it, you can use the method GetComponent<BoxCollider>().bounds.center to get the center of the box in world units. Then you can use the RotateAround method to rotate the object around it’s true center. If you wish to only rotate around the y-axis, then it should be as simple as specifying that in the method’s second argument. The following code has been tested with an object that has a wonky pivot point, but a BoxCollider2D that fits normally around the sprite:

using UnityEngine;

public class RotateAroundCenter : MonoBehaviour 
{
    public float Speed = 20f;

    private void Update()
    {
         transform.RotateAround
         (
             GetComponent<BoxCollider2D>().bounds.center, 
             new Vector3(0f, 0f, 1f), 
             Speed
         );
    }
}

So for your purposes, assuming you have a BoxCollider or something similar attached to your gameobject, you could do this in the update:

transform.RotateAround
(
    GetComponent<BoxCollider>().bounds.center, 
    new Vector3(0f, 1f, 0f), 
    Speed
);

The first argument is the true center of your object, the second argument is what axis you wish to rotate on, that being the y-axis, so you simply pass in a vector where the y value is one, and the x and z values are zero. Finally, your last argument is the angle you wish to rotate at. As long as this method is being called in Update(), FixedUpdate(), or something similar, then you should be able to achieve a constantly rotating object by just passing in the amount of degrees you wish to rotate each frame.