Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving object from vector A to B in 2d environment with in increments of percents

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.

like image 767
newbie Avatar asked Jun 01 '11 08:06

newbie


2 Answers

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.

like image 108
aib Avatar answered Oct 08 '22 02:10

aib


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);
like image 14
Eric Avatar answered Oct 08 '22 01:10

Eric