Vector-angle helper methods

Topics: User Forum
Aug 15, 2009 at 4:01 PM

Hey, I created these because sometimes with vectors it's just nicer to work with length and angle as opposed to horizontal and vertical distance. Feel free to use these, or provide a better implementation if you have one. Note that the first method is currently an "extension method" (the this keyword in the parameter), and can be used in this manner:

 float? a = v.GetAngle();

/// <summary>
/// Returns the angle of the vector in radians using the standard
/// polar coordinate system, or null if the vector's length is 0.
/// Assumes the vector is on a grid where x increases to the left 
/// and y increases downward.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public static float? GetAngle(this Vector2 v)
{
    if (v.X == 0)
        if (v.Y == 0)
            return null;
        else
            return MathHelper.PiOver2 * (v.Y<0?1:-1);
    else
        return MathHelper.WrapAngle((float) (Math.Atan(-v.Y / v.X) + ((v.X<0)?Math.PI:0)));
}

/// <summary>
/// Returns a new Vector2 object specified by angle and length using
/// the standard polar coordinate system.
/// </summary>
/// <param name="angle">The direction of the Vector2 in radians.</param>
/// <param name="length">The magnitude of the Vector2.</param>
/// <returns></returns>
public static Vector2 CreateVector2(float angle, float length)
{
    return new Vector2((float)Math.Cos(angle) * length, (float)Math.Sin(-angle) * length);
}
Coordinator
Aug 15, 2009 at 11:29 PM

Thanks Cowdozer. If you ever want to share something big that does not fit on the forums or you would like to be included in the engine, you can use our patch section.

Keep up the good work.

Aug 16, 2009 at 2:46 AM

Cool, so that's how it's done! I was just looking to see where it might make sense to put this, and found Mathematics.Calculator, which does have some methods (VectorToRadians and RadiansToVector) that do pretty much the same thing. Two differences are:

1. my equivalent of VectorToRadians returns null if you give it Vector2.Zero (whereas the Calculator one will return 0 radians--not always the best thing to do, but probably fine).

2. the Calculator ones, when used with a downward-increasing y-axis (like with graphics) treat polar coordinates as going CW (just a case of a sign change).

It's debatable as to which is more desirable in the general case. I'll let you (or anyone who wishes to comment) decide if I should submit a patch for this. I'm leaning towards a no.

I'm going to post another bit of code in another thread... it's maybe a little long to do that, but I'd like to hear if people think it is desirable enough to include in farseer, and it might also be nice to leave it public for people to find through google.