Java 2D - Drag the mouse to rotate the image smoothly

What is the logic that moves the rotation of the image through the movement of the mouse. I know how to rotate using graphics2d.rotate ... but it is difficult to do this with the mouse as a source of rotation. Here are the basic steps:

  • we get the mouse x (dx) and the distance y (dy) of the mouse from the anchor point (in this case it will be the center of the image that we want to rotate).
  • use this point in Math.arcTan2 (dy, dx) to get an angle or rotation.
  • use the value from step for the Graphics2D.rotate method.

With this strategy, every time I rotate the image, the image starts to rotate from -pi, and after 90 degrees of rotation it returns to -pi. I do not understand what I'm doing wrong here, it should be pretty simple.

Here is the piece of code:

// mouse dragged events get sent here.
public void mouseDragged( MouseEvent e ) {
    int mx = e.getX( ), my = e.getY( );
    // just checking if it falls within bounds of the image we 
    // want to rotate.
    if( mx > speedKX || mx < speedKX + speedK.getWidth( ) || my > speedKY || my < speedKY + speedK.getHeight( )/2 )
    {
        theta += getTheta( e.getX( ), e.getY( ) ); 
    }
} 
+3
1

, ( , ) ( ). ( ) .

, :

rotate(anglenow - angle0)

:

( ) , .

(getAngle (x1, y1, x2, y2). ( , x y, ) arctan (dy/dx).

dy/dx, :

+ / + -> +
+ / - -> -
- / + -> -
- / - -> +

. , - .

arctan doc , , ( 0 pi -pi/2 + pi/2), dx dy ( , arctan ) / pi .

getAngle, 360º.

Edit

:

Math.atan -pi/2 pi/2.

, , 0 X, , , , . , .

dx = xtarget - xorigin ( ), , , - .

, dy < 0, pi . -pi/2 3pi/2. , (-pi, pi) (0,2pi).

: , , !

onmousedown {
    startpoint = (x,y);
    startangle = getAngle(origin, startpoint);
}

onmousemove {
    currentpoint = (x,y);
    currentangle = getAngle(origin, currentpoint);
    originalimage.rotate(currentangle - startangle);
}

getAngle(origin, other) {
    dy = other.y - origin.y;
    dx = other.x - origin.x;
    if (dx == 0) // special case
        angle = dy >= 0? PI/2: -PI/2;
    else
    {
        angle = Math.atan(dy/dx);
        if (dx < 0) // hemisphere correction
            angle += PI;
    }
    // all between 0 and 2PI
    if (angle < 0) // between -PI/2 and 0
        angle += 2*PI;
    return angle;
}
+4

Source: https://habr.com/ru/post/1731339/


All Articles