Daniel
Daniel

Reputation: 7724

Predict transform position after rotation

I have a GameObject and some objects that are its children.

I'm gonna rotate this GameObject but I want to predict if any of his children will collide, so I can avoid rotating. For this, I need to predict the final position of each of the children before I actually rotate the parent.

I'm rotating the parent like this:

transform.Rotate(x, y, z, Space.World);

How can I predict the end position of each children after this rotation operation?

Upvotes: 3

Views: 1726

Answers (2)

rustyBucketBay
rustyBucketBay

Reputation: 4561

I can think of 3 options:

1.- You can create a set of empty game objects with the same hierarchy as the object you intend to rotate. The transform.Rotate(x, y, z, Space.World); applicated to this parallel gameobject would give each of the children positions. This is similar that rotating the original gameobject, but just handling a copy for your predictions, which does not seem very useful

2.- The other chance you have is to calculate yourself with matrix transformations the rotation transformation to all of the children in the hierarchy. Possible, but quite tough without the help of all the unity functions and automatic transformation along the hierarchy

3.- Transform.RotateAround rotates a point determined angle around a determiuned axis. For your determined children you can just with an empty gameobject at the same worlds position as the children gameobject you want to make your prediction with, calculate your rotation axis and rotate around the pivot point, that is the original gameobject's maximum parent in the hierarchy's world position. You can do that at once if you know your axis and your angle, or if you are rotating around the 3 axis as with transform.Rotate(x, y, z, Space.World); you can chain the 3 rotations with Transform.RotateAround applying the rotations of eulerAngles.z degrees around the z-axis, eulerAngles.x degrees around the x-axis, and eulerAngles.y degrees around the y-axis (in that order), as the Transform.Rotate does. The point of this is to rotate the empty gameobject yourself respect to the max parent position manually, imitating what would be done by the authomatic rotation by the hierarchy itself when the max parent gameObject is rotated.

Hope I made myself understood

Upvotes: 1

Daniel
Daniel

Reputation: 7724

I think I solved the problem. I used this function:

private Vector3Int RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) {
    returnQuaternion.Euler(angles) * (point - pivot) + pivot;
}

It apparently rotates a point around another in world space coordinates, so I passed the child position in point, the parent position in pivot and a new Vector3(x, y, z) in angles. The result seems to be the final position of the child after the rotation.

Upvotes: 3

Related Questions