计算直线与 x 轴之间的角度

新手上路,请多包涵

我目前正在为 Android 开发一个简单的 2D 游戏。我有一个位于屏幕中央的静止物体,我试图让该物体旋转并指向用户触摸的屏幕区域。我有代表屏幕中心的常量坐标,我可以获得用户点击的点的坐标。我正在使用本论坛中概述的公式: How to get angle between two points?

  • 它说如下“如果你想要由这两点定义的线与水平轴之间的角度:
   double angle = atan2(y2 - y1, x2 - x1) * 180 / PI;".

  • 我实现了这个,但我认为我在屏幕坐标中工作的事实导致计算错误,因为 Y 坐标是相反的。我不确定这是否是正确的方法,如有任何其他想法或建议,我们将不胜感激。

原文由 kingrichard2005 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 626
2 个回答

假设: x 为横轴,从左向右移动时递增。 y 为纵轴,从下往上递增。 (touch_x, touch_y) 是用户选择的点。 (center_x, center_y) 是屏幕中心的点。 theta+x 轴逆时针测量。然后:

 delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)

编辑:您在评论中提到 y 从上到下增加。在这种情况下,

 delta_y = center_y - touch_y

但是将其描述为在相对于 (center_x, center_y) (touch_x, touch_y) 会更正确。正如 ChrisF 所提到的,采用“两点之间的角度”的想法没有明确定义。

原文由 Jim Lewis 发布,翻译遵循 CC BY-SA 2.5 许可协议

我自己也需要类似的功能,所以经过一番努力,我想出了下面的功能

/**
 * Fetches angle relative to screen centre point
 * where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
 *
 * @param screenPoint
 * @return angle in degress from 0-360.
 */
public double getAngle(Point screenPoint) {
    double dx = screenPoint.getX() - mCentreX;
    // Minus to correct for coord re-mapping
    double dy = -(screenPoint.getY() - mCentreY);

    double inRads = Math.atan2(dy, dx);

    // We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
    if (inRads < 0)
        inRads = Math.abs(inRads);
    else
        inRads = 2 * Math.PI - inRads;

    return Math.toDegrees(inRads);
}

原文由 Dave Discoid 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题