简体   繁体   English

C# 归一化(如矢量)

[英]C# Normalize (like a vector)

Code in my moving object:我移动object中的代码:

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

Utility function:公用事业 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.请注意,我不使用 XNA 框架。

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.另请参阅此处的第一段以了解什么是归一化向量(单位向量)以及如何计算它。

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);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM