Reputation: 25
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
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:
setup()
blockdraw()
blockkeyPressed()
, mouseClicked()
, etc.)noLoop()
is calledSo when you call noLoop()
, the computer is no longer listening for your input, and is simply ignoring you.
Upvotes: 1