Calculating the angle between the line defined by two points

前端 未结 6 1158
我在风中等你
我在风中等你 2020-11-28 08:17

I\'m currently developing a simple 2D game for Android. I have a stationary object that\'s situated in the center of the screen and I\'m trying to get that object to rotate

6条回答
  •  無奈伤痛
    2020-11-28 08:33

    Assumptions: x is the horizontal axis, and increases when moving from left to right. y is the vertical axis, and increases from bottom to top. (touch_x, touch_y) is the point selected by the user. (center_x, center_y) is the point at the center of the screen. theta is measured counter-clockwise from the +x axis. Then:

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

    Edit: you mentioned in a comment that y increases from top to bottom. In that case,

    delta_y = center_y - touch_y
    

    But it would be more correct to describe this as expressing (touch_x, touch_y) in polar coordinates relative to (center_x, center_y). As ChrisF mentioned, the idea of taking an "angle between two points" is not well defined.

提交回复
热议问题