p5.js | Keyboard | keyIsDown()

The keyIsDown() function in p5.js checks the key’s current status that key is down, i.e. pressed. It can be used if you have a movable object, and you want several keys to be able to affect its behavior simultaneously, such as moving a sprite diagonally.

Syntax:

keyIsDown()

Below program illustrates the keyIsDown() function in p5.js:
Example-1:



filter_none

edit
close

play_arrow

link
brightness_4
code

let x = 100;
let y = 100;
  
function setup() {
    
    // create canvas of size 600*600
    createCanvas(600, 600);
}
  
function draw() {
    
    // fill color
    fill(x, y, x - y);
  
    if (keyIsDown(LEFT_ARROW)) {
        x -= 5;
    }
  
    if (keyIsDown(RIGHT_ARROW)) {
        x += 5;
    }
  
    if (keyIsDown(UP_ARROW)) {
        y -= 5;
    }
  
    if (keyIsDown(DOWN_ARROW)) {
        y += 5;
    }
  
    clear();
    ellipse(x, y, 50, 50);
}

chevron_right


Output:

Example-2:

filter_none

edit
close

play_arrow

link
brightness_4
code

let diameter = 30;
  
function setup() {
    
    // Create canvas of size 600*600
    createCanvas(600, 600);
}
  
function draw() {
    
    // 107 and 187 are keyCodes for "+"
    if (keyIsDown(107) || keyIsDown(187)) {
        diameter += 1;
    }
  
    // 109 and 189 are keyCodes for "-"
    if (keyIsDown(109) || keyIsDown(189)) {
        diameter -= 1;
    }
  
    clear();
    fill(255, 0, 0);
    ellipse(width / 2, height / 2, diameter, diameter);
}

chevron_right


Output:

Reference: https://p5js.org/reference/#/p5/keyIsDown



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.