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

果实动画

我们要实现以下几种特效

  • 果实长大 (增加一个图片的大小来实现果实长大)

  • 果实上浮 (减小 y 轴坐标,让果实上浮)

我们需要思考一下逻辑。

果实长大,那么它的直径应该是随着时间变大的,当长大到一定的直径就停止生长,然后开始上浮,上浮的过程中,我们需要不同的速度,所以我们需要一个存放速度的数组,同时它也可以限定生长速度。

随着时间变化,我们之前在 game-loop 文件里面有一个 deltaTime ,通过它我们来实现随时间变化。

首先在 game-loop.ts 中导出需要的变量。

export { deltaTime }

修改你的 fruits.ts 文件

import { cvs_height, ctx_two, anemones } from "./init";
import { deltaTime } from "./game-loop";


class Fruits{
  num: number = 30; // 绘画果实的数量
  alive: boolean[] =[];  // 判断果实是否存活
  x : number[]= []; // 果实的 x 坐标数组
  y : number[] = []; // 果实的 y 坐标数组
  diameter : number[] = []; // 果实的直径数组
  speed: number[] = []; // 控制果实成长速度、上浮速度的数组
  orange = new Image(); // 黄色果实
  blue = new Image(); // 蓝色果实
  constructor(){
    for (let i = 0; i < this.num; ++i) {
      this.alive[i] = true; // 先设置它的存活为 true
      this.diameter[i] = 0; // 未生长出来的果实半径为0
      this.speed[i] = Math.random() * 0.02 + 0.005; // 设置速度在区间 0.005 - 0.025 里
      this.born(i);
    }
    this.orange.src = 'assets/img/fruit.png';
    this.blue.src = 'assets/img/blue.png';
  }

  // 绘制果实
  draw(){
    for (let i = 0; i < this.num; ++i) {

      // 只有属性为存活的时候才绘制
      if(this.alive[i]){
        if(this.diameter[i] <= 20) {
          this.diameter[i] += this.speed[i] * deltaTime; // 随着时间半径不断变大 也就是果实长大
        }else{
          this.y[i] -= this.speed[i] * deltaTime; // 果实成熟之后, y 坐标减小,果实开始上升
        }

        // 把果实绘制出来,为了让果实居中,所以要减去图片高度一半,宽度一半
        // 就像实现水平居中一样 left: 50px; margin-left: -(图片宽度 / 2);
        // 第一个参数 图片, 第二三个参数,坐标轴的 x 和 y,第四五个参数,图片的宽高
        ctx_two.drawImage(this.orange, this.x[i] - this.diameter[i] / 2 , this.y[i] - this.diameter[i], this.diameter[i], this.diameter[i]);
      }

      if(this.y[i] <= -10) {
        this.alive[i] = false; // 果实出去了之后 存活状态为 flase
      }

    }
  }

  // 初始化果实的坐标
  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 坐标,为海葵高度的顶点坐标
  }
}

export default Fruits;

此时的果实上升已经完成了。

Previous绘制果实Next控制果实的数量

Last updated 7 years ago

QQ20170104-0