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

2022-08-31 16:16:05

我目前正在为Android开发一个简单的2D游戏。我有一个位于屏幕中心的静止对象,我正在尝试让该对象旋转并指向屏幕上用户触摸的区域。我有表示屏幕中心的常量坐标,我可以获取用户点击的点的坐标。我使用的是这个论坛中概述的公式:如何获得两点之间的角度?

  • 它说如下:“如果你想要由这两个点定义的线和水平轴之间的角度:

    double angle = atan2(y2 - y1, x2 - x1) * 180 / PI;".
    
  • 我实现了这一点,但我认为我在屏幕坐标中工作的事实导致了计算错误,因为Y坐标是相反的。我不确定这是否是正确的方法,任何其他想法或建议都值得赞赏。


答案 1

假设:是水平轴,从左向右移动时增加。 是垂直轴,并从下到上增加。 是用户选择的点。 是屏幕中心的点。 从轴逆时针方向测量。然后:xy(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

但是,将其描述为以相对于 的极坐标表示会更正确。正如ChrisF所提到的,“在两点之间取一个角度”的想法没有得到很好的定义。(touch_x, touch_y)(center_x, center_y)


答案 2

我自己需要类似的功能,所以经过多次拉扯后,我想出了下面的功能

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

推荐