2013-09-24 37 views
3

我希望有人能夠看看我一直在爲一個簡單的舊學校馬里奧克隆正在致力於此JavaScript代碼。 我已經將幾個教程中關於畫布的知識拼湊在一起,並且我無法獲得塊的碰撞或跳躍正常工作。Javascript HTML5帆布馬里奧兄弟NES克隆,碰撞和跳躍破碎

跳躍似乎設置馬里奧在一個無限循環反覆彈跳,這看起來很有趣,但不是非常有利於玩遊戲!

 function Player() { 
    this.srcX = 0; 
    this.srcY = 0; 
    this.drawX = gameWidth /2; 
    this.drawY = 0; 
    this.scaleWidth = 38; 
    this.scaleHeight = 50; 
    this.width = 48; 
    this.height = 60; 
    this.speed = 10; 
    this.maxJump = 50; 
    this.velY = 0; 
    this.velX = 0; 
    this.isJumpKey = false; 
    this.isRightKey = false; 
    this.isCrouchKey = false; 
    this.isLeftKey = false; 
    this.jumping = false; 
    this.grounded = false; 
    } 


    Player.prototype.draw = function(){ 
     clearPlayer(); 
     this.checkKeys(); 
     ctxPlayer.drawImage(
     player, 
     this.srcX, 
     this.srcY, 
     this.width, 
     this.height, 
     this.drawX, 
     this.drawY, 
     this.scaleWidth, 
     this.scaleHeight); 
    }; 
Player.prototype.checkKeys = function() { 


if(this.isJumpKey){ 

    if (!this.jumping && this.grounded) { 
     this.jumping = true; 
     this.grounded = false; 
     this.velY = -this.speed * 2; 
    } 

} 

if(this.isRightKey){ 

    if (this.velX < this.speed) { 
      this.velX++; 
     } 

} 
    if(this.isLeftKey){ 
    if (this.velX < this.speed) { 
      this.velX--; 
     } 
} 
if(this.isCrouchKey){ 
     player1.grounded = true; 
     player1.jumping = false; 
} 


}; 

下面是我在現在其中codepen:http://codepen.io/AlexBezuska/pen/ysJcI

我真的很感激任何幫助,我將繼續尋找,並在此期間,玩弄這一點,但任何指針你可以給,甚至對格式化,原型創建等方面的建議都非常讚賞(我對於畫布和原型都很新穎)

回答

4

在你的checkKeyDown()checkKeyUp()函數中,你讓它們檢查不同的'跳轉'鍵。從checkKeyDown()

if (keyID === 74) { //spacebar 
    e.preventDefault(); 

    player1.isJumpKey = true; 
} 

checkKeyUp()

if (keyID === 32) { // spacebar 
    player1.isJumpKey = false; 
    e.preventDefault(); 
} 

所以checkKeyUp()不能正常復位player1.isJumpKey。將它們設置爲相同,並且對我來說工作正常。

作爲一般性觀點,可能需要設置一個對象來保存代碼中包含多個實例的所有參數。然後通過引用該對象將它們寫入代碼中。你已經這樣,只得到了改變他們在一個地方:

CONSTS = { 
    upKeyID: 32, 
    etc. 
} 

// then later: 

if (keyID === CONSTS.upKeyID) { 
    player1.isJumpKey = false; 
    e.preventDefault(); 
} 
+0

太棒了,我不知道我是怎麼忽略的!謝謝,現在我只需要看看如何使碰撞工作。非常感謝你的幫助! – glasses

+0

@眼鏡不用擔心。雖然在你的代碼旁邊,我也注意到,即使玩家接地,player1.velY也會繼續增加。這是因爲在'draw()'中的'player1.velY + = gravity;'行。你可能想把它改成:'if(!player1.grounded){player1.velY + = gravity;} else {player1.velY = 0};'。 – BYossarian

+0

再次感謝!我將添加常量。好主意 – glasses

0

我想通了衝突問題,我有x位置和在名爲「drawX」和「drawY」玩家原型y位置瓦爾,但在碰撞檢測功能中,它們只是'x'和'y',現在它可以工作:http://codepen.io/AlexBezuska/pen/ysJcI w00t!