Draw a line connecting two objects and extend it

I made two-sphere geometries I will call them observer and target. I am trying to draw a line from observer to target and extend the line by 700 units. For simplicity, I am only working on the xz plane.
The observer and target move randomly.
I wrote the following code

var lineGeom = new THREE.BufferGeometry();
var positions = new Float32Array( 3 * 3 ); // 3 vertices per point
lineGeom.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
lineGeom.setDrawRange( 0, 3 );
var material = new THREE.LineBasicMaterial( { color: 0xffffff ,linewidth:4} );
line = new THREE.Line( lineGeom, material );
scene.add(line);
tracker(marsMesh,earthMesh);

Tracker function: I calculate the slope of the line based on the observer and target locations then I calculate the third point at a distance of 700 units from the target.

function tracker(observer,target){
    var positions = line.geometry.attributes.position.array;
    console.log(positions)
    positions = [];
    positions.push(observer.position.toArray());
    positions.push(target.position.toArray());
    var m = (target.position.z-observer.position.z)/(target.position.x-observer.position.x);
    var angle = Math.atan(m);
    var tracker = new THREE.Vector3( -700*Math.cos(angle)+target.position.x, 0, -700*Math.cos(angle)+target.position.z ).toArray();
    positions.push(tracker);
}

animate function:

function animate() {
    
    var timer = 0.0001 * Date.now();
    observer.position.x = Math.sin(timer * 3) * 120;
    observer.position.z = Math.cos(timer * 3) * 120;
    observer.rotation.y  += 0.1

    target.position.x = Math.sin(timer * 2) * 200;
    target.position.z = Math.cos(timer * 2) * 200;
    target.rotation.y  += 0.1
    
    line.geometry.setDrawRange( 0, 3 );
    tracker(observer,target);
    line.geometry.verticesNeedUpdate = true;
    
    requestAnimationFrame(animate);
    controls.update();
    render();
}

I can see the observer and target spheres but I don’t see the line. What am I doing wrong? I am new to using three js.

Just for clarification: you want to draw a line and add 700 units to it?

Here is a simple example with the concept of how you can do it: https://jsfiddle.net/prisoner849/8u560zsy/

Thanks! that was very easy to understand. One more question, if I want to show the path traced by the endpoint of the line how do I do it? I think I should store the positions in an array by limiting the size of the array to maybe 1000 points for efficiency. Once I stored the array how do I visualize it?

Recently, I’ve seen how @mjurczyk solved something similar, helping on discord (though it was about dynamic colours, but with the same principle). So all thanks go to him :handshake: https://jsfiddle.net/prisoner849/2gp8kctb/

2 Likes