6

I know coordinates of vectors A and B. How can I count first point between these two vectors? First vector X is 1% of the distance between vectors A and B. So first I will move object in vector A 1% closer to vector B. So I need to calculate vector X that is new vector for object, until it reaches vector B.

Eric
  • 95,302
  • 53
  • 242
  • 374
newbie
  • 24,286
  • 80
  • 201
  • 301

2 Answers2

19

You want lerping. For reference, the basic formula is:

x = A + t * (B - A)

Where t is between 0 and 1. (Anything outside that range makes it an extrapolation.)

Check that x = A when t = 0 and x = B when t = 1.

Note that my answer doesn't mention vectors or 2D.

aib
  • 45,516
  • 10
  • 73
  • 79
14

Turning aib's answer into code:

function lerp(a, b, t) {
    var len = a.length;
    if(b.length != len) return;

    var x = [];
    for(var i = 0; i < len; i++)
        x.push(a[i] + t * (b[i] - a[i]));
    return x;
}

var A = [1,2,3];
var B = [2,5,6];

var X = lerp(A, B, 0.01);
Community
  • 1
  • 1
Eric
  • 95,302
  • 53
  • 242
  • 374