Multiple Key Inputs

#1

I’m trying to create a game where two people move at once. I’ve realised that you can’t have more than one key input at a time which makes my idea impossible. I was wondering if there was a way where I could have more than one key be pressed at once. Thank you.

1 Like
#2

Hi Samira,

check out the keyIsDown function:
https://p5js.org/reference/#/p5/keyIsDown

I’ll get an example going here for you too!

1 Like
#3

if you check the keyIsDown() during draw and use an if statement you can check for what keys are down and detect multiple keys.

one thing of note, in the online editor, you might have to ‘click’ on the canvas to make that ‘pane’ active before the key events will be recognized

let p1x = 0
let p2x = 0

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  
  //65 is the A  key
  if(keyIsDown(65) == true ){
    
    p1x += 1
  }
  
  //76 is the L key
  if(keyIsDown(76) == true ){
    p2x += 1
  }
  
  
  //put the ellipses on the screen
  ellipse(p1x,height/4,10,10)
  ellipse(p2x,height/4*3,10,10)

  
}
1 Like
#4

Oh my god you are a lifesaver, thank you so much. I didn’t even know this function existed!

1 Like