p5js中的keyIsDown()问题 [英] Issues with keyIsDown() in p5js

查看:88
本文介绍了p5js中的keyIsDown()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用p5js和p5.play制作基本的2D游戏.每次尝试执行任何操作时都会引起问题的问题是keyIsDown函数.有没有一种方法可以在按下某个键之前确定它是否已按下?如果我使用

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将显示为未定义,直到我按向上箭头.在按下它们之前,是否有任何方法可以将相应的布尔值分配给这些类型的事物? 到目前为止,直到我一次按下每个已插入的键,我的游戏才能正常工作.

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.

推荐答案

keyIsDown()函数检查按键当前是否按下(即按下) .如果您有一个可移动的对象,并且希望多个键能够同时影响其行为,例如对角线移动精灵,则可以使用它.

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.

这是一个使用awsd键并注销当前按下键的键代码的示例.

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>

这篇关于p5js中的keyIsDown()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆