admin管理员组

文章数量:1406924

For a camera movement in three.js I need to calculate point C so to move the camera from point A to a certain distance dist to point B.

For a camera movement in three.js I need to calculate point C so to move the camera from point A to a certain distance dist to point B.

Share Improve this question asked Mar 15, 2018 at 23:39 piaaaacpiaaaac 612 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

three.js has methods to do that very easily.

Assuming a, b, and c are instances of THREE.Vector3(),

a.set( 2, 1, 4 );
b.set( 9, 4, 2 );

c.subVectors( a, b ).setLength( dist ).add( b );

three.js r.91

So you need to calculate the coordinates of point C, given that it lies on the line between B and A at the given distance from B? This is pretty straightforward using the following steps:

  • Calculate the vector from B to A (this will just be A - B).
  • Normalize that vector (make it's length 1).
  • Multiply that by the distance you want.
  • Add that vector to the point B.

So a short javascript example:

const A = [2, 1, 4];
const B = [9, 4, 2];

const dist = 3;

function addVectors(v1, v2) {
    return v1.map((x, i) => x + v2[i]);
}

function scalarMultiply(v, c) {
    return v.map(x => x*c);
}

function getLength(v) {
    return Math.hypot(...v);
}

const vecB2A = addVectors(A, scalarMultiply(B, -1)); // Step 1
const normB2A = scalarMultiply(vecB2A, 1/getLength(vecB2A)); // Step 2
const distB2A = scalarMultiply(normB2A, dist); // Step 3
const C = addVectors(B, distB2A); // Final step

console.log(C);

Point C is equal to point B minus 'dist' times a unit vector whose direction is AB. So it is quite easy:

vector v from A to B is equal (xB-xA, yB-yA, zB-zA) / distance(AB)

Then C = B - d*v where d is the distance from B you want C to be.

本文标签: javascriptCalculate point in 3d spacebetween two points at specific distanceStack Overflow