计算坐标轴上面俩个点的距离,大家应该记得,利用了勾三股四原理,不记得百度一下就会立即想起了。

    首先我们准备一个计算距离的函数,把它放在 utils.ts 文件里面

    所有需要实时监测的、动画相关的,我们都需要写到循环里面去,在 game-loop.ts 文件里面准备我们的碰撞检测函数。

    1. * 鱼妈妈与果实的碰撞检测
    2. */
    3. function fishAndFruitsCollision() {
    4. for (let i = fruits.num; i >= 0; i--) {
    5. // 假如或者就计算鱼儿与果实的距离
    6. if(fruits.alive[i]) {
    7. // 得到距离的平方根
    8. const distance = utils.getDistance(
    9. {x: fruits.x[i], y: fruits.y[i]},
    10. {x: fish_mother.x, y: fish_mother.y}
    11. );
    12. if(distance < 700) {
    13. fruits.dead(i)
    14. }
    15. }
    16. }
    17. }

    碰撞之后要死亡,尽管我们可以直接在函数里面改,但是为了封装性,我们还是在 fruits.ts 里面增加一个 dead 函数

    1. function gameLoop() {
    2. const now = Date.now()
    3. deltaTime = now - lastTime;
    4. lastTime = now;
    5. drawBackbround() // 画背景图片
    6. anemones.draw() // 海葵绘制
    7. fruits.draw() // 果实绘制
    8. fruits.monitor() // 监视果实,让死去的果实得到新生
    9. ctx_one.clearRect(0, 0, cvs_width, cvs_width); // 清除掉所有,再进行绘制,要不然的话会多次绘制而进行重叠。
    10. fish_mother.draw() // 绘制鱼妈妈
    11. fishAndFruitsCollision() // 每一帧都进行碰撞检测
    12. requestAnimationFrame(gameLoop); // 不断的循环 gameLoop,且流畅性提升
    13. }

    此时我们的与应该可以吃果实了。

    此时我们再优化一下细节,在 game-loop 给 deltaTime 设置一个上线值,避免切换到其他 tag 的时候,暂停渲染,导致俩次渲染的间隔很大,导致果子巨大失真。

    所以我们需要修改下 fish-mother.ts

    1. this.x = utils.lerpDistance(mouse_x, this.x , .95)
    2. this.y = utils.lerpDistance(mouse_y, this.y , .95)
    3. // ....