How do I position C gameObject
such that it forms a right angled triangle with A and B
. I tried to use (B.transform.position.x,A.transform.position.z)
but it still gives me something which is close to A
(it takes it globally). I want the C
to be along the local red axis of A
and local green axis of B
as seen in the picture. What do I do?
-
\$\begingroup\$ The problem as you've described it is over-constrained. Of the three criteria {on the local red axis through A, on the local green axis through B, forming a right-angled triangle with A and B}, two suffice to uniquely specify the point, and all three together can result in no solution if the orientation of A & B do not match. Would picking just two of these criteria suffice for your needs? \$\endgroup\$– DMGregory ♦Commented Jul 21, 2019 at 21:49
-
\$\begingroup\$ @DMGregory Thanks, yeah never thought about it! Picking just two criteria would be good! \$\endgroup\$– MrRobot9Commented Jul 21, 2019 at 21:51
-
\$\begingroup\$ @DMGregory But which two would be good so that I can get close to that point if not exact? \$\endgroup\$– MrRobot9Commented Jul 21, 2019 at 21:54
-
\$\begingroup\$ I would ignore B's rotation entirely. \$\endgroup\$– Draco18s no longer trusts SECommented Jul 21, 2019 at 22:50
-
1\$\begingroup\$ The angle at C is required to be a right angle. The angle at A is fixed. A little SOHCAHTOA will get you the rest. \$\endgroup\$– Draco18s no longer trusts SECommented Jul 21, 2019 at 23:35
1 Answer
Taking these two constraints:
- "position C gameObject such that it forms a right angled triangle with A and B"
- "I want the C to be along the local red axis of A"
We can solve this relatively easily using A's transformation:
// Transform point B into A's local space.
Vector3 bInAsSpace = a.transform.InverseTransformPoint(b.transform.position);
// Find a position along A's x-axis (y = z = 0 in A's local coordinates)
// that matches B's x-coordinate when viewed from A's frame of reference.
Vector3 cInAsSpace = new Vector3(bInAsSpace.x, 0, 0);
// Transform this position from A's local space back to world space.
Vector3 cInWordSpace = a.transform.TransformPoint(cInAsSpace);
This is guaranteed to be along A's x-axis (the red axis), since its y & z position in A's local space are both zero.
It's guaranteed to form a right-angled triangle with A & B because it forms a right triangle in A's local space (its separation from A is purely along the x-axis, and its separation from B has an x component of zero), and Unity transforms don't include shear.