Search code examples
javascriptvectorthree.js3dline

Javascript Three.js lines round edges


I Have a function to create a Track using 3D Points from a separate trackline.json file with the following example data:

[{"x":5.01088018657063,"y":0.033095929202426655,"z":-1.469083126575439},{"x":-2.836023686139761,"y":1.2315534616542192,"z":-2.623173656748311},{"x":-5.188269059945695,"y":-3.889753328348702,"z":2.4758137354826646},{"x":0.5400173030307891,"y":-4.415289185011361,"z":3.7757418987784406},{"x":4.475184816920873,"y":-0.3696880702837009,"z":0.6426064577081578}]

This Creates Multiple 3d Lines (3D Vectors) which should be used as a camera path. But the Lines have sharp edges at each end of the line. How can i calculate more Points to smoothen the lines or is there a faster way to implement this?

This is my Code which Creates the Track-Lines:

    setupTrackline() {
    fetch('trackline.json')
        .then(response => {
            return response.json();
        })
        .then(data => {
            // Process the data if needed
            console.log(data); // Check the retrieved data
            this.setupTracklineWithData(data);
        })
        .catch(error => {
            console.error('Error fetching trackline.json:', error);
        });
}

setupTracklineWithData(data) {
    // Assuming the data is an array of Vector3 objects, adjust this part accordingly
    const points = data.map(position => new THREE.Vector3(position.x, position.y, position.z));

    const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
    const lineMaterial = new THREE.LineBasicMaterial({ color: 0x00dd00 }); // Green color for the line

    this.trackline = new THREE.Line(lineGeometry, lineMaterial);
}

This is a 2D Example Vizualization for the Problem:

enter image description here


Solution

  • You can use SplineCurve to create a smooth curve from points.

    const curve = new THREE.SplineCurve( [
        new THREE.Vector2( -10, 0 ),
        new THREE.Vector2( -5, 5 ),
        new THREE.Vector2( 0, 0 ),
        new THREE.Vector2( 5, -5 ),
        new THREE.Vector2( 10, 0 )
    ] );
    
    const points = curve.getPoints( 50 );
    const geometry = new THREE.BufferGeometry().setFromPoints( points );