C#Normalize(像向量)

Nap*_*eon 0 c# vector normalize

移动物体中的代码:

ObjectX.Location.Add(Velocity * Utils.GetMoveDir(start, destination));
Run Code Online (Sandbox Code Playgroud)

实用功能:

    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
    }
Run Code Online (Sandbox Code Playgroud)

扩展我无法工作:

    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
    }
Run Code Online (Sandbox Code Playgroud)

请注意,我不使用XNA框架.

Jes*_*sen 12

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);
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此处的第一段,了解规范化向量(单位向量)是什么以及如何计算它.


Hen*_*rik 5

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);
} 
Run Code Online (Sandbox Code Playgroud)