【问题标题】:C# Normalize (like a vector)C# 规范化(像一个向量)
【发布时间】:2012-04-18 04:40:12
【问题描述】:

我的移动对象中的代码:

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

实用功能:

    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
    }

我无法工作的扩展:

    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
    }

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

【问题讨论】:

  • PointF 实际上是 System.Drawing.PointF 还是别的什么?上面提到的PointF 没有SubStract 非静态方法,但它确实有Subtract 静态方法。
  • 对不起,我忘了说,这是我在PointF上的扩展方法。但它是一个真正的 PointF,就像在 System.Drawing 中一样。

标签: c# vector normalize


【解决方案1】:
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);
}

另请参阅第一段 here 了解什么是归一化向量(单位向量)以及如何计算它。

【讨论】:

  • 像魅力一样工作(顺便说一句,两个答案都有效)。请注意,您必须添加一个 float-cast 才能使其编译: (float)Math.Sqrt(..);
【解决方案2】:
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);
} 

【讨论】:

    猜你喜欢
    • 2015-01-10
    • 2019-12-19
    • 2016-06-04
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2016-06-18
    • 2013-01-15
    • 2020-01-16
    相关资源
    最近更新 更多