简体   繁体   English

Java/Processing mousePressed in loop 不起作用

[英]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().所以我在 Java + Processing 中制作了一个简单的游戏,其中 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.显然,如果有循环,PApplet 函数 mousePressed() 不会一直工作,所以我尝试在循环期间检查我自己的 checkmouse() 函数。 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?我如何制作它以便我可以使用while循环运行游戏并同时不断检查mousePressed?

//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.当我在处理窗口中单击鼠标时,即使 checkmouse() 每次循环都运行,它也永远不会显示“x”,所以理论上它应该在循环运行时不断检查它。

Also could someone explain why this doesn't work?也有人可以解释为什么这不起作用?

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

The event variables ( mousePressed , keyPressed , etc.) are updated between calls to the draw() function.事件变量( mousePressedkeyPressed等)调用draw()函数之间更新。

In other words: the mousePressed function will never change within a call to the draw() function.换句话说:在调用draw()函数时, mousePressed函数永远不会改变。 You need to let the draw() function complete and then be called again if you want the event variables to be updated.如果要更新事件变量,则需要让draw()函数完成,然后再次调用。

Behind the scenes, this is because Processing is single-threaded.在幕后,这是因为处理是单线程的。 (This is by design, because multi-threaded UI programs are a nightmare.) (这是设计使然,因为多线程 UI 程序是一场噩梦。)

Taking a step back, you probably don't want to include a long loop inside your draw() function.退后一步,您可能不想在draw()函数中包含一个长循环。 Take advantage of the 60 FPS loop that's implemented by Processing instead.而是利用 Processing 实现的 60 FPS 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM