开发者

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 n开发者_StackOverflow中文版ew vector for object, until it reaches vector B.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜