Crafting a smooth curve between a pair of points using Three.js

I am currently working on a Three.js visualization project where I need to connect points using a spline.

After adding points to an array and passing it to THREE.SplineCurve3, I am able to render the spline by stepping through the points. However, I encounter an error when trying to add a mid-point along with the start and end points.

You can find an example of the issue here:

http://jsfiddle.net/sLQK9/4/

I believe the solution is simple, but I am unable to identify it. Can anyone provide assistance?

Ultimately, I aim to visualize the points on the surface of a sphere, with the splines between them following the path an aircraft would take. This means the spline will resemble a great circle, but further away from the center of the sphere at the midpoint.

Thank you in advance for your help.

Answer №1

When working with splines, it's important to specify the number of points you want the curve to interpolate in order to achieve the desired smoothness. Simply providing control points is not enough for the curve to know how smooth you want it to be.

Consider the following approach:

// Define the number of points for smoothing the curve
var numPoints = 100;

spline = new THREE.SplineCurve3([
   new THREE.Vector3(0, 0, 0),
   new THREE.Vector3(0, 200, 0),
   new THREE.Vector3(150, 150, 0),
   new THREE.Vector3(150, 50, 0),
   new THREE.Vector3(250, 100, 0),
   new THREE.Vector3(250, 300, 0)
]);

var material = new THREE.LineBasicMaterial({
    color: 0xff00f0,
});

var geometry = new THREE.Geometry();
var splinePoints = spline.getPoints(numPoints);

for(var i = 0; i < splinePoints.length; i++){
    geometry.vertices.push(splinePoints[i]);  
}

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

Additionally, as mentioned in @juan Mellado's answer, you can determine a position on the spline using spline.getPoint(t), where t is a value between 0-1 representing the start and end points of the spline.

For more information, check out this related question that provides a helpful example.

Answer №2

Here is a technique I use to create curves between two points in a 3D scene, particularly on a globe:

function generateCurve(start, end, elevation) {
    var startPoint3D = globe.translateCoordinatesToPoint(start.latitude, start.longitude);
    var endPoint3D = globe.translateCoordinatesToPoint(end.latitude, end.longitude);
    var midPoint = (new LatLon(start.latitude, start.longitude)).midpointTo(new LatLon(end.latitude, end.longitude));
    var middlePoint3D = globe.translateCoordinatesToPoint(midPoint.lat(), midPoint.lon(), elevation);

    var curve = new THREE.QuadraticBezierCurve3(startPoint3D, middlePoint3D, endPoint3D);
    //   var curve = new THREE.CubicBezierCurve3(startPoint3D, startPoint3D_control, endPoint3D_control, endPoint3D);

    var curvePath = new THREE.CurvePath();
    curvePath.add(curve);
    //   curvePath.add(curve);
    return curvePath;
}

Then you can call the function like this:

var curvePath = globe.generateCurve(item1, item2, 200);
var curveMaterial = new THREE.LineBasicMaterial({color: 0xFFFFAA, linewidth: 3});
var curveLine = new THREE.Line(curvePath.createPointsGeometry(20), curveMaterial);
globe.scene.add(curveLine);

Keep in mind the Quadratic or Cubic method of curve creation.

Answer №3

It is important that the parameter for the getPoint function falls within the range of [0 to 1]:

// This is a virtual method in the base class that needs to be implemented in subclasses
//  - t should be a value between 0 and 1

THREE.Curve.prototype.getPoint = function ( t ) {
...

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

How can I find a user's ID in a JSON file using for...in loop in Discord.js?

I'm facing an issue with this loop where I am only able to retrieve the guild id instead of the user id that I actually need. Here is my code: for(let userID in money){ res.push({"guildid": message.guild.id, "id": userID, " ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

The Yeoman Angular Coffee router is not routing properly and displays an error message "cannot GET"

Struggling with getting the router to load a basic template after setting up a Yeoman angular scaffolder installation. Here's my configuration: // index.html <body ng-app="mvmdApp"> <div class="container" ng-view=""></div>// not ...

What is the way to activate Dynamic ng-model from a controller?

I am implementing a loop in my HTML code where each iteration dynamically creates a model. Here is an example of how the loop looks: <tr ng-repeat="item in voucherItems"> <td><input type="text" ng-model="this['id-' + $index ...

What is the best way to engage in conversations with several users using socket.io?

Currently, I am in the process of developing a chat application with authentication. The implementation involves socketio for real-time communication and jwt along with cookies for user authentication. The connection to the database has been successfully e ...

Error: The use of import statement is not allowed outside a module in JavaScript due to a Syntax

I'm just beginning my journey with React, starting from scratch without setting up all the necessary dependencies. Initially, I used CDNs in my html file but now I want to learn how to import React and ReactDOM into my local setup and also link CSS fi ...

I developed an RPG game with an interactive element using jQuery. One of the biggest challenges I'm facing is the random selection process for determining which hero will be targeted by the enemy bots during battles

Hello, this marks my debut on stack overflow with a question. I've created a game inspired by old school RPGs where players choose from three heroes based on the Marvel universe to battle one of three enemies. The problem I'm facing is that even ...

Retrieve data from an HTML form and utilize it to search a JSON array for a specific value

If I have a Json File structured like this: {"403": [ { "403-01-01": "219,00" }, { "403-01-02": "180,00" } ], "404": [ { "404-01-01": "26,00" }, {"403-01-02": " ...

Launching a Node.js Express application on Heroku

I'm facing an issue while trying to deploy my app on Heroku, as I keep encountering the following error: 2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306 2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnect ...

Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out... The application I'm working on was created using Laravel with Vue for the frontend. Essentially, I have an array of objects that need to be sent to t ...

The session in Express.js is not retained across different domains

I am currently developing a third-party application that will be utilized across multiple domains. My main goal is to manage a session per user who uses the app, which led me to implement the express-session module for this purpose. However, I encountered ...

AngularJS and Handlebars (npm)

Is it possible for angularJS to function as a substitute for the "view engine" in nodeJS? I am seeking insights on the optimal method to use. (Do MEAN Stack developers utilize view engines? Or do they prefer using res.sendFile along with tools like ui-ro ...

javascript functionality may be affected in Internet Explorer and Firefox following the upgrade to jquery version 1.8.3

After upgrading to jquery 1.8.3 from jquery 1.7 (where everything was functioning properly in all browsers), I added a javascript plugin that specifically requires jquery 1.8.2 or 1.8.3 Unfortunately, the image resizing functionality of this javascript is ...

Please proceed with submitting your choices in the order that you have selected

My goal is to submit options from a dropdown list in the order they are selected, rather than in the order they appear in the list. How can I achieve this? Here is the HTML code for the dropdown: < select style = "padding: 1em;" name = "skills" multi ...

Getting inaccurate results by entering numbers

const [shipping, setShipping] = useState({ overseas: '3' }) const handleChange = (e) => { setShipping({ overseas: e.target.value }) //can change to 8 or 3 } const selection = shipping.overseas console.log(sel ...

I am creating an HTML page that incorporates p5.js, and the text I'm rendering

It seems like the draw loop is continuously refreshing every x seconds, causing this behavior. Is there a way to slow down or disable the frame update without affecting the video refresh rate? I was thinking of adding an fps counter and implementing an i ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Issue with Jest Testing: React Fragment Not Being Rendered

Currently, I am facing an issue while testing components related to rendering the rows within a material-ui table especially when using React Testing Library. To create the table rows of a material-ui table, I am utilizing react fragments to iterate throug ...

Altering the dimensions of a <div> based on the retrieved data

I am currently retrieving data from an API and displaying certain properties using mapping. I would like to adjust the width of the component based on the value of these properties. <h5> <span className="viewcount" ref={boxSize}> ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...