很明显,我们是通过移动鼠标来控制鱼,那当然是我们鼠标的坐标。
在 init.ts 里面声明俩个变量来保存我们的鼠标坐标,并且通过监听我们的鼠标移动事件,来获得我们鼠标的坐标。
- 创建监听函数
这里的 offset 会比 layer 大 1
function mouseMove(e: MouseEvent) {
// offset = layer + 1
if(e.offsetX || e.layerX) {
mouse_x = typeof e.offsetX == undefined ? e.layerX : e.offsetX
mouse_y = typeof e.offsetY == undefined ? e.layerY : e.offsetY
}
console.log(mouse_x);
console.log(mouse_y);
}
- 修改 init 函数,为 canvas one 添加事件监听
function init() {
[cvs_one, ctx_one] = getCanvasAndContextById('one');
[cvs_two, ctx_two] = getCanvasAndContextById('two');
bgPic.src = 'assets/img/background.jpg';
cvs_width = cvs_one.width;
cvs_height = cvs_one.height;
fruits = new Fruits()
fish_mother = new FishMother()
mouse_x = cvs_width / 2; // 先把鱼初始化在画布的中间
mouse_y = cvs_height / 2;
// 因为鱼是在 canvas one 上面,所以把监听添加到 one 上面
cvs_one.addEventListener('mousemove', mouseMove, false);
}
- 添加导出
- 在 fish-mother.ts 使用坐标,首先先导入。
import { ctx_one, cvs_height, cvs_width, mouse_x, mouse_y } from "./init";
- 更新 draw 函数
draw(){
this.x = mouse_x
this.y = mouse_y
ctx_one.save();
ctx_one.translate(this.x, this.y); // 定义相对定位的坐标中心点
ctx_one.scale(.7, .7);
ctx_one.drawImage(this.bigBody, -this.bigBody.width / 2, -this.bigBody.height / 2);
ctx_one.restore();
}
- 创建一个带有缓冲功能的函数
每一次设置值只是设置一个趋近于鼠标位置的值,这样就会有一个渐变的过程,就不会那么突然。
而不是直接就等于,当鼠标与鱼的位置重合时,lerpDistance
就返回的 aim
新建 utils.ts 文件
第一帧时
cur: 20
aim: 10
ratio: 0.9
delta 10
return 19 = 10 + 10 * 0.9
this.x = 19
第二帧,此时的 cur = 19
cur: 19
aim: 10
delta 9
return 18.1 = 10 + 9 * 0.9
第三帧,此时 cur = 18.1
- 在 fish-mother.ts 中使用这个函数
再次试一试,看看鱼儿是如何动起来的。