我正在尝试用上、下、左、右键控制一个椭圆。我想让它平滑,所以椭圆不会立即停止。此外,当它向左移动并按下右箭头时,它会更快地转身。
最小、完整和可验证的示例:
var x,y,speed,xspeed,yspeed,size;
function setup() {
createCanvas(window.innerWidth-20,window.innerHeight-20);
x = width / 2;
y = height - 20;
speed = 5.5;
yspeed = 0;
xspeed = 0;
size = 20;
}
function draw() {
background(0);
fill(255,0,0);
ellipse(x-size/2,y-size/2,size,size);
checkKeys();
x=constrain(xspeed+x,0+size,width);
y=constrain(yspeed+y,0+size,height);
}
function accelerateUP() {
if(-1*(speed) <= yspeed && yspeed<= 0){yspeed-=0.5;}
else if (0 < yspeed) yspeed=lerp(yspeed,0,0.5);
}
function accelerateDOWN(){
if(yspeed >=0 && yspeed <= speed){yspeed+=0.5;}
else if (yspeed <0) yspeed=lerp(yspeed,0,0.5);
}
function accelerateLEFT(){
if(xspeed <=0 && xspeed >= -1*(speed)){xspeed-=0.5;}
else if (xspeed >0) xspeed=lerp(xspeed,0,0.5);
}
function accelerateRIGHT (){
if(speed >= xspeed && xspeed >=0){xspeed+=0.5;}
else if (0 > xspeed ) xspeed=lerp(xspeed,0,0.5);
}
function checkKeys (){
if (keyIsDown(UP_ARROW)){
accelerateUP();
}
else if (keyIsDown(DOWN_ARROW)){
this.accelerateDOWN();
}else yspeed = lerp(yspeed,0,0.5);
if (keyIsDown(LEFT_ARROW)){
this.accelerateLEFT();
}
else if (keyIsDown(RIGHT_ARROW)){
accelerateRIGHT();
}else
xspeed = lerp(xspeed,0,0.5);
}