Vector Projection with zero length

Started by
11 comments, last by nowzer 10 years, 8 months ago

That code is more robust, assuming division by 0 doesn't trigger an exception or anything (sorry, I don't know Java or whatever that language you are using is).

But I still wonder why you are projecting onto a vector that is not roughly unit length.

Advertisement

I want to point out that the code in the OP is not very robust: If the input is the vector (0, epsilon) --where epsilon is a number so small that its square is 0--, the code will still divide by zero.

How about this then?


        public static Vector2 Project(this Vector2 A, Vector2 B)
        {
            float DotOverDot = Vector2.Dot(A, B) / Vector2.Dot(A, A);
            if (float.IsNaN(DotOverDot) || float.IsInfinity(DotOverDot))
                return Vector2.Zero;
            else
                return Vector2.Multiply(A, DotOverDot);                
        }

The typical way of handling this would be,


float sqrA = Vector2.Dot(A, A);
if(sqrA < epsilon)
{
    return Vector2.Zero;
}

return Vector2.Multiply(A, Vector2.Dot(A, B) / sqrA));

where 'epsilon' is a tolerance that you choose.

-Josh

--www.physicaluncertainty.com
--linkedin
--irc.freenode.net#gdnet

... and I was going to say null until I saw Josh's answer...

This topic is closed to new replies.

Advertisement