第一次使用 Javascript 中的类时,我想知道如何在此代码中添加 setInterval,以便我可以平滑地移动 s



例如,我希望能够在点击左箭头按钮时移动正方形。尽管代码在下面有些工作,但我希望能够在播放器类中的 show(( 函数中添加一个设置的间隔,以便它也能清除 Rect 并使我的方块移动更顺畅。这是我的代码:提前谢谢你...

<body>
<canvas width="400" height="400" id="myCanvas"></canvas>
<script>
var a=document.getElementById("myCanvas");
var c=a.getContext("2d");

class player{
constructor(){
this.x=200;
this.y=200;
}

show(){
c.clearRect(0,0,200,200);
c.fillStyle="black";
c.beginPath();
c.rect(this.x,this.y,30,30);
c.fill();
c.closePath();
}

moveUp(){
this.y-=2;
}
moveDown(){
this.y+=2;
}
moveLeft(){
this.x-=2;

}
moveRight(){
this.x+=2
}
}

var player1=new player();

window.onkeydown=function(e){
if(e.keyCode==37){
player1.show();
player1.moveLeft();
}
}

</script>
</body>

我只是编写了一个简单游戏循环的模板,您可以在后期增强,在这个游戏循环中,我使用了window.requestAnimationFrame而不是window.setInterval,以便我们可以坚持浏览器的本机刷新循环,并且您需要自己计算 deltaTime,以便您可以顺利运行。

这是我从您的代码库中想出的模板:

<body>
<canvas width="400" height="400" id="myCanvas"></canvas>
<script>
var a = document.getElementById("myCanvas");
var c = a.getContext("2d");
class player {
constructor() {
this.x = 200;
this.y = 200;
this.vel = 90;
this.canMoveUp = false;
this.canMoveDown = false;
this.canMoveLeft = false;
this.canMoveRight = false;
}
show() {
c.clearRect(0, 0, a.width, a.height);
c.fillStyle = "black";
c.beginPath();
c.rect(this.x, this.y, 30, 30);
c.fill();
c.closePath();
}
moveUp(deltaTime) {
this.y -= this.vel * deltaTime;
}
moveDown(deltaTime) {
this.y += this.vel * deltaTime;
}
moveLeft(deltaTime) {
this.x -= this.vel * deltaTime;
}
moveRight(deltaTime) {
this.x += this.vel * deltaTime;
}

updatePos(deltaTime){
if(this.canMoveUp) this.moveUp(deltaTime);
if(this.canMoveDown) this.moveDown(deltaTime);
if(this.canMoveLeft) this.moveLeft(deltaTime);
if(this.canMoveRight) this.moveRight(deltaTime);
}
}
var player1 = new player();
document.addEventListener('keydown', function(e) {
e.preventDefault();
if (e.code === "ArrowDown") player1.canMoveDown = true;
if (e.code === "ArrowUp") player1.canMoveUp = true;
if (e.code === "ArrowLeft") player1.canMoveLeft = true;
if (e.code === "ArrowRight") player1.canMoveRight = true;
}, false);

document.addEventListener('keyup', function(e) {
e.preventDefault();
if (e.code === "ArrowDown") player1.canMoveDown = false;
if (e.code === "ArrowUp") player1.canMoveUp = false;
if (e.code === "ArrowLeft") player1.canMoveLeft = false;
if (e.code === "ArrowRight") player1.canMoveRight = false;
}, false);
var now, deltaTime, lastTime = window.performance.now();
function frame() {
now = window.performance.now();
deltaTime = (now - lastTime) / 1000;
player1.updatePos(deltaTime);
player1.show(deltaTime);
lastTime = now;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>

为了更好地理解 setInterval,你可以在这里阅读它 https://javascript.info/settimeout-setinterval

通用语法是:

let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)

例:

setInterval(show, <specify the time in milliseconds> )

最新更新