Tuesday, March 15, 2016

java - 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?



Answer



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.



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...