15

How can I find a point ( C (x,y,z) ) between 2 points ( A(x,y,z) , B(x,y,z) ) in a thgree.js scene?

I know that with this: mid point I can find the middle point between them, but I don't want the middle point, I want to find the point which is between them and also has distance a from the A point?

in this picture you can see what I mean :

enter image description here

Thank you.

Community
  • 1
  • 1
  • 1
    Plenty of info here: http://stackoverflow.com/questions/1250419/finding-points-on-a-line-with-a-given-distance – gaitat Dec 11 '14 at 15:37

3 Answers3

41

Basically you need to get the direction vector between the two points (D), normalize it, and you'll use it for getting the new point in the way: NewPoint = PointA + D*Length.

You could use length normalized (0..1) or as an absolute value from 0 to length of the direction vector.

Here you can see some examples using both methods:

Using absolute value:

function getPointInBetweenByLen(pointA, pointB, length) {
    
    var dir = pointB.clone().sub(pointA).normalize().multiplyScalar(length);
    return pointA.clone().add(dir);
       
}

And to use with percentage (0..1)

function getPointInBetweenByPerc(pointA, pointB, percentage) {
    
    var dir = pointB.clone().sub(pointA);
    var len = dir.length();
    dir = dir.normalize().multiplyScalar(len*percentage);
    return pointA.clone().add(dir);
       
}

See it in action: http://jsfiddle.net/8mnqjsge/

Hope it helps.

Community
  • 1
  • 1
fernandojsg
  • 1,090
  • 18
  • 27
2

I know the question is for THREE.JS and I end up looking for something similar in Babylon JS.

Just in case if you are using Babylon JS Vector3 then the formula would translate to:

function getPointInBetweenByPerc(pointA, pointB, percentage) {

    var dir = pointB.clone().subtract(pointA);
    var length = dir.length();
    dir = dir.normalize().scale(length *percentage);
    return pointA.clone().add(dir);

  }

Hope it help somebody.

Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
2

This is known as lerp between two points

e.g. in Three: C = new Three.Vector3() C.lerpVectors(A, B, a)

also in generic this is just a single lerp (linear interpolation) math (basically (a * t) + b * (1 - t)) on each axis. Lerp can be described as follows:

function lerp (a,  b,  t) {
    return a + t * (b - a)
}

in your case (see above) :

A = {
  x: lerp(A.x, B.x, a),
  y: lerp(A.y, B.y, a),
  z: lerp(A.z, B.z, a)
}
hhamm
  • 1,511
  • 15
  • 22