Unity rotating parent so that child's position matches with point

48 views Asked by At

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.

2

There are 2 answers

1
anjelomerte On BEST ANSWER

Assuming you have properties assigned for:

Transform parentP;      // Parent transform
Transform childC;       // Child transform
Transform randomPointK; // Random point transform

You can call the following function RotateToClosest to 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:

void RotateParentToClosest()
{
    // Calculate vectors from parent to child and from parent to random point
    Vector3 toChild = childC.position - parentP.position;
    Vector3 toRandomPoint = randomPointK.position - parentP.position;

    // Calculate the rotation to align toChild with toRandomPoint vectors
    Quaternion desiredRotation = Quaternion.FromToRotation(toChild, toRandomPoint);

    // Apply the rotation to the parent
    parentP.rotation = desiredRotation * parentP.rotation;
}
0
hijinxbassist 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.