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

2021/4/15

How to register when left and right mouse buttons are clicked at the same time?

RoverKnight RoverKnight

2021/4/15

#
Hello! I'm trying to create a method that is executed only when both the left and right mouse button are pressed, so I wanted to use Greenfoot.getMouseInfo().getButton(), as it's also used in other (not relevant to this post) parts of the code. However, as this gives back only a single value (in this case 1 or 3), it can't be both at the same time, so I don't know how I could register both being clicked at the same time... By the way, I also have a command that executes on left click only and am planning on adding one for right click only as well, so the code for both being clicked should only execute once one of them is released while the other is held down.
danpost danpost

2021/4/15

#
Add an int field to track buttons down. Increase by (button value plus one) divided by two on mouse presses and decrease by same on mouse clicks. Only perform action for both buttons down when its value is three. One thing to note: although not very likely, it is possible for both buttons to perform an action during the same act cycle, which may throw your count off. Increasing the scenario speed will help in minimizing that possibility. Limiting the value of the field to between zero and three on any change in its value would also help to rectify it when it does go off value. With this:
1
2
3
4
5
6
7
private int mVal; // mouse value
 
private void adjustMouseValue(int btnVal, int btnDir) // direction '1' is pressed and '-1' is clicked
{
    if (btnDir == 1 && btnVal&mVal == 0) mVal += btnVal;
    else if (btnDir == -1 && btnVal&mVal != 0) mVal -= btnVal;
}
the following should work to catch changes:
1
2
3
4
int btnDir = 0;
if (Greenfoot.mousePressed(null)) btnDir++;
if (Greenfoot.mouseClicked(null)) bbnDir--;
if (btnDir != 0) adjustMouseValue((Greenfoot.getMouseInfo().getButton()+1)/2, btnDir);
You need to login to post a reply.