Azza
Azza

Reputation: 25

Iterate over Array of images

I've created an array and pushed 30 Images into it, and implemented the keyPressed() function to change the image drawn randomly from the array but when I test it, it just changes the image one time only without looping over the array.

here is my example code simulates my problem

function keyPressed() {
    loop();
    //press left arrow to change pic
    if(keyCode === LEFT_ARROW){
        for(var i = 0; i < imgs.length; i++){
            image(imgs[i], 0 ,0);
        }
    }
}

Upvotes: 1

Views: 298

Answers (1)

Jacob Stuligross
Jacob Stuligross

Reputation: 1479

The keyPressed() function is only called at the moment when you press down the key. It is not called repeatedly while you hold it down.

One solution is to use the built-in boolean variable keyIsPressed, which is true when any key is pressed. You might do something like this:

let img_number = 0;

function setup() {
  //whatever is in your setup
}

function draw() {
  if (keyIsPressed) {
    if(keyCode === LEFT_ARROW) {
      img_number = (img_number + 1) % imgs.length;
    }
  }
  image(imgs[img_number];
}

If you're using noLoop(), I recommend finding an alternative because p5.js takes inputs like this:

  1. Run the setup() block
  2. Run the draw() block
  3. Listen for input (check where the cursor is, whether the mouse was clicked, what keys were pressed, etc.)
  4. Run the appropriate commands (keyPressed(), mouseClicked(), etc.)
  5. Repeat 2-4 until noLoop() is called

So when you call noLoop(), the computer is no longer listening for your input, and is simply ignoring you.

Upvotes: 1

Related Questions