Reputation: 509
After countless searches, I don't understand how this is possible, in the Unity editor window, this is very easy.
How do you Rotate an object, that exists at any point in the world, where it perfectly rotates around it's own center point?
I don't want to add a "parent" gameobject, and I don't want to necessarily rely on the object's MeshRenderer. (due to mismatching naming conventions)
Here is the latest code I have tried. (I had the most success with this)
public float deg = 0;
public GameObject go;
public Vector3 center;
public Rigidbody rb;
void Start ()
{
deg = 0;
go = this.gameObject;
rb = go.GetComponent<Rigidbody>();
center = go.GetComponent<BoxCollider>().center;
}
private void FixedUpdate()
{
deg += 1f;
if (deg >= 360f) deg = 0;
Vector3 cen = go.transform.position; // + center;
go.transform.RotateAround(cen, Vector3.up, deg);
}
The behavior I'm seeing is that either it rotates around the corner of the object, or it rotates around the center, but moves the object all over the screen. In the code revision above, it rotates around the corner.
Upvotes: 2
Views: 1632
Reputation: 20249
The problem is that center = go.GetComponent<BoxCollider>().center;
gives you the center's position in local space (the center's position relative to go
's position and rotation), but if you're using RotateAround
, the first argument needs to be in global space (the center's position relative to the origin point with no rotation).
So, to fix the problem, we need to convert from local space to global space. We can use Transform.TransformPoint
to do this:
public float deg = 2f;
public GameObject go;
public Vector3 cenLocal;
public Rigidbody rb;
void Start ()
{
go = this.gameObject;
rb = go.GetComponent<Rigidbody>();
cenLocal = go.GetComponent<BoxCollider>().center; // Center (local space)
}
private void FixedUpdate()
{
Vector3 cenGlobal = go.transform.TransformPoint(cenLocal); // Center (global space)
go.transform.RotateAround(cenGlobal , Vector3.up, deg);
}
As an aside, you may already know this, but if go == this.gameObject
always, you can just use transform.xyz
instead of go.transform.xyz
. Simply using transform
is the more conventional way of referring to this.gameObject.transform
.
Upvotes: 3