9
\$\begingroup\$

I have 3 points on my screen:

a = a point which is (c.x, 0) makes a line pointing straight up
b = a user input touch, can be anywhere on the screen
c = a moving object

       a
_______.________
|      |       |
|      |       | 
|   b  |       |
|  .   |       |
|   \  |       |
|    \ |       | 
|     \|       |
|      | c     |
|______._______|

I have drawn some lines so that you can see the vectors.

I want to be able to get the angle between a and b. I have tried this, but it doesn't work, does anyone know what I'm doing wrong?:

//v1 moving object
float boxX = this.mScene.getLastChild().getX(); 
float boxY = this.mScene.getLastChild().getY();

//v2 user touch
float touchX = pSceneTouchEvent.getX();
float touchY = pSceneTouchEvent.getY();     

//v3 top of screen
float topX = boxX;
final float topY = 0;

float dotProd = (touchX * topX) + (touchY * topY);

float sqrtBox = (touchX * touchX) + (touchY * touchY);
float sqrtTouch = (topX * topX) + (topY * topY);

double totalSqrt = sqrtBox * sqrtTouch;
double theta = Math.acos(dotProd / Math.sqrt(totalSqrt));

The answer I usually get is between 0 and 1. How do I fix this so that I get the angle in degrees?

\$\endgroup\$

2 Answers 2

16
\$\begingroup\$

You are looking for the wondrous atan2.

// v1 moving object
float boxX = this.mScene.getLastChild().getX(); 
float boxY = this.mScene.getLastChild().getY();

// v2 user touch
float touchX = pSceneTouchEvent.getX();
float touchY = pSceneTouchEvent.getY();     

double theta = 180.0 / Math.PI * Math.atan2(boxX - touchX, touchY - boxY);

Normally it is used as atan2(y,x) but since you are looking for the angle with the vertical line, you need to use atan2(-x,y) instead.

\$\endgroup\$
2
  • \$\begingroup\$ +1 for the way you're rotating the frame of reference 90 degrees. \$\endgroup\$
    – Steve H
    Apr 27, 2012 at 12:39
  • \$\begingroup\$ @PoiXen sorry, I had confused v1 and v2 in the formula; I now fixed it but did it really work for you the first time? \$\endgroup\$ Apr 27, 2012 at 13:17
2
\$\begingroup\$

I see you use dot product, try invcos(value) it might do the thing (but not sure).

Otherwise just do it the 'regular' way with atan2(dy/dx):

b=b-c:
angle=atan2(b.y, b.x);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .