贪吃蛇身匀速运动模型

通用运动模型

在这里插入图片描述

我们已知斜线为移动的距离dddxxx轴总偏移量为dxdxdxyyy轴总偏移量为dydydy,在一帧当中,我们也知道能走的距离为mdmdmd。那么作为一般的运动模型,该如何确定我们进行移动的方向呢?需要向夹角θθθ的方向移动,这样我们移动的所有点都在直角三角形的斜边上,这是一个正确的移动模式。
在这里插入图片描述

从上图我们可以看到,需要求的就是mdxmdxmdxmdymdymdy了。也就是mdmdmdxxx轴和yyy轴上的投影。我们可以简单思考确定物体移动方向的问题,夹角θθθ决定了物体移动的方向。其中,sinθ=dy/dsinθ=dy/dsinθ=dy/dcosθ=dx/dcosθ=dx/dcosθ=dx/d,若要沿相同角度出发,即两次的θθθ相同,那么也应该有对应的sinθ2sinθ_2sinθ2cosθ2cosθ_2cosθ2
整个过程就是从结果反推过程:

  1. 一个点是如何移动到目标位置的呢?向thetathetatheta方向移动mdmdmd
  2. 如何达到mdmdmd呢?先朝xxx轴走一点,再朝yyy轴走一点。
  3. x、yx、yxy走多少呢?具体计算…
简易版运动模型

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

在这里插入图片描述

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

  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)因此当动作为000(向上)时,我们要给yyy减去偏移量而不是xxx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值