【发布时间】:2017-07-04 12:56:48
【问题描述】:
我正在尝试使用 ES6 和 Canvas 进行游戏开发。在这个例子中,我有一个宇宙飞船的图像,我用左右箭头键旋转它,然后用上键向前移动它。 如果您查看旋转和向前移动,您会发现它是滞后的。有没有办法让它更流畅?
Plunker
“动画”和运动的代码:(也可以在 plunker 中找到)
来自engine.js:
let mainLoop = function() {
clrscr();
draw();
requestAnimationFrame(mainLoop);
}
let draw = function() {
spaceship.draw(ctx);
}
let keyDownListener = function(e) {
if(e.keyCode == 37)
spaceship.rotateLeft();
if(e.keyCode == 38)
spaceship.moveForward(ctx);
if(e.keyCode == 39)
spaceship.rotateRight();
if(e.keyCode == 32)
createExplosion();
};
let clrscr = function() {
ctx.fillStyle="#415575";
ctx.fillRect(0,0,w,h);
}
来自spaceship.js:
let width = image.width * resizeMultiplier;
let height = image.height * resizeMultiplier;
const rotateDelta = 0.37;
const forwardDelta = 0.77;
let draw = function(context) {
//Save context
context.save();
//Translate before rotate
context.translate(x,y);
//Rotate on translated 0,0
context.rotate((angle) * Math.PI/180);
//Draw rotated image
context.drawImage(image, -(width/2), -(height/2), width, height);
//Restore the translated & rotated coords to where we began
context.restore();
}
let rotateRight = function() {
console.log(angle);
angle = (angle === 360) ? 0 : angle + (rotateDelta *(1000/60));
}
let rotateLeft = function() {
console.log(angle);
angle = (angle === -360) ? 0 : angle - (rotateDelta *(1000/60));
}
let moveForward = function() {
let dx = Math.sin((angle) * Math.PI/180);
let dy = - Math.cos((angle) * Math.PI/180);
x += dx * forwardDelta * (1000/60);
y += dy * forwardDelta * (1000/60);
console.log('dx: ',dx,' dy: ',dy);
//x += forwardDelta * (1000/20);
}
感谢您的宝贵时间。
【问题讨论】:
-
您要做的不是直接操纵船的位置和方向,而是操纵它的速度和角动量,并让这些属性在主循环中操纵船。
标签: javascript ecmascript-6 game-physics