Issues with keyIsDown() in p5js

一个人想着一个人 提交于 2019-12-11 06:41:52

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/54802201/issues-with-keyisdown-in-p5js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!