p5.js: 我如何让玩家连续移动?

p5.js: How would I make the player move continuously?

我正在创建一个游戏,但我有一个问题,我想向左或向右移动玩家,但当我按下按钮时,它只会向左或向右移动一次,而不是连续移动

var player 1 = new Player(width / 4)

function keyPressed() {
    if (key === "d") {
        player1.move(1);
      } else if (key === "a") {
        player1.move(-1);
      }
   }



function Player(xPos) {
  this.x = xPos;
  this.y = height - 100;

  this.show = function() {
    fill(255);
    rectMode(CENTER);
    rect(this.x, this.y, 50, 100);
  }

  this.move = function(dir) {
    this.x += dir * 5;
  }
}

使用 keyIsDown() 而不是 keyPressed()

来自documentation

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. You can put in any number representing the keyCode of the key, or use any of the variable keyCode names listed here.

也应该在draw()函数内:

function draw(){
    if(keyIsDown("d")){
        player1.move(1);
    }
    if (keyIsDown("a")) {
        player1.move(-1);
    }
}