贪吃蛇身匀速运动模型

通用运动模型

我们已知斜线为移动的距离 d d d, x x x轴总偏移量为 d x dx dx, y y y轴总偏移量为 d y dy dy,在一帧当中,我们也知道能走的距离为 m d md md。那么作为一般的运动模型,该如何确定我们进行移动的方向呢?需要向夹角 θ θ θ的方向移动,这样我们移动的所有点都在直角三角形的斜边上,这是一个正确的移动模式。

从上图我们可以看到,需要求的就是 m d x mdx mdx和 m d y mdy mdy了。也就是 m d md md在 x x x轴和 y y y轴上的投影。我们可以简单思考确定物体移动方向 的问题,夹角 θ θ θ决定了物体移动的方向。其中, s i n θ = d y / d sinθ=dy/d sinθ=dy/d, c o s θ = d x / d cosθ=dx/d cosθ=dx/d,若要沿相同角度出发,即两次的 θ θ θ相同,那么也应该有对应的 s i n θ 2 sinθ_2 sinθ2和 c o s θ 2 cosθ_2 cosθ2。

整个过程就是从结果反推过程:

  1. 一个点是如何移动到目标位置的呢?向 t h e t a theta theta方向移动 m d md md。
  2. 如何达到 m d md md呢?先朝 x x x轴走一点,再朝 y y y轴走一点。
  3. 朝 x 、 y x、y x、y走多少呢?具体计算...
简易版运动模型

当然,这是一个通用的运动模型,即在物体运动的动作空间为连续(360度随便走)时和离散时(如本项目:上右下左)都适用。我们可以想到,当我们的贪吃蛇向右走时,其实只有 y y y轴(标准坐标系,非canvas)有移动,因此我们要移动的总距离 d d d和每一帧移动距离 m d md md都只会分配到 y y y轴上 ,该公式理论上恒成立 d y / d = 1 dy/d=1 dy/d=1(具体计算中可能有浮点数精度问题)。

有了这个想法,我们就可以实现一个仅适用本项目的离散版本的。

js 复制代码
  update_move() {
    const distance = Math.sqrt(dx * dx + dy * dy);
    if (distance < this.eps) {
      this.cells[0] = this.next_cell;
      this.next_cell = null;
      this.status = "idle";
      this.direction = -1;

      if (!this.check_tail_increasing()) {
        this.cells.pop();
      }
    } else {
      const move_distance = this.speed * this.timedelta / 1000; 
      // 设置snake0
      if (this.id === 0) {
        if (this.direction === 0) this.cells[0].y -= move_distance;
        else if (this.direction === 1) this.cells[0].x += move_distance;
        else if (this.direction === 2) this.cells[0].y += move_distance;
        else if (this.direction === 3) this.cells[0].x -= move_distance;
      }
      // 设置snake1
      if (this.id === 1) {
        if (this.direction === 0) this.cells[0].y -= move_distance;
        else if (this.direction === 1) this.cells[0].x += move_distance;
        else if (this.direction === 2) this.cells[0].y += move_distance
        else if (this.direction === 3) this.cells[0].x -= move_distance;
      }
    }
  }

这段代码就是如果当前为移动状态,每一帧刷新时直接根据获取的direction添加固定方向的偏移量。注意上面是渲染cell,因此 ( x , y ) (x,y) (x,y)会变成 ( y , x ) (y,x) (y,x)因此当动作为 0 0 0(向上)时,我们要给 y y y减去偏移量而不是 x x x。

相关推荐
孟无岐1 天前
【Laya】Laya 类使用说明
typescript·游戏引擎·游戏程序·laya
郝学胜-神的一滴4 天前
深入理解Mipmap:原理、实现与应用
c++·程序人生·unity·游戏程序·图形渲染·unreal engine
呆呆敲代码的小Y7 天前
【Unity 实用工具篇】| UX Tool 工具 快速上手使用,提高日常开发效率
游戏·unity·游戏引擎·游戏程序·ux
郝学胜-神的一滴7 天前
OpenGL纹理技术详解:从原理到实践
c++·程序人生·游戏程序·图形渲染·贴图
心疼你的一切12 天前
【技术创作的璀璨盛宴——2025年CSDN博客之星总评选深度总结】
microsoft·unity·游戏引擎·游戏程序·csdn·博客之星
OC溥哥99914 天前
2D我的世界创造模式网页版正式出炉——《我们的2D创造世界:无限创意,多人同乐》欢迎来到ourcraft.xin网站上玩
后端·python·阿里云·flask·html·游戏程序
行思理17 天前
小游戏系统提供二开服务
layui·游戏程序·小游戏·thinkphp
星依网络25 天前
yolov5实现游戏图像识别与后续辅助功能
python·开源·游戏程序·骨骼绑定
郝学胜-神的一滴1 个月前
OpenGL中的glDrawArrays函数详解:从基础到实践
开发语言·c++·程序人生·算法·游戏程序·图形渲染
星依网络1 个月前
易语言开发FPS游戏辅助科技脚本示例
自然语言处理·游戏程序·图形渲染·骨骼绑定