This site requires JavaScript, please enable it in your browser!
Greenfoot back
MrEvans
MrEvans wrote ...

2016/11/3

Mouse press-and-drag rotation of actors.

MrEvans MrEvans

2016/11/3

#
I have been trying all sorts of ways to get an actor to rotate by clicking-&-dragging on them, with their rotation stopping when the mouse button is released. I can get the actor to rotate following the mouse movement without mouse clicks, but can't get this to only happen when the mouse button is held down - it rotates immediately to the position the mouse was clicked at and stays there until the next click. Here is my code at the moment. public class Mirror extends Actor { public int state = 0; public void act() { MouseInfo mouse = Greenfoot.getMouseInfo(); if (Greenfoot.mousePressed(this)) { state = 1; } else { state = 0; } } public void rotate() { if (state == 1){ MouseInfo mouse = Greenfoot.getMouseInfo(); if (mouse != null) { setRotation((int)(180*Math.atan2(mouse.getY()-getY(),mouse.getX()-getX())/Math.PI)); } } } } Any help would be appreciated!
danpost danpost

2016/11/3

#
The Greenfoot class method 'mousePressed' only returns true when a mouse button goes from an unpressed state to a pressed state. It does not return true if there is no change in the state of a button. Therefore, your 'else' block needs to be removed and you need to use another set of conditions for detecting when the state is changed back:
if (Greenfoot.mouseClicked(null))
would work by itself, if you are okay with the possibility that it could be the other mouse button that is released.
if (Greenfoot.mouseClicked(this) || Greenfoot.mouseDragEnded(this))
will probably work better.
You need to login to post a reply.