如何找到两个向量之间的夹角?


9

我的屏幕上有3分:

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     |
|______._______|

我画了一些线,以便您可以看到向量。

我希望能够获得a和b之间的角度。我已经尝试过了,但是没有用,有人知道我在做什么错吗?:

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

我通常得到的答案是0到1。如何解决这个问题,以便获得角度(以度为单位)?

Answers:


16

您正在寻找奇妙的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);

通常,它用作,atan2(y,x)但由于您要查找与垂直线的夹角,因此需要使用它atan2(-x,y)


+1将参考框架旋转90度。
史蒂夫·H

@PoiXen对不起,我在公式中混淆了v1和v2;我现在修复了它,但是它真的真的为您第一次工作了吗?
sam hocevar 2012年

2

我看到您使用的是点积,请尝试invcos(value)可以完成此操作(但不确定)。

否则,请使用atan2(dy / dx)以“常规”方式进行操作:

b=b-c:
angle=atan2(b.y, b.x);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.