2016-07-27 73 views
1

我正在製作一個非常簡單的html5帆布遊戲。我希望這樣做,當玩家失去全部3條生命時,遊戲重置。如何編寫一個循環來檢查生命=== 0?

我在想我可以做一個while循環,它總是檢查生命=== 0然後運行一個函數,但是這打破了遊戲,沒有任何東西出現在畫布上。

這是我的代碼。

var lives = 3; 
while (lives <= 0) { 
var fullReset = function() { 

// Throw the monster somewhere on the screen randomly 
monster.x = 1 + (Math.random() * (canvas.width - 64)); 
monster.y = 1 + (Math.random() * (canvas.height - 64)); 
monster2.x = 1 + (Math.random() * (canvas.width - 100)); 
monster2.y = 1 + (Math.random() * (canvas.height - 100)); 


// player start again 
hero.x = canvas.width/2; 
hero.y = canvas.height/2; 

//score resets 
monstersCaught() = 0; 
lives() = 3; 
} 
fullReset(); 
} 
+1

如果(住=== 0) – prgrm

回答

2

我認爲你的方法存在一個概念錯誤。你從3條生命開始(在你的例子中缺少初始化)。然後,每當怪物遭到攻擊時,你就減少一個人的生命並檢查新的價值。當新值爲零時,是時候重置遊戲了。

所以,你的循環應該只處理移動你的對象,而只要怪物攻擊並應用上述邏輯就會觸發事件。

1
function gameLoop() { 

    var lives = 3; 
    if(lives <= 0) { 
    var fullReset = function() { 

    // Throw the monster somewhere on the screen randomly 
    monster.x = 1 + (Math.random() * (canvas.width - 64)); 
    monster.y = 1 + (Math.random() * (canvas.height - 64)); 
    monster2.x = 1 + (Math.random() * (canvas.width - 100)); 
    monster2.y = 1 + (Math.random() * (canvas.height - 100)); 


    // player start again 
    hero.x = canvas.width/2; 
    hero.y = canvas.height/2; 

    //score resets 
    monstersCaught() = 0; 
    lives() = 3; 
    } 
    fullReset(); 
    } 
    requestAnimationFrame(gameLoop); 
} 

你試過了requestAnimationFrame()這樣你可能甚至不依賴於while循環和使用對象的換了個位置,每次再次提請畫布上一遍又一遍。

1

這不是一個非常實用的方法來解決您的問題。

我會處理的是與一個OnEvent觸發,例如當一個怪物的攻擊,或者當玩家接觸的怪物