Creating curved edges in Three.js using Javascript

One of my functions involves creating a track using 3D points from a separate file called trackline.json. The example data in the file looks something like this:

[{"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 function creates multiple 3D lines (vectors) that are meant to serve as a camera path. However, the lines have sharp edges at each end. I am looking for a way to calculate additional points to smooth out these lines or any other efficient method to achieve this.

Below is the code snippet responsible for creating 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);
}

Here's a simple 2D visualization of the issue:

https://i.sstatic.net/3Ydyt.png

Answer №1

Utilizing SplineCurve in THREE.js enables you to effortlessly create a smooth curve with specified 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 splinePoints = curve.getPoints( 50 );
const curveGeometry = new THREE.BufferGeometry().setFromPoints( splinePoints );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically determining the direction of a page with Vue Js

Is it possible to dynamically set the page direction (RTL or LTR) in a Vue js project? I have tried setting it dynamically using a variable called direction but it doesn't seem to work (it continues to use the standard LTR value): <html lang="e ...

Message from Discord: Unable to access the property 'MessageEmbed' because it is undefined

Attempting to create a simple welcome message embed. Here is my main.js file without the login token: const Discord = require('discord.js'); const client = new Discord.Client(); const MessageEmbed = new Discord.MessageEmbed(); const prefix = &ap ...

Every time I attempt to load the table, I encounter an error

Encountering errors when attempting to load the table: 'Uncaught ReferenceError: usersArray is not defined at loadUsers (trgames.js:20:17) at trgames.js:22:1' and 'Uncaught TypeError: Cannot set properties of null (setting ...

`validate.js verifying the elements within an array`

One of the challenges I'm facing in my JavaScript project is dealing with objects that have two array properties included. As part of my development process, I've decided to utilize the resources provided by the validate.js library. To illustrat ...

Retrieving the status of a checkbox using jQuery to obtain a value of 1 or

Incorporating jQuery, I am able to retrieve the values of all input fields using the provided code snippet. However, an issue arises when dealing with checkboxes as they return "on" if checked. How can I modify this to receive a value of 1 when a checkbox ...

Changing the image source when clicking on it and removing it can be done by using JavaScript

How can I add a class 'selected' to ".swiper-slide" when it is clicked? I also want to change the image src when svg-img1, 2, or 3 is clicked. However, I need the image to revert back to its default src when another swiper-slide is clicked. ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

Update the configurable product process for the custom attribute 'delivery_time' in Magento 1.9.2

I am currently using Magento 1.9.2.4 (1.9.2.3 in my Testpage) and I have a few configurable products with multiple options. Each product (child of the configurable one) has a different delivery time. To achieve this, I created an attribute called "delivery ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Having trouble with adding data from an array of objects to an HTML element using jQuery's each method

I am currently facing an issue with looping through an array of objects using $.each in jQuery and trying to append the values to an <li>. Here is the relevant jQuery code: $(".sidebar").empty().append("<div>" + "<h5>Student Info</ ...

The integration of Google Translate with Javascript on HtmlEditorExtender is experiencing difficulties and is not functioning properly

I implemented the use of a text box with ajaxtoolkit HtmlEditorExtender (Rich textbox) to translate English to Gujarati using Google translation Javascript. The translation function works perfectly with the regular text box, but encounters issues when used ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

I'm encountering an issue with this error message: "Warning: Each item in a list must be assigned a unique 'key' prop."

I encountered an error message... Warning: Each child in a list should have a unique "key" prop. I'm puzzled about this because I believe I have assigned a unique key for my map. All the resources I've checked regarding this warning are relat ...

Issue with Generating divs dynamically in Ionic Framework

I'm currently working on dynamically generating a board game using divs in AngularJS, like so: HTML: <div class="boardgame" ng-repeat="square in board"> <div class="square"></div> </div> JS: $scope.board = [ {value: ...

Error: Using `[object HTMLDocument]` as a selector is not recognized in firefox

How can I load my local javascript library and execute an alert command? var jq = document.createElement('script'); jq.src = "http://127.0.0.1/js/jquery-3.3.1.min.js"; document.getElementsByTagName('head')[0].appendChild(jq); $(documen ...

The input field malfunctioned after the clear button was pressed

Hi there, I have a question. Every time I try to click on the clear button, it keeps giving me an error message and I'm not sure what the issue is. Also, I can't type in the field anymore after clicking it. methods: { add () { this.ta ...

Issues with event firing when using the tag

I've been exploring the use tag within an svg element. I managed to get a simple example working on JSFiddle: https://jsfiddle.net/cneLLLqu/ When I click on the red square (outside of the defs and use tags), a message box pops up. However, clicking o ...

(Definition) What is the proper way to reference a variable inside another variable?

Currently, my project is using inconsistent terminology when referring to variables, and I need to clarify this issue. Let's take an object defined in this way: var anObject = { a: { value1: 1337, value2: 69, value3: "420 ...

Issue - The 'defaultValue' is failing to load the state value, and the 'value' is not being updated when changed

My current setup involves an input field in my MovieInput.tsx file: <input id="inputMovieTitle" type="text" onChange={ e => titleHandleChange(e) } value={ getTitle() }> </input> This is how the titleHandleChange function ...

PHP scripts for performing multiplication and subtraction operations

My goal is to create a PHP script that can determine the total miles driven by a car rental customer (at a rate of 0.12 cents per mile), calculate the cost based on the number of days they rented the car ($15 per day), and display the grand total in a text ...