创建鱼宝宝

鱼妈妈与鱼宝宝都是鱼,所以我们可以抽象一些它们相同的部分,这里又俩种方式,一种是通过函数去创建,也就是鱼厂,这个是面向过程编程。此时我们写面向对象代码,使用继承来减少代码。

因为鱼宝宝是要跟着鱼妈妈的,所以我们把鱼妈妈跟着鼠标的坐标改一下就能用了。

修改一下鱼宝宝的初始坐标。因为 fish-mother.ts 文件要放鱼妈妈和鱼宝宝,所以叫个个名字就不合适了,我们把它改成 fish.ts ,所以下面代码写到 fish.ts 里面。

import { ctx_one, cvs_height, cvs_width, mouse_x, mouse_y, fish_mother } from "./init";
import utils from "./utils";

// 鱼妈妈
class FishMother{
  x: number = cvs_width / 2; // 坐标轴 x
  y: number = cvs_height / 2 ; // 坐标轴 y
  bigEye = new Image(); // 眼睛
  bigBody = new Image(); // 身体
  BigTail = new Image(); // 尾巴
  angle: number = 0; // 鱼的角度
  constructor(){
    this.bigEye.src = 'assets/img/bigEye0.png';
    this.bigBody.src = 'assets/img/bigSwim0.png';
    this.BigTail.src ='assets/img/bigTail0.png';
  }

  draw(){

    this.x = utils.lerpDistance(mouse_x, this.x , .95)
    this.y = utils.lerpDistance(mouse_y, this.y , .95)


    let instance_X = mouse_x - this.x; // 边 a
    let instance_Y = mouse_y - this.y; // 边 b

    let ag = Math.atan2(instance_Y, instance_X) + Math.PI // [-PI, PI]

    this.angle = utils.lerpAngle(ag, this.angle, .9)

    ctx_one.save();
    ctx_one.translate(this.x, this.y); // 定义相对定位的坐标中心点
    ctx_one.rotate(this.angle);
    ctx_one.scale(.8, .8);
    ctx_one.drawImage(this.BigTail, -this.BigTail.width / 2 + 30, -this.BigTail.height / 2); // 这里的尾巴,往右移动30像素,让它在身体的后面。
    ctx_one.drawImage(this.bigBody, -this.bigBody.width / 2, -this.bigBody.height / 2);
    ctx_one.drawImage(this.bigEye, -this.bigEye.width / 2, -this.bigEye.height / 2); // 居中,所以向左移动宽度的一半,向上移动宽度的一半

    ctx_one.restore();

  }
}

// 鱼宝宝
class FishBaby extends FishMother {
  x: number = cvs_width / 2 + 50; // 坐标轴 x
  y: number = cvs_height / 2 + 50; // 坐标轴 y
  constructor() {
    super()
    this.bigEye.src = 'assets/img/babyEye0.png';
    this.bigBody.src = 'assets/img/babyFade0.png';
    this.BigTail.src = 'assets/img/babyTail0.png';
  }

  draw(){

    this.x = utils.lerpDistance(fish_mother.x, this.x , .98)
    this.y = utils.lerpDistance(fish_mother.y, this.y , .98)

    let instance_X = fish_mother.x - this.x; // 边 a
    let instance_Y = fish_mother.y - this.y; // 边 b

    let ag = Math.atan2(instance_Y, instance_X) + Math.PI // [-PI, PI]

    this.angle = utils.lerpAngle(ag, this.angle, .7)

    ctx_one.save();
    ctx_one.translate(this.x, this.y); // 定义相对定位的坐标中心点
    ctx_one.rotate(this.angle);
    ctx_one.scale(.8, .8);
    ctx_one.drawImage(this.BigTail, -this.BigTail.width / 2 + 30, -this.BigTail.height / 2); // 这里的尾巴,往右移动30像素,让它在身体的后面。
    ctx_one.drawImage(this.bigBody, -this.bigBody.width / 2, -this.bigBody.height / 2);
    ctx_one.drawImage(this.bigEye, -this.bigEye.width / 2, -this.bigEye.height / 2); // 居中,所以向左移动宽度的一半,向上移动宽度的一半

    ctx_one.restore();

  }
}

export {
  FishMother,
  FishBaby
}

因为修改了文件名和导入导出,所以我们还需要修改一下其他模块的代码。比如 init.ts 文件,我们需要在 init 里面初始化鱼宝宝。

在 game-loop.ts 里面画鱼宝宝。

鱼宝宝已经绘制完毕啦。

Last updated