Napoleon
Napoleon

Reputation: 1102

C# Normalize (like a vector)

Code in my moving object:

ObjectX.Location.Add(Velocity * Utils.GetMoveDir(start, destination));

Utility function:

public static PointF GetMoveDir(PointF start, PointF destination)
{
    PointF substraction = destination.SubStract(start);

    if (substraction == PointF.Empty) // If-statement is needed because normalizing a zero value results in a NaN value
         return PointF.Empty;
    else return substraction.Normalize(); // I need something for this
}

The extension I can't get to work:

public static PointF Normalize(this PointF A)
{
    throw new NotImplementedException(); // How do I solve this to make it like: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector2.normalize.aspx
}

Note that I do NOT use the XNA framework.

Upvotes: 2

Views: 16600

Answers (2)

Henrik
Henrik

Reputation: 23324

public static PointF Normalize(this PointF A)
{
    float length = Math.Sqrt( A.X*A.X + A.Y*A.Y);
    return new PointF( A.X/length, A.Y/length);
} 

Upvotes: 4

Jesse van Assen
Jesse van Assen

Reputation: 2290

public static PointF Normalize(this PointF A)
{
    float distance = Math.Sqrt(A.X * A.X + A.Y * A.Y);
    return new PointF(A.X / distance, A.Y / distance);
}

Also see the first paragraph here to learn what a normalized vector (unit vector) is and how you can calculate it.

Upvotes: 14

Related Questions