views:

291

answers:

2

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 and point to the area on the screen that the user touches. I have the constant coordinates that represent the center of the screen and I can get the coordinates of the point that the user taps on. I'm using the formula outlined in this forum: How to get angle between two points?

-It says as follows "If you want the the angle between the line defined by these two points and the horizontal axis: double angle = atan2(y2 - y1, x2 - x1) * 180 / PI;".
-I implemented this, but I think the fact the I'm working in screen coordinates is causing a miscalculation, since the Y-coordinate is reversed. I'm not sure if this is the right way to go about it, any other thoughts or suggestions are appreciated.

A: 

If you think the y coordinate is reversed just negate the value(s). Does the answer make more sense?

ChrisF
I tried that, but didn't seem to work. What I mean is that, the origin is at the top-left of the screen and the Y-Coordinate increases going down, while the X-Coordinate increases to the right like normal. I guess my question becomes, do I have to convert the screen coordinates to Cartesian coordinates before applying the above formula?
kingrichard2005
@kingrichard2005 - if negating the y doesn't work try doing `yMax - y`.
ChrisF
+1  A: 

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.

Jim Lewis
Thanks Jim, whether I'm using Cartesian or polar coordinates, how would I know if the calculated angle is based on the horizontal line that cuts through my object and not the horizontal at the top of the screen, which is coming out of the origin at the top-left??
kingrichard2005
@kingrichard2005: Since delta_x and delta_y are calculated with respect to the center point (the location of your object), thetawill also be calculated with respect to the same point.
Jim Lewis
Thanks for the help Jim.
kingrichard2005