我正在尝试在基本的frogger风格的Javascript游戏中实施减少生命的系统。我有一个计数器系统,其中以数字显示生命,当玩家角色击中敌人时,生命从3倒数到0。
现在,我试图用显示的unicode心代替数字倒计时。理想情况下,游戏启动时将有三颗心,并且每次碰撞都会使显示的心数减少1。
在我的代码中,如果将生命显示为数组,则此方法有效,但会显示分隔心脏的逗号。如果我尝试将其显示为字符串,则逗号消失了,但是心脏不再减少。我觉得我离我很近,但我很沮丧。
谢谢!
var playerLives = ['💚', '💚', '💚'];
var hearts = playerLives.join(' ');
//turn playerLives array into hearts string
var playerScore = 0;
var scoreEl = document.getElementById('score');
function checkCollisions() {
for (var i = 0; i < allEnemies.length; i++) {
if (player.x <= allEnemies[i].x + 70
&& player.x + 70 >= allEnemies[i].x
&& player.y <= allEnemies[i].y + 50
&& player.y + 50 >= allEnemies[i].y)
{
player.x = 200;
player.y = 415;
hearts.slice(-10);
//attempt to remove string from hearts, but doesn't
//work
playerLives.splice(-1, 1);
//decrease playerLives array by 1 on collision
if (playerScore >= 50) {
playerScore -= 50;
scoreEl.textContent = 'Score: ' + playerScore;
}
//reset(); //create reset function
}
}
}
function score() {
if (player.y < 60) {
player.x = 200;
player.y = 415;
playerScore += 100;
scoreEl.textContent = 'Score: ' + playerScore;
level++;
levelEl.textContent = 'Level: ' + level;
}
}
function playerLife() {
for (var i = 1; i <= 3; i++) {
var lifeEl = document.getElementById('life');
lifeEl.innerHTML = 'Lives: ' + hearts; // lives appear as
//string and do not decrease on collision
//if use "'Lives: ' + playerLives" hearts do decrease
//but appear as an array with commas separating
}
}
最佳答案
要将数组转换为不带分隔符的字符串,请使用.join()和空字符串:
playerLives.join("");
关于javascript - 如何在Javascript和canvas中实现减少生命周期的系统,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34464724/