2013-03-11 48 views
11

对,我正在使用canvas和javascript创建sidescrolling无尽的空间主题游戏。我只是使用向上和向下的箭头控制飞船,并且我想实施某种运动缓解,这样当我放开钥匙时船不会停下来。我环顾四周,并没有发现任何东西加上我自己的尝试只是不工作,这是我已经试过......使用键盘控制的帆布游戏中的滑动角色运动

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; 
     } 
    } 
} 
+2

研究力,动量和摩擦力的基本物理模拟。做到这一点,以便你的钥匙给船上添加一种力量,这种力量有一个质量,并在其上施加摩擦力......通过适当选择参数(质量,摩擦,力),你可以创建各种行为。这是棘手的,但!但您可以稍后使用它:获得船舶更快动作的奖励或负面奖励,使船舶变得沉重。 – ppeterka 2013-03-11 16:54:37

+2

几乎只是用JavaScript创建物理定律O.O – VoidKing 2013-03-11 16:55:52

回答

23

你只是想申请一些摩擦。它很容易。你可以做如下的事情。

this.speed*=0.98; 

数值越低(0.8,0.5等),速度越慢。

我提供了一个演示,您可以在其中移动并逐渐放慢速度。继续,玩这个价值,看看它是如何影响它的。

Live Demo

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, 0, 300, 300); 
    ctx.beginPath(); 
    ctx.arc(x, y, 5, 0, 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; 
}); 
+1

奇妙的是,我正在寻找感谢! – 2013-03-13 17:09:43

+1

太棒了!正是我需要的。非常简化我的代码。 – Xaxis 2015-10-13 17:19:41

+0

爱你的答案。将requestAnimationFrame(update)调用放在更新函数的末尾而不是顶部之间有什么区别吗? – macalaca 2017-11-08 03:25:56

1

我想我会做的是对的keyup不停止船只,只是有一个函数,它减缓了一下,然后在setInterval调用这个函数在任何间隔给你所需的效果,然后一旦船舶的速度为零调用clearInterval

因此,基本安装u基本上安装setInterval(slowShip,500)

0

不能你只是做

if(!playerUp && !playerDown && moveSpeed > 0){ 
    moveSpeed--; 
} 

还是你想为一个特殊的配方?