识别顺时针或逆时针旋转

时间:2016-01-14 17:36:56

标签: rotation linear-algebra game-physics

我必须确定用户是进行顺时针旋转手势还是逆时针旋转手势。我已经启动了Vector位置以及当前和之前的触摸。虽然我认为起始矢量不是很有用,因为如果用户也可以在两者之间改变旋转。也就是说他可以改变从顺时针到逆时针的旋转。就像旋转x-box的d-pad一样。 对于想法的现场演示,就像Dead Trigger 2开发者所做的那样,没有屏幕按钮只是使用手势在屏幕上旋转。  我如何识别它?

1 个答案:

答案 0 :(得分:2)

要确定2D输入是顺时针还是逆时针旋转,请从旋转原点找到两个矢量的叉积,看它是负还是正。一个向量来自前一个输入,另一个向量来自当前输入。

在伪代码中。

centerX = screenCenterX;  // point user is rotating around
centerY = screenCenterY;
inputX = getUserX();   // gets X and Y input coords
inputY = getUserY();   //
lastVecX = inputX - centerX;  // the previous user input vector x,y
lastVecY = inputY - centerY;  //      

while(true){ // loop 
    inputX = getUserX();  // gets X and Y input coords
    inputY = getUserY();  //

    vecInX = inputX - centerX;  // get the vector from center to input
    vecInY = inputY - centerY;  // 

    // now get the cross product
    cross = lastVecX * vecInY - lastVecY * vecInX;

    if(cross > 0) then rotation is clockwise
    if(cross < 0) then rotation is anticlockwise
    if(cross == 0) then there is no rotation

    lastVecX = vecInX;  // save the current input vector
    lastVecY = vecInY;  // 
} // Loop until the cows come home.

为了得到你需要的角度来规范化矢量,然后交叉积是角度变化的罪。

在伪代码中

vecInX = inputX - centerX;  // get the vector from center to input
vecInY = inputY - centerY;  // 

// normalized input Vector by getting its length
length = sqrt(vecInX * vecInX + vecInY * vecInY);

// divide the vector by its length
vecInX /= length;
vecInY /= length;

// input vector is now normalised. IE it has a unit length

// now get the cross product
cross = lastVecX * vecInY - lastVecY * vecInX;

// Because the vectors are normalised the cross product will be in a range
// of -1 to 1 with < 0 anticlockwise and > 0 clockwise

changeInAngle = asin(cross);  // get the change in angle since last input
absoluteAngle += changeInAngle; // track the absolute angle

lastVecX = vecInX;  // save the current normalised input vector
lastVecY = vecInY;  //       
// loop