Search code examples
javascriptthree.jsline

How to clone the Mesh of a Line object in THREE.js?


Im trying to create a for loop of 10 lines . However line.Clone() gives me an error, since it doesnt find any mesh to clone from? Please if you know how to acces the mesh of a line let me know.

Here is some code:

forward_RT(){

    var spotLight = new THREE.SpotLight( 0xffffff ); //White Color
    spotLight.position.set( 150, 500, -210 );
    scene_Main.add( spotLight );

    var material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
    var geometry = new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3( spotLight.position.x, spotLight.position.y, spotLight.position.z) );
    geometry.vertices.push(new THREE.Vector3( ray_End_pos_X, ray_End_pos_Y, ray_End_pos_Z) );

    var line = new THREE.Line( geometry, material );

    for(var i=0; i<10; i++){
        //Also tried 
        //var newLine = line.clone(); & scene_Main.add(newLine);
        scene.add(line.clone());

        ray_End_pos_X += 50;
    }
}

Solution

  • There are several problems with your code (e.g. you increment ray_End_pos_X but do not use it in the loop). I have a suspicion you probably only need to change geometry during each iteration.

    I would go with new lines from cloned geometry and shared material. I quickly checked, this works:

        var rayX = 0, rayY=0, rayZ = 0;
    
        var material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
        var geometry = new THREE.Geometry();
        geometry.vertices.push(new THREE.Vector3( spotLight.position.x, spotLight.position.y, spotLight.position.z) );
        geometry.vertices.push(new THREE.Vector3( rayX, rayY, rayZ) );
    
        for(var i=0; i<10; i++) {
            var newLine = new THREE.Line(geometry.clone(), material);
            newLine.geometry.vertices[1].x = rayX;
            this.context.scene.add(newLine);
            rayX += 0.1;
        }
    

    This is how it looks (red lines, the rest is irrelevant):

    result screenshot