Scenario:
- Parent P1 has Child C1
- Target exists
- All items' forward vectors face perfectly parallel to the X-Z Plane (pseudo 2D)
- Positions of all objects are arbitrary
- Child will never move on its own within Parent's space
Goal:
Rotate P1 exclusively about the Y-Axis to have C1 Face the opposite direction of target's forward vector
Note: Y-Axis Positive would face reader, Negative would go into screen
Implementation:
P1.rotation = Quaternion.LookRotation(-target.forward) * Quaternion.Euler(0, -C1.localEulerAngles.y, 0);
The above seems to work most of the time but breaks randomly and sometimes generates a Zero Vector as the forward. I am inexperienced with Euler Angles and Quaternions so my apologies in advance.
CodePudding user response:
Using some quaternion algebra:
Given this in Unity terms/c#:
Desired child world = Quaternion.LookRotation(-target.forward)
Given:
Desired child world = desired parent world * child local
Multiply on right of both sides:
Desired child world * inverse(child local) = desired parent world * child local
* inverse(child local)
= desired parent world
Substituting and expressing using Unity/C#, you get:
P1.rotation = Quaternion.LookRotation(-target.forward)
* Quaternion.Inverse(C1.localRotation);
CodePudding user response:
A simple way of representing this transform would be the targets rotation plus 180 degrees about the up axis, and that can be expressed as follows:
P1.rotation = target.rotation * Quaternion.AngleAxis(180, Vector3.up);
Note that order does matter, particularly if it is being used in 3D space at all (it would work all the same if the forward vectors are on the same plane in 2D).
Here's how it looks: