代码之家  ›  专栏  ›  技术社区  ›  Victor Wei

画布中最平滑的后续动画

  •  0
  • Victor Wei  · 技术社区  · 9 年前

    我想在以下条件下使坐标(coord1)跟随另一个坐标(coord2)尽可能平滑:

    1. coord2能够移动。
    2. coord1以最平滑的方式跟随coord2(弧形方式)。

    我这里有一个例子,但它只成功于条件1和条件3,而不是条件2。在这个例子中,你可以用箭头键移动球。 Click here to go to the example

    以下是我的代码:

    Obstacle.prototype.follow = function () {
      this.y += this.vSpeed
      this.x += this.hSpeed
    
      if (this.x < ball.x - 9) {
        this.hSpeed = 1;
      }
      if (this.x > ball.x - 10) {
        this.hSpeed = -1;
      }
      if (this.y > ball.y - 10) {
        this.vSpeed = -1;
      }
      if (this.y < ball.y - 9) {
        this.vSpeed = 1;
      }
    }
    

    有人能解决这三个条件吗?

    1 回复  |  直到 9 年前
        1
  •  1
  •   Blindman67    9 年前

    要跟随一个对象,请创建一个从色调对象到另一个对象的矢量。向量有方向和长度。长度就是速度,方向就是它要去的地方。

    我已经用叉子把你的小提琴分叉来表示这一点。唯一的变化是以下功能。 https://jsfiddle.net/blindman67/ksu518cg/2/

    // obj one 
    var x1 = 100;
    var y1 = 100;
    
    // object to follow
    var x2 = 300;
    var y2 = 200; 
    

    每个动画都会为距离设置帧

    var dist = Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));  // distance
    

    创建长度为1像素的矢量

    var dx = (x2-x1)/dist;
    var dy = (y2-y1)/dist;
    

    乘以你想要移动的速度

    dx *= speed;
    dy *= speed;
    

    然后添加到对象位置

    x2 += dx;
    y2 += dy;