我正在尝试为小行星游戏显示滚动主屏幕,该游戏不断重绘背景,直到用户按下“输入”,之后,它将执行启动游戏所需的方法。
主屏幕上的帧速率正常,但是当您按Enter键时,游戏会渲染,但移动速度太慢,动画滞后且游戏无法播放。
我觉得它必须与速度'变量失控,但我尝试重置它。
如果您删除requestAnimationFrame
的第一个电话,主屏幕将不会滚动(显然,因为'速度'永远不会增加,因此背景是静态的),但游戏将会以它的正常帧速率播放。我也尝试用this.game.draw(this.ctx, speed)
作为0来调用speed
,但无效。
请注意,DIM_Y
和DIM_X
只是在范围之外定义的常量。
GameView.prototype.animate = function(time) {
speed += 1;
if (speed >= 605) {
speed = 0;
};
if (this.onHomeScreen) {
console.log("asf")
let that = this;
img.onload = function () {
that.ctx.drawImage(img, 0, 0)
};
img.src = 'space_background.png';
let y = 0;
let x = 0;
y += speed;
this.ctx.drawImage(img, x,y);
this.ctx.drawImage(img, x, y - DIM_Y);
if (y >= DIM_Y) {
y = 0;
};
this.ctx.fillStyle = "white";
this.ctx.font = "italic "+24+"pt Arial";
this.ctx.fillText('ASTEROIDS', 100, 200);
requestAnimationFrame(this.animate.bind(this));
key('enter', ()=> {
this.onHomeScreen = false;
this.start();
});
} else {
// 'enter' has been pressed, the game begins.
this.game.step();
this.game.draw(this.ctx, speed);
if(!this.game.lose() && !this.game.win()){
requestAnimationFrame(this.animate.bind(this));
}
else {
this.ctx.fillStyle = "white";
this.ctx.font = "italic "+24+"pt Arial ";
that = this;
if(this.game.win()){
that.ctx.fillText(`You Win! \n Press Enter to restart`, 100, 200);
} else {
console.log(speed)
that.ctx.fillText(`Game Over \n Press Enter to restart`, 100, 200);
}
key('enter', ()=>{
this.game = new Game();
this.start();
});
}
}
};