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

2016/12/12

MouseInfo.getButton() only displays the button being held if the cursor is moving?

TypoKign TypoKign

2016/12/12

#
While debugging an issue, I decided to run this test code in the act() method of an object in the world:
1
2
3
mi = Greenfoot.getMouseInfo(); // repoll the mouse every tick
         
        if (mi != null) { System.out.println(mi.getButton()); }
Running the program and terminal side by side, I noticed that the terminal was flooded with zeros even if I held the mouse button, and would only display a "1" if the mouse was moving while the button was held. What is the best practice for determining if the button is being held (note: anywhere in the world, so mouseDragged(Actor actor) does not fulfill my needs. Thanks
danpost danpost

2016/12/12

#
TypoKign wrote...
What is the best practice for determining if the button is being held (note: anywhere in the world, so mouseDragged(Actor actor) does not fulfill my needs.
I would add an instance boolean field to track the state of the button. Set the field to 'true' when the button is pressed and set it to 'false' when the button is released:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// instance field
private boolean mousePressed;
 
/** in action code */
// button press (anywhere, in the example code)
if ( ! mousePressed)
{
    mousePressed = Greenfoot.mousePressed(null);
}
else // button released
{
    mousePressed = ! Greenfoot.mouseClicked(null);
}
 
// button held
if (mousePressed)
{
    // whatever when button held
}
Super_Hippo Super_Hippo

2016/12/12

#
I just tried a bit and ended up with this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
private int button = -1;
 
public void act()
{
    MouseInfo mouse = Greenfoot.getMouseInfo();
     
    if (mouse != null)
    {
        if (Greenfoot.mousePressed(null) && button == -1) button = mouse.getButton();
        if (Greenfoot.mouseClicked(null)) button = -1;
        if (button != -1) System.out.println(button);
    }
}
danpost danpost

2016/12/12

#
Super_Hippo wrote...
I just tried a bit and ended up with this code: < Code Omitted >
Line 11 needs to be placed down one line, to outside the main 'if' block or you will not know if a button is pressed when there is no mouse action.
You need to login to post a reply.