对,我正在使用canvas和
javascript创建一个侧面无限的空间主题游戏.我正在使用向上和向下箭头控制太空船,我想实施某种运动缓和,以便当我放开钥匙时,船只不会停止死亡.我已经环顾四周,没有找到任何东西,而我自己的尝试也没有工作,这是我试过的…
Jet.prototype.checkDirection = function () { if (this.isUpKey) { this.drawY -= this.speed; if (this.speed < 5) { this.speed += 0.1; } } if (this.isDownKey) { this.drawY += this.speed; if (this.speed < 5) { this.speed += 0.1; } } if (!this.isUpKey) { if (!this.isDownKey) { if (this.speed >= 0) { this.drawY -= this.speed; this.speed -= 1; } } } if (!this.isDownKey) { if (!this.isUpKey) { if (this.speed >= 0) { this.drawY += this.speed; this.speed -= 1; } } }
解决方法
你只想施加一些摩擦.它很容易你可以做如下的事情.
this.speed*=0.98;
值越低(0.8,0.5等)越快,你会减速.
我提供了一个演示,您可以在其中移动,并将逐渐减慢.继续玩这个价值,看看它是如何影响的.
var canvas = document.getElementById("canvas"),ctx = canvas.getContext("2d"); canvas.width = canvas.height = 300; var x = 150,//initial x y = 150,// initial y velY = 0,velX = 0,speed = 2,// max speed friction = 0.98,// friction keys = []; function update() { requestAnimationFrame(update); // check the keys and do the movement. if (keys[38]) { if (velY > -speed) { velY--; } } if (keys[40]) { if (velY < speed) { velY++; } } if (keys[39]) { if (velX < speed) { velX++; } } if (keys[37]) { if (velX > -speed) { velX--; } } // apply some friction to y velocity. velY *= friction; y += velY; // apply some friction to x velocity. velX *= friction; x += velX; // bounds checking if (x >= 295) { x = 295; } else if (x <= 5) { x = 5; } if (y > 295) { y = 295; } else if (y <= 5) { y = 5; } // do the drawing ctx.clearRect(0,300,300); ctx.beginPath(); ctx.arc(x,y,5,Math.PI * 2); ctx.fill(); } update(); // key events document.body.addEventListener("keydown",function (e) { keys[e.keyCode] = true; }); document.body.addEventListener("keyup",function (e) { keys[e.keyCode] = false; });