0
$\begingroup$

I am writing some code and want to select a calculation to do based on "how much" of a direction vector is in the X and Z axis (which are the planar axes in Unity). If more of the direction vector is along the X axis, I want to compute Y(X); but if more of the vector is along the Z axis, I want to compute Y(Z). I am hopeful that doing this will avoid undefined behavior when the curve is entirely (or almost entirely) parallel to the XY plane or ZY plane. Here is what I wrote:

// Vector3.right is the x-axis
if (Mathf.Abs(Vector3.Dot(direction,Vector3.right)) >= Mathf.Sqrt(2f) )
{
    //Calculate Y(x)
}
else
{
    //Calculate Y(z)
}

Is this logical? In this situation, would the dot product always be greater than or equal to $\sqrt{2}$ with respect to either the X or Z axis? That is the question.

$\endgroup$
1
$\begingroup$

In Mathematica:

If[Abs[#[[1]]]>Abs[#[[2]]],f[#],g[#]]&

You simply look at the $x$ component (#[[1]]) and the $y$ (#[[2]]) component of the vector and see which is larger.

$\endgroup$
  • $\begingroup$ Ah... Duh. Thanks. Changed to if (Mathf.Abs(direction.x) >= Mathf.Abs(direction.z) ){// calculate Y(X);} else {// calculate Y(Z);}. What you are suggesting is better because it is faster, less overhead, and avoids rounding error. Also, obvious. $\endgroup$ – hatinacat2000 Jan 5 at 1:55
  • $\begingroup$ Speed on such a trivial problem is irrelevant. The difference between the fastest algorithm and the slowest algorithm is less than the time it takes between two crests of a sound wave to pass into your ear. $\endgroup$ – David G. Stork Jan 5 at 4:06
  • $\begingroup$ Yes, thank you, I get that $\endgroup$ – hatinacat2000 Jan 6 at 1:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.