Why my function return value when I release the key?

Viewed 71

I know this could be a stupid question, but I can't figure out what's happening with my code in p5.js (I use the online editor).

I'm making a simple snake game but when I call the function to add a certain value to move the head (for now just the head) it returns the value I want but does it another time when I release the key despite I also called this:

function keyReleased(){
    return false;
  }

These are the functions that I call in the sketch file.

let w = 87;
let a = 65;
let s = 83;
let d = 68;
let stepToDo = 10;

function keyPressed(axis){
  if (axis === 0){
    if(keyCode === a){
      keyCode = 0;
      return -stepToDo;
    } else if(keyCode === d){
      keyCode = 0;
      return stepToDo;
    } else {
      return 0;
    }
  } else if (axis === 1) {
    if(keyCode === w){
      keyCode = 0;
      return -stepToDo;
    } else if(keyCode === s){
      keyCode = 0;
      return stepToDo;
    } else {
      return 0;
    }
  }
}

function keyReleased(){
    return false;
  }

This is the sketch file.

let arrTest = [200, 200];


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

function draw() {
  background(220);

  arrTest[0] = arrTest[0] + keyPressed(0);
  arrTest[1] = arrTest[1] + keyPressed(1);
  keyReleased();
  //console.log(arrTest);

  rect (arrTest[0], arrTest[1], 10, 10);
}

Link to the sketch itself https://editor.p5js.org/antolab/sketches/_Lzz41cos

1 Answers

The keyPressed() function is an event listener. You don't have to call it from your main draw() loop; instead, it is automatically called every time a key is pressed. That way you can use it to change your position array depending on the input key. For example as follows:

function keyPressed() {
  if (keyCode === a) {
    arrTest[0] = arrTest[0] - stepToDo;
  } else if (keyCode === d) {
    arrTest[0] = arrTest[0] + stepToDo;
  } else if (keyCode === w) {
    arrTest[1] = arrTest[1] - stepToDo;
  } else if (keyCode === s) {
    arrTest[1] = arrTest[1] + stepToDo;
  }
}

Note that because we do not define a new arrTest variable within the keyPressed() function it will automatically access the variable that you defined further above. Here is the corresponding modified sketch.

The reason the keyPressed() function was seemingly executed ``twice'' in your code is that it got executed as part of every iteration of the draw() loop and automatically upon pressing a key.

Related