4
\$\begingroup\$

I am having a nightmare trying to make a child object rotate towards a given point of its parent object, similar to what is possible at the world level when using LookAt.

The problem is that most functions related to rotating in Unity do not work for local level. In the description of function transform.Rotate one can have the impression that it allows that, trough passing the Space.Self parameter. However, to use that function one has to know the 3 angles between the 2 points of interest. And there is no function that allows such calculation.

Anyone could please help implementing a local LookAt?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

This should do it:

void LookAtPointInParent(Vector3 parentSpacePoint)
{
    Vector3 parentSpaceDirection = parentSpacePoint - transform.localPosition;
    transform.localRotation = Quaternion.LookRotation(parentSpaceDirection);
}

If you want, you can add a second parameter to Quaternion.LookRotation() to control the roll of the object. For instance, you could use...

Vector3 localUp = transform.parent.InverseTransformDirection(Vector3.up);

to keep the object's up vector roughly aligned with the world up vector (y+) whenever possible (ie. when not looking directly up/down)

\$\endgroup\$
1
  • \$\begingroup\$ Superb! That solution together with Quaternion.Slerp made my day. Many thanks, sir. \$\endgroup\$
    – MAnd
    Sep 22, 2015 at 0:11
0
\$\begingroup\$

Assuming you know father position and local point position:

GameObject tmp = new GameObject("tmp"); //empty gameobject declared outside update() for performance

//inside update...
tmp.transform.position = new Vector3(fatherPos.x+localx
        , fatherPos.y+localy, fatherPos.z+localz);
transform.LookAt(tmp);
\$\endgroup\$
1
  • \$\begingroup\$ Many thanks for replying. However, it does not work. The main object that will be rotated becomes all twisted, altered in a bizarre way. Besides, per the logic of that solution, wouldn't it be better to directly position object " tmp" where object "local" is? Like tmp.transform.position = trasnform.TransformPoint(local.transform.position)? \$\endgroup\$
    – MAnd
    Sep 21, 2015 at 11:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .