# How do I find the angle between two vectors?

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?

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.

• +1 for the way you're rotating the frame of reference 90 degrees. – Steve H Apr 27 '12 at 12:39
• @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? – sam hocevar Apr 27 '12 at 13:17

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);