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

2011/5/25

Dragging

ClemeC ClemeC

2011/5/25

#
Hi, I am trying to create an actor which would follow the mouse wherever it goes. It should be able to do so with and without the left button pressed down. The code I used was:
1
2
3
4
5
if(Greenfoot.mouseMoved(null))
{
MouseInfo mouse = Greenfoot.getMouseInfo();
setLocation(mouse.getX(), mouse.getY());
}
However, the code only worked when the left button is not pressed down. What are the problems and how can I fix them?
davmac davmac

2011/5/25

#
Same problem as in this post: mouse cursor Basically, the mouse either "moves" or "drags" but not both at the same time. So you can check each separately:
1
2
if (Greenfoot.mouseMoved(null) || Greenfoot.mouseDragged(null)) {
    ....
... or use the solution from the other discussion.
Builderboy2005 Builderboy2005

2011/5/25

#
Whenever I make a scenario that has mouse based control, I always do something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int mouseX,mouseY;
boolean mousePressed;
 
MouseInfo mouse = Greenfoot.getMouseInfo();
if(mouse!=null){
    mouseX = mouse.getX();
    mouseY = mouse.getY();
}
if(Greenfoot.mousePressed(null)){
    mousePressed = true;
}
if(Greenfoot.mouseClicked(null)){
    mousePressed = false;
}
That way I always have my mouse position value and button status in easy to access variables. I never understood why MouseInfo becomes null whenever the mouse does not move or do anything, wouldn't it be a lot more useful for it to just stay in existence so that we don't have to manually keep track of its location?
You need to login to post a reply.