Search code examples
javamathjavafxrectanglesscene

Why it only rotates between 90 and -90?


In this code the rectangle always faces the cursor and everything is good. But, there is one problem that might not be visible when executing the code. what happens is, it rotates only between 90 and -90. It's good if I didn't add anything. But when I color it with 2 colors (lets say red and blue) if I move the cursor next to the rectangle from the right it faces the cursor from the red side but when moving in the other side it faces the cursor from the blue side.

double centerX = Rectangle.getX() + 0.5 * Rectangle.getWidth();
double centerY = Rectangle.getY() + 0.5 * Rectangle.getHeight();
Rectangle.setRotate(180 * Math.atan((e.getY() - centerY)/(e.getX() - centerX()));
}```

Solution

  • Just replace

    Math.atan((e.getY() - centerY)/(e.getX() - centerX())
    

    with

    Math.atan2((e.getY() - centerY), (e.getX() - centerX())