Let say there is a transform called P, its child called C and a random point on a world called K. I want to rotate P so that C's position became equal or closest to K. How can i do it? I searched Quaternions, LookAt, Inverse etc. but didnt make it.
Unity rotating parent so that child's position matches with point
48 views Asked by Uur Kn At
2
There are 2 answers
0
On
First get the directions from parent to child and from parent to other object.
Once you have those 2 direction vectors, get the signed angle between them.
This angle is the amount you need to rotate the parent by.
var childDirection = (child.position - transform.position);
var otherDirection = (other.position - transform.position);
var angle = Vector3.SignedAngle(childDirection, otherDirection, Vector3.up);
transform.Rotate(new Vector3(0, angle, 0));
The above assumes you are rotating around the up axis. You can change the axis by replacing the axis parameter in the SignedAngle function, and changing the rotation vector component.
Assuming you have properties assigned for:
You can call the following function
RotateToClosestto rotate the parent so that the child is closest to the random point. Rotation is independent of any axis and can be applied immediately since we are using Quaternions: