How do i convert world direction to local direction?

133 views Asked by At

I have the world positions of two objects (A and B) and the rotation of A. How do i calculate the local direction from A to B from the perspective of A?

Position = x, y, z Rotation = x, y, z, w

I think the world direction should be:

dir = B  - A
magnitude = dir.magnitude()
direction = dir / magnitude

Not sure how local direction would work?

1

There are 1 answers

2
Paweł Łęgowski On

There are many ways to achieve that, you can use worldToLocalMatrix from GameObject A

var dir = A.transform.worldToLocalMatrix.MultiplyVector(dir);

or use Quaternions to calculate that manually like that:

var dir = Quaternion.Inverse(A.transform.rotation) * dir;

The results should be quite similar, except second way would ignore lossyScale (which is probably desired effect anyway)

I'm not sure what result Type are you expecting, as "direction" can be represented by either Vector3 forward or Quaterion rotation, but you can use

Quaternion.LookRotation(dir);

to convert from Vector3 to Quaterion and it should work fine most of the times