很明显,我们是通过移动鼠标来控制鱼,那当然是我们鼠标的坐标。

    在 init.ts 里面声明俩个变量来保存我们的鼠标坐标,并且通过监听我们的鼠标移动事件,来获得我们鼠标的坐标。

    • 创建监听函数

    这里的 offset 会比 layer 大 1

    1. function mouseMove(e: MouseEvent) {
    2. // offset = layer + 1
    3. if(e.offsetX || e.layerX) {
    4. mouse_x = typeof e.offsetX == undefined ? e.layerX : e.offsetX
    5. mouse_y = typeof e.offsetY == undefined ? e.layerY : e.offsetY
    6. }
    7. console.log(mouse_x);
    8. console.log(mouse_y);
    9. }
    • 修改 init 函数,为 canvas one 添加事件监听
    1. function init() {
    2. [cvs_one, ctx_one] = getCanvasAndContextById('one');
    3. [cvs_two, ctx_two] = getCanvasAndContextById('two');
    4. bgPic.src = 'assets/img/background.jpg';
    5. cvs_width = cvs_one.width;
    6. cvs_height = cvs_one.height;
    7. fruits = new Fruits()
    8. fish_mother = new FishMother()
    9. mouse_x = cvs_width / 2; // 先把鱼初始化在画布的中间
    10. mouse_y = cvs_height / 2;
    11. // 因为鱼是在 canvas one 上面,所以把监听添加到 one 上面
    12. cvs_one.addEventListener('mousemove', mouseMove, false);
    13. }
    • 添加导出
    • 在 fish-mother.ts 使用坐标,首先先导入。
    1. import { ctx_one, cvs_height, cvs_width, mouse_x, mouse_y } from "./init";
    • 更新 draw 函数
    1. draw(){
    2. this.x = mouse_x
    3. this.y = mouse_y
    4. ctx_one.save();
    5. ctx_one.translate(this.x, this.y); // 定义相对定位的坐标中心点
    6. ctx_one.scale(.7, .7);
    7. ctx_one.drawImage(this.bigBody, -this.bigBody.width / 2, -this.bigBody.height / 2);
    8. ctx_one.restore();
    9. }
    • 创建一个带有缓冲功能的函数

    每一次设置值只是设置一个趋近于鼠标位置的值,这样就会有一个渐变的过程,就不会那么突然。

    而不是直接就等于,当鼠标与鱼的位置重合时,lerpDistance 就返回的 aim

    新建 utils.ts 文件

    第一帧时

    1. cur: 20
    2. aim: 10
    3. ratio: 0.9
    4. delta 10
    5. return 19 = 10 + 10 * 0.9
    6. this.x = 19

    第二帧,此时的 cur = 19

    1. cur: 19
    2. aim: 10
    3. delta 9
    4. return 18.1 = 10 + 9 * 0.9

    第三帧,此时 cur = 18.1

    • 在 fish-mother.ts 中使用这个函数

    再次试一试,看看鱼儿是如何动起来的。