画布中动画效果最流畅

时间:2016-09-19 13:39:53

标签: javascript jquery canvas html5-canvas

我想在下列条件下尽可能顺利地使坐标(coord1)跟随另一个坐标(coord2):

  1. coord2能够移动。
  2. coord1以最平滑的方式跟踪coord2(弧形方式)。
  3. coord1以恒定速度跟随。
  4. 我在这里有一个例子,但只有条件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 个答案:

答案 0 :(得分:1)

跟随对象创建从色调对象到另一个对象的向量。矢量具有方向和长度。长度是速度,方向是它的前进方向。

我已经把你的小提琴分开来表明这是有效的。唯一的变化是跟随功能。 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;
相关问题