编程中的数学:关于点之间旋转角度的三角学

时间:2014-04-28 08:37:43

标签: android math trigonometry angle

我有一个问题,就是用鼠标指针找到三个点的角度。当鼠标在旋转物体周围移动时,旋转不会跟随鼠标。

这是我的公式:

double degree = Math.toDegrees( Math.atan2(
                 (now.y - point.y) - (previous.y - point.y),
                 (now.x - point.x) - (previous.x - point.x)));

         Log.w("RESULT", "DEGREE = " + degree);
        if ( degree < 0 )
          degree = 360 - (-degree);

最后两行后来被添加。

这是跟踪鼠标旋转的完整代码。

相机相机= Camera.getInstance();

     if (event.getActionMasked() == MotionEvent.ACTION_DOWN &&
         event.getPointerCount() == 1) {
         previous = new Point(event.getX(), event.getY());
         previous = camera.getMapPoint(previous);

     }
     else if (event.getActionMasked() == MotionEvent.ACTION_MOVE && 
         event.getPointerCount() == 1) 
     {  
         Point now = new Point(event.getX(), event.getY());
         now = camera.getMapPoint(now);

         ArrayList<GameObject> list = mObject.getSubObjects();
         GameObject part = list.get(0);
         Point point = part.getPolygon().getCenter();

         Log.w("RESULT", "Previous = " + previous.x + " " + previous.y);
         Log.w("RESULT", "Next = " + now.x + " " + now.y);
         Log.w("RESULT", "Center = " + point.x + " " + now.y);

         double degree = Math.toDegrees( Math.atan2(
                 (now.y - point.y) - (previous.y - point.y),
                 (now.x - point.x) - (previous.x - point.x)));

         Log.w("RESULT", "DEGREE = " + degree);
        if ( degree < 0 )
          degree = 360 - (-degree);


         android.graphics.Matrix matrix = new android.graphics.Matrix();
         matrix.postRotate((float) degree, point.x, point.y);


        // Polygon polygon;
        // Polygon.Builder builder = new Polygon.Builder();
         for (int i=0; i<part.getPolygon().getVertex().size(); i++) 
         {
             float[] newPoint = new float[2];
             Point p = part.getPolygon().getVertex().get(i);
             newPoint[0] = p.x;
             newPoint[1] = p.y;

             matrix.mapPoints(newPoint); 
             part.getPolygon().getVertex().remove(i);
             part.getPolygon().getVertex().add(i, new Point(newPoint[0], newPoint[1]));

         } 
         previous = new Point(event.getX(), event.getY());
         previous = camera.getMapPoint(previous);
     }
     else if (event.getActionMasked() == MotionEvent.ACTION_UP)
     {
        previous = null; 
        isSelected = false;
     }

1 个答案:

答案 0 :(得分:2)

如果要在矢量(前一点)和(现在点)之间找到角度,请使用:

 Math.atan2((now.x - point.x)*(previous.y - point.y) - 
           (now.y - point.y)*(previous.x - point.x), 
           (now.x - point.x)*(now.y - point.y) - 
           (previous.x - point.x)*(previous.y - point.y))

(这是atan2(vectorproduct, scalarproduct)

您也可以使用

angle = atan2(now.y-point.y, now.y-point.y)-
        atan2(previous.y-point.y, previous.x-point.x);