I tried using the transform.Rotate(0,0,90) function to rotate an object around the y axis on its center, but instead is rotating an axis on its left. The inspector window indicates only the rotation changes and the position is fixed but the object moves. Any suggestions?
All of the transform.Rotate etc. functions rotate around the object's pivot, not the centre. To rotate around the centre instead, it depends on what kind of object it is. If the object has neither a mesh renderer or a collider, it doesn't make sense to rotate it around a centre which is different from the actual position.
You can use either
Vector3 centrePoint = collider.bounds.center;
or
Vector3 centrePoint = renderer.bounds.center;
and then use
transform.RotateAround(centrePoint, Vector3.up, 90);
to rotate 90 degrees around the y axis.
Of course, a better way to do this would be to create a separate 'centre' transform at that centre point, then make it the parent object of your transform, then rotate that. Then, after having made the rotation, return it to its original parent and delete the centre object.
To have this functionality automatically, just put this in an empty .cs file somewhere in your project, then call it using
transform.RotateAroundCentre(some vector3);
public static class Utility
{
public static void RotateAroundCentre(this Transform trans, Vector3 rotation)
{
if(!trans.renderer && !trans.collider)
{
return;
}
Vector3 centre;
if(trans.renderer)
{
centre = trans.renderer.bounds.center;
} else {
centre = trans.collider.bounds.center;
}
Transform tempTrans = new GameObject("TempObj").transform;
tempTrans.position = centre;
Transform originalParent = trans.parent;
trans.parent = tempTrans;
tempTrans.Rotate(rotation);
trans.parent = originalParent;
GameObject.Destroy(tempTrans);
}
}
The first method did not work. I will try the second later. Thanks