如何使用 keyIsDown 使形状移动 (p5.js)

How to make a shape move with keyIsDown (p5.js)

所以我正在尝试使用 p5.js 在 canvas 中移动形状。然而,它所做的只是在新分配的位置重新绘制相同的形状而不删除旧位置的形状,留下某种痕迹,而不是像我想要的那样完全移动它。 You can see the result here.

下面是我的 "Player" class(我要移动的形状)的代码:

function Player() {
    this.hp = 10;
    this.x = 230;
    this.y = 240;
    this.color = "red";
    this.r = 10;

    this.spawn = function(){
        fill(this.color);
        noStroke();
        rect(this.x, this.y, this.r*2, this.r*2);
    }
}

这是我在 setupdraw 函数中的代码 p5.js:

var p1;

function setup() {
    createCanvas(500, 500);
    background("green");
    p1 = new Player();;
}

function draw() {
    p1.spawn();
    if (keyIsDown(LEFT_ARROW)) { 
        p1.x--;
    }
    if (keyIsDown(RIGHT_ARROW)) {
        p1.x++;
    }
    if (keyIsDown(UP_ARROW)) {
        p1.y--;
    }
    if (keyIsDown(DOWN_ARROW)) {
        p1.y++;
    }
}

如有任何帮助,我们将不胜感激。谢谢!

您需要使用background()功能清除旧帧。您通常应该从 draw() 函数的第一行调用 background()。这是一个例子:

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

function draw() {
  background(64);
  ellipse(mouseX, mouseY, 25, 25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>

尝试将对 background() 函数的调用移动到 setup() 函数以了解我的意思。

你就用

if (keyDown(the key you want to use)) {
 
}

if(keyDown("the key you want to use")){


}