【问题标题】:2D orbit increasing over time2D 轨道随时间增加
【发布时间】:2014-09-03 15:35:32
【问题描述】:

我有一种方法可以让一个精灵(舰队)围绕另一个精灵(行星)运行。问题是,随着时间的推移,舰队会移动得更远(非常缓慢,除非你让轨道运行几分钟,否则几乎不会被注意到)。

public void Orbit()
{
    // Planet's position - fleet position
    Vector2 distanceToDestination = currentLocation.Position - position;

    // Calculate fleet's rotation ( - right angle so fleet rotates clockwise)
    rotation = MathHelper.WrapAngle((float)Math.Atan2(distanceToDestination.Y, distanceToDestination.X)) - Helpers.RightAngle;

    // Get the direction that the fleet is facing
    direction = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation));

    // Fleet position, thrust is set to 0.4f
    position = Vector2.Add(position, direction * thrust);

    // Fleet rectangle
    rect = new Rectangle((int)position.X, (int)position.Y, fleetTexture.Width, fleetTexture.Height);
}

public static class Helpers
{
    public const float RightAngle = (float)Math.PI / 2;
}

如果社区能指出为什么我的舰队没有保持一致的轨道,我将不胜感激,这正是我想要实现的!非常感谢。

【问题讨论】:

  • 感谢两位出色的回答。 @dbc - 我选择了您的答案,因为我使用了您发布的方法的变体。再次感谢。

标签: c# math .net-4.0 xna


【解决方案1】:

如果我理解您在做什么,您正在尝试使用类似于汽车绕圈行驶的模型来模拟轨道物理(即,您不是在模拟垂直于当前速度的重力加速度和@ 987654321@)。相反,您正在这样做:

  1. 垂直于半径r的圆心移动少量d
  2. 重新调整方向,使“汽车”仍然垂直于圆心。
  3. 重复。

现在,在每一步之后,您的对象离圆心有多远?嗯,根据勾股定理,它是sqrt(r*r + d*d),它将比r 稍大。对d 使用非常大的值来强调:

这应该说明你的漂移。

顺便说一句,您不需要使用三角函数来构造与 distanceToDestination 的垂直线。简单地将其与 ±Z 向量相交会容易得多,结果将是(在 2d 中)±(-distanceToDestination.Y, distanceToDestination.X)

更新:既然你并没有真正模拟轨道物理,为什么不分析地解决这个问题?

    public static Vector2 Orbit(Vector2 center, Vector2 startPos, float speed, float time)
    {
        // positive speed means CCW around the center, negative means CW.
        var radiusVec = (startPos - center);
        var radius = radiusVec.Length();
        var angularVelocity = speed / radius; // Add check for divide by zero
        Vector2 perpendicularVec = new Vector2(-radiusVec.Y, radiusVec.X);
        return center + (float)Math.Cos(time * angularVelocity) * radiusVec + (float)Math.Sin(time * angularVelocity) * perpendicularVec;
    }

【讨论】:

    【解决方案2】:

    这是你正在计算的:

    要获得轨道中的下一个点,您必须保持矢量长度。

    所以你的计算应该是:

    // Planet's position - fleet position
    Vector2 distanceToDestination = currentLocation.Position - position;
    
    // Calculate fleet's rotation ( - right angle so fleet rotates clockwise)
    rotation = MathHelper.WrapAngle((float)Math.Atan2(distanceToDestination.Y, distanceToDestination.X));
    rotation -= Helpers.RightAngle;
    
    // Get the direction that the fleet is facing
    direction = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation));
    direction *= distanceToDestination.Length;
    
    position = currentLocation.Position - direction;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      相关资源
      最近更新 更多