2013-03-11 45 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--; 
} 

還是你想爲一個特殊的配方?