How can I listen to user input before leaving a loop in my game code?

How do I pause my game code until input is received from the user?

For (an unpractical) example, if I have

var x = 0;

do {
  image.on('pointerup', function(){ x++; });
} while (x < 10); // if the user clicks the image 10 times, the loop concludes.

from my experiments, the game seems to loop indefinitely and never begins to listen for the user input. How do I make it so that the listener starts to listen for the user input even before exiting the loop?

var x = 0;

image.on('pointerup', function() {
  x++;

  if (x === 10) {
    // That was 10 clicks.
  }
});

There’s no waiting, and you don’t actually receive any input by calling on(). Instead you’re registering a function that will be called later if there is any input.

1 Like

Thanks for the reply! However, I don’t think I was clear enough in my question. The 10 clicks thing was just an arbitrary example. I understand that image.on only turns on the listener. However, I’m looking for my game to wait for user input until it continues with the rest of the game code.

For example, I thought about doing

var clicked = false;

image.on('pointerup', foo(){
  clicked = true;
});

do{
  ;
} while (!clicked)

But it seems like the game isn’t rendered until the entire code is finished, which will never happen until the image is able to be clicked (thus, a never ending loop)…

What is the suggested way to wait for user input before continuing on with the rest of the game code?

I’ll check out the link you provided though and see if I discover anything else.

I would try to put it in Phaser’s update function and flag like:

update(){
if(clicked){
… do the code here
}
}

It won’t crash your game

1 Like

Wouldn’t that be the same as just putting it in your create() function? The listener will automatically run the callback function once the image is clicked.

By the way, I didn’t know this until yesterday, but if you put the characters ``` before and after text, it will format it as code. Then it will register indentation.

var image;
var clicked = false;

function create() {
  image.on('pointerup', function() {
    clicked = true;
  });
}

function update() {
  if (clicked) {
    // Do something.
    // Reset?
    // clicked = false;
  }
}

Study the examples.