Search code examples
camerathree.jspositionlineparticles

Find the point of a line after which it dissapears - three.js


I want to position x,y,z labels (sprites) on the axis I have in my scene. The problem is that zooming with the camera , should result to also moving the particles analogously so they stay in the side of the "screen".

So I just want to find a way to always know where the lines of x,y,z are out of the camera to update the labels' positions : fiddle (here they are just static).

the pseudocode of what I might need to acheve that :

    function update() { 
      var pointInLinePosition = calculateLastVisiblePointOfXline();
      xSprite.position.set(pointInLinePosition.x, pointInLinePosition.y, pointInLinePosition.z);
    }

    function calculateLastVisiblePointOfXline(){
    } 

Solution

  • I found a solution which is satisfying enough (for me at least) but not perfect.

    Firstly I create a frustum using the scene's camera :

    var frustum = new THREE.Frustum();
    frustum.setFromMatrix( new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse ) );
    

    Then, I check if any of the planes of the frustum intersects with any of the lines I have in the scene :

    for (var i = frustum.planes.length - 1; i >= 0; i--) { 
    
          var py = frustum.planes[i].intersectLine( new THREE.Line3( new THREE.Vector3(0,0,0), new THREE.Vector3(1000,0,0) ) ) ; 
          if(py !== undefined) {
            ySprite.position.x = py.x-1 ;  
          }
    
          var px = frustum.planes[i].intersectLine( new THREE.Line3( new THREE.Vector3(0,0,0), new THREE.Vector3(0,0,1000) ) ) ; 
          if(px !== undefined) {
            xSprite.position.z = px.z-1 ; 
          }
    
        };
    

    If there is an intersection, I update the labels' position using the return value of the intersectLine() which is the point of intersection.

    This is the updated fiddle : fiddle

    I hope that helps. In my case it fit.