1

I'm trying to make a basic 2d game with p5js and p5.play. An issue that seems to cause issues every time I try to do anything is the keyIsDown function. Is there a way to determine if a key is down before pressing it? If I used

upKey = keyIsDown(UP_ARROW);

upKey will show as undefined until I press the up arrow. Is there any way to assign the respective boolean values to these types of things prior to pressing them? As of now, my game will not properly work until I have pressed every involed key one time.

DocRatMD
  • 11
  • 2

1 Answers1

0

The keyIsDown() function checks if the key is currently down, i.e. pressed. It can be used if you have an object that moves, and you want several keys to be able to affect its behaviour simultaneously, such as moving a sprite diagonally.

Note that the arrow keys will also cause pages to scroll so you may want to use other keys for your game.. but if you want to use arrow keys this is the code snippet from the reference page

let x = 100;
let y = 100;
function setup() {
  createCanvas(512, 512);
}

function draw() {

  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();
  fill(255, 0, 0);
  ellipse(x, y, 50, 50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>

To implement similar logic without the use of arrow keys you will need to determine the key code of the keys you want to use.

Here is an example that uses awsd keys and also logs out the key code of the currently pressed key.

let x = 50;
let y = 50;
function setup() {
  createCanvas(512, 512);
}
function keyPressed(){
console.log(keyCode);
}

function draw() {
  if (keyIsDown(65)) {
    x -= 5;
    if (x < 0) x = 0;
  }

  if (keyIsDown(68)) {
    x += 5;
    if (x > width) x = width;
  }

  if (keyIsDown(87)) {
    y -= 5;
    if (y < 0) y = 0;
  }

  if (keyIsDown(83)) {
    y += 5;
    if ( y > height) y = height;
  }

  clear();
  fill(255, 0, 0);
  ellipse(x, y, 50, 50);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
Charlie Wallace
  • 1,810
  • 1
  • 15
  • 17