我正在尝试创建一个用于娱乐和学习的画布游戏,但是我的代码无法按我的意愿运行。
我在游戏中有一个角色,该角色向右/向左/向上/向下走动,每一步都为图像添加了px并制作了动画。 这意味着如果字符位于屏幕的20px,40px上,而您向右移动,则将是40px,40px。
我的代码如下:
start() {
this.deltaTime();
this.ctx.clearRect(0, 0, this.gameWindow.width, this.canvas.height);
this.map.drawMap();
this.player.drawPlayer();
this.text.drawText('Coordinates X:'+this.player.position.x+', Y:'+this.player.position.y, 5, 5);
this.text.drawText('FPS: '+this.graphic.lastfps, 5, 17);
this.text.drawText('ms: '+this.graphic.lastDelta, 5, 29);
this.text.drawText('delta: '+this.graphic.delta, 5, 41);
this.text.drawText('Running time: '+this.runningTime, 5, 53);
this.text.drawTextList();
}
deltaTime() {
// Calc FPS
let fps, delta;
let performanceUse = performance.now();
fps = delta = Math.floor(performanceUse / 1000);
if(this.graphic.lastTimeFPSDate !== fps) {
this.graphic.lastTimeFPSDate = fps;
this.graphic.lastfps = this.graphic.fps;
this.graphic.fps = 1;
this.runningTime++;
}
else
this.graphic.fps++;
// Calc Delta
this.graphic.delta = performanceUse - this.graphic.lastTimeDeltaCall;
this.graphic.lastTimeDeltaCall = performanceUse;
if(this.graphic.lastTimeDeltaDate !== delta) {
this.graphic.lastTimeDeltaDate = delta;
this.graphic.lastDelta = Math.floor(this.graphic.delta);
}
}
animationMove(to) {
let target;
let animationSpeed = (this.running) ? this.engine.gameSpeed.runSpeed : this.engine.gameSpeed.walkSpeed;
let distanceBettwenSquares = this.engine.mapSettings.pxPerSquare;
let seconds = 1000;
let everyStepAnimation = Math.ceil((60 / this.engine.graphic.lastfps));
let runLoopForAnimationEveryXMS = Math.floor(seconds / distanceBettwenSquares);
let stopLoop = false;
let sign = null;
//console.clear();
console.log('runLoopForAnimationEveryXMS: '+runLoopForAnimationEveryXMS+', everyStepAnimation: '+everyStepAnimation);
console.log('FPS: '+this.engine.graphic.lastfps+', deltaTime: '+this.engine.graphic.lastDelta);
console.log('REAL FPS: '+this.engine.graphic.fps+', REAL deltaTime: '+this.engine.graphic.delta);
// - - - - - - - - - -
this.engine.animationLoop(true, 0, runLoopForAnimationEveryXMS, (id) => {
// Stop the animation if it is 0 or bigger than the distance that require or stopLoop is true (which mean the numbers get over fed)
if (this.playerAnimation[target] === 0 || Math.abs(this.playerAnimation[target]) > distanceBettwenSquares || stopLoop) {
this.engine.animationLoop.kill(id);
this.playerAnimation.walk = false;
this.playerAnimation.needAnimation = true;
this.playerAnimation[target] = 0;
return;
}
// Do each step of the animation
sign = Math.sign(this.playerAnimation[target]);
this.playerAnimation[target] = sign * (Math.abs(this.playerAnimation[target]) - everyStepAnimation);
if (Math.sign(this.playerAnimation[target]) !== sign)
stopLoop = true;
});
}
function game() {
start();
window.requestAnimationFrame(game);
}
window.requestAnimationFrame(game);
按下某个键时,它会先进行动画处理(每步将图像移动几像素),然后更新当前位置的变量。
这是问题所在: 有时动画会变慢,甚至“跳跃”。 没有实际的FPS更改(1-2 +-)。
所以我的问题是:
感谢和抱歉我的英语,即使回答一个答案也有帮助!