AnonymousRand
AnonymousRand

Reputation: 21

Java/Processing mousePressed in loop not working

So I was making a simple game in Java + Processing where there were buttons and loops in draw(). Apparently the PApplet function mousePressed() doesn't work constantly if there is a loop, so I tried putting my own checkmouse() function to be checked during the loop. However, it still doesn't work. How do I make it so that I can run a game with while-loops and constantly check for mousePressed at the same time?

//draw() func
public void draw() {

    for (int i = 0; i < 10000; i++) {    //to simulate a while loop
        //do something, like run some other functions that create the buttons
        checkmouse();
    }
}

//checkmouse function
public void checkmouse() {

    if (mousePressed) {
        System.out.println("x");
    }
}

When I click the mouse in the processing window, it never shows "x" even though checkmouse() runs every time it loops, so theoretically it should be checking it pretty constantly while the loop runs.

Also could someone explain why this doesn't work?

boolean esc = false;
while (!esc) {
    if (mousePressed) {
        System.out.println("x");
        esc = true;
    }
}

Upvotes: 2

Views: 694

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

The event variables (mousePressed, keyPressed, etc.) are updated between calls to the draw() function.

In other words: the mousePressed function will never change within a call to the draw() function. You need to let the draw() function complete and then be called again if you want the event variables to be updated.

Behind the scenes, this is because Processing is single-threaded. (This is by design, because multi-threaded UI programs are a nightmare.)

Taking a step back, you probably don't want to include a long loop inside your draw() function. Take advantage of the 60 FPS loop that's implemented by Processing instead.

Upvotes: 2

Related Questions