【问题标题】:Setting counter for collision设置碰撞计数器
【发布时间】:2014-09-05 14:29:03
【问题描述】:

目前我有一个游戏,当你点击画布时,会在上面画一块食物。然后鱼精灵会走向食物吃掉它。

这是让鱼向食物移动的功能:

Fish.prototype.eatFood = function() {
    var foodX, foodY;
    var halfWidth = this.frameWidth * this.frameScale / 2;
    var halfHeight = this.frameHeight * this.frameScale / 2;
    // Loop backward because we are removing elements.
    for (var i = foodArray.length-1; i >= 0; i--) {
        foodX = foodArray[i].x + foodWidth / 2;
        foodY = foodArray[i].y + foodHeight / 2;
        if (foodX > this.xPos - halfWidth &&
            foodX < this.xPos + halfWidth &&
            foodY > this.yPos - halfHeight&&
            foodY < this.yPos + halfHeight)
        {
            foodArray.splice(i, 1); //Clearing away food after both of it collide
        }
    }
};

我怎样才能设置一个计数器,这样每次鱼吃完食物时,计数器就会增加。

【问题讨论】:

  • 您是否尝试过保留一个全局变量并在foodArray.splice(i, 1); 之后增加它?

标签: javascript html canvas


【解决方案1】:

这可能会有所帮助:在脚本的开头创建一个变量(全局)并将其初始化为 0。然后每当食物消失时,就在这里:{ foodArray.splice(i, 1); //Clearing away food after both of it collide }

增加变量。像这样:

   ` {
        foodArray.splice(i, 1); //Clearing away food after both of it collide
        foodCount++;
    } `

这样,鱼每次吃东西都会增加。

【讨论】:

  • document.getElementById("foodCount").innerHTML = foodCount;foodCount++之后添加以上行
  • 在主 Fish(blah, blah, blah...) 中添加这一行:this.foodCount = 0;,然后将我们之前的编辑更改为this.foodCount++; document.getElementById("foodCount").innerHTML = this.foodCount; /* whenever a fish eats food, that fish's count is displayed */
  • 至于食品柜台展示,我只是在我的 html 文件中添加更多 &lt;p id="foodCount"&gt;&lt;/p&gt; 用于多个柜台展示,或者我应该怎么做?
  • 多个元素的 ID 不能相同。使用数组或其他东西来保存分数,然后一次显示。我建议您先了解 javascript 基础知识,然后再继续。 codecademy 里面有很好的源代码
猜你喜欢
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
相关资源
最近更新 更多