lover-fish
  • Introduction
  • 搭建环境
  • 绘制背景
  • 绘制海葵
  • 绘制果实
  • 果实动画
  • 控制果实的数量
  • 增加果实的类型
  • 绘制鱼
  • 让鱼动起来
  • 让鱼跟着鼠标动起来
  • 吃果实之碰撞检测
  • 创建鱼宝宝
  • 给鱼添加动画
  • 加入计分模块
  • 大鱼身体特效
  • 游戏结束逻辑
  • 增加吃果实特效
  • 海葵动画
  • 漂浮物
Powered by GitBook
On this page

控制果实的数量

此时的果实,假如超出了可视区域,就不会再回来了,所以我们应该需要让存活为 flase 的果实在某些时机复活。

所以我们需要一个监视果实的方法,当存活的果实小于15个的时候,就重置一个果实的状态,让它又涨出来。

  // 监视果实
  monitor() : void {
    let num = 0;
    for (let i = 0; i < this.num ; ++i) {
      if(this.alive[i]) num++; // 计数存活果实的数量

      if(num < 15) {
        // 产生一个果实
        this.reset()
        return ;
      }
    }
  }

  //重置果实的状态
  reset() {
    for (let i = 0; i < this.num; ++i) {
      if(!this.alive[i]) {
        this.born(i); // 假如存活为 false , 让它重新出生。
        return ; // 每次只重置一个果实
      }
    }
  }

因为我们要在 born 里面重置,所以,我们要把构造器里面的一些重置属性的代码放到 born 方法里面。

  // 初始化果实
  born(i){
    let aneId = Math.floor( Math.random() * anemones.num ) // 随机拿到一个果实的 ID
    this.x[i] = anemones.x[aneId]; // 设置果实的 x 坐标为海葵的 x 坐标
    this.y[i] = cvs_height - anemones.height[aneId]; // 设置果实的 y 坐标,为海葵高度的顶点坐标
    this.speed[i] = Math.random() * 0.02 + 0.005; // 设置速度在区间 0.005 - 0.025 里
    this.alive[i] = true; // 先设置它的存活为 true
    this.diameter[i] = 0; // 未生长出来的果实半径为0
  }

而我们构造会像这样,简单很多。

  constructor(){
    for (let i = 0; i < this.num; ++i) {
      this.born(i);
    }
    this.orange.src = 'assets/img/fruit.png';
    this.blue.src = 'assets/img/blue.png';
  }

当然,这个监视果实的方法需要我们在,游戏循环里面调用

function gameLoop() {
  const now = Date.now()
  deltaTime = now - lastTime;
  lastTime = now;

  console.log(deltaTime);

  drawBackbround()

  anemones.draw()
  fruits.draw()
  fruits.monitor()
  requestAnimationFrame(gameLoop);
}

这样就会有果实不断的消失,不断的重生,死去意味着新的生命开始。

Previous果实动画Next增加果实的类型

Last updated 7 years ago