gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:20:05 27 4
gpt4 key购买 nike

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

下面是我的“Player”类的代码(我想要移动的形状):

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);
}
}

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

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() 函数,看看我的意思。

关于javascript - 如何使用 keyIsDown 使形状移动 (p5.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com