Good afternoon guys, I'm trying to rotate an polygon based on my mouse position, but I can't figure out how to rotate the polygon upwards based on my mouse y. I'm using MouseMotionListener. I've tried to do this until now:
public void mouseMoved(MouseEvent m){
int yantes= m.getY();
while (true){
int y = m.getY();
repaint();
if (y - yantes > 0){
rotation++;
if (rotation > 360) rotation = 0;
repaint();
break;
} else {
rotation--;
if (rotation < 0) rotation = 359;
repaint();
break;
}
}
}
The yantes variable tries to calculate the y before the move, and y the y in after the movement.
In your comment, you wrote:
Are you referring to the book Beginning Java SE 6 Game Programming, Third Edition ?
A java applet is a Container and so is a JPanel, so you can achieve the same results by extending class
JPanelrather than extendingApplet. That means you can write a regular java application without the need for HTML or a Web browser.Instead of overriding method
paint()inApplet, you need to override methodpaintComponent()in classJPanel.The below code demonstrates rotating a square by moving the mouse. It rotates the square around the center point of the square. When you place the mouse inside the
JPaneland move it to the left, the square rotates anti-clockwise. When you move the mouse to the right, the square rotates clockwise. If you move the mouse up and down, i.e. parallel to the y-axis, the square does not rotate.Note that when overriding method
paintComponent()you nearly always need to first call methodpaintComponent()in the super class.