正在设置碰撞计数器

Setting counter for collision

本文关键字:计数器 碰撞 设置      更新时间:2023-09-26

目前我有一个游戏,当你点击画布时,会在上面画一块食物。然后鱼精灵会朝着食物移动来吃它。

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

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
        }
    }
};

我怎么能设置一个计数器,这样每当鱼吃东西时,计数器就会增加。

这可能会有所帮助:在脚本的开头创建一个变量(Global)并将其初始化为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++;
    } `

这样,每当鱼吃东西时,它就会增加。