Tips for utilizing a Three.js curve to guide the movement of a mesh along a specified path

Developing an animation, currently at this stage:

http://jsfiddle.net/CoderX99/66b3j9wa/1/

Please avoid delving into the code, it's written in CoffeeScript and may not be beneficial for your mental well-being.

Imagine a "nordic" landscape with ships sailing by and cars moving along. The yellow sphere in the top left symbolizes a car, while the winding roads are represented by curves.

The yellow sphere is supposed to follow these CatmullRomCurve3s precisely.

Let's work with a closed curve structure, which looks like this:

curveRoadNo2 = new THREE.CatmullRomCurve3([
  new THREE.Vector3( 15, roadHeight, 11 ),
  new THREE.Vector3( 12, roadHeight, 12 ),
  ...
] )

The figures are randomly inputted.

Next:

curveRoadNo2.closed = true
geometry = new THREE.Geometry()
geometry.vertices = curveRoadNo2.getPoints( 200 )
material = new THREE.LineBasicMaterial( { color : 0xa9c41e } )
curveObject = new THREE.Line( geometry, material )
scene.add( curveObject )

I would like to animate using getPoint(t) and getTangent(t), but I am unsure how to proceed.

t = 0
animate = ->
  requestAnimationFrame animate

  t += 0.1
  vehicle.position = curveRoadNo2.getPoint(t)

  # More animation steps can be added here...

  renderer.render scene, camera
animate()

Currently, the vehicle remains stationary. While I searched for solutions, they seemed overly complex and lengthy.

Suggestions or ideas in JavaScript are also appreciated.

Answer №1

It is advisable to create a separate vector for defining the position.

  animate = function() {
    requestAnimationFrame(animate);
    t += 0.001;
    var pos = curveRoadNo2.getPoint(t);
    vehicle.position.set(pos.x, pos.y, pos.z);
    // if 0 < t < 7
    //     v = t * 0.01
    //     ship.rotation.y += 26 * v ** 0.96 * Math.PI / 180
    //     ship.position.x += -6 * v
    //     ship.position.z +=  12 * v ** 1.3 
    return renderer.render(scene, camera);
  };

I found that increasing t by 0.1 was too fast, so I changed it to 0.001. When assigning positions to Object3D or Mesh objects, remember to use:

mesh.position.set(x, y, z);
object.position.set(newPos.x, newPos.y, newPos.z);

This method also applies to rotations, ensuring better organization and structure of your code.

Following this approach will lead to more effective coding practices.

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

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

Dynamic water filling effect with SVG

I'm trying to create a wipe animation that looks like water filling up inside of a drop shape. Currently, it is a square with a wave animation on top of the drop logo. The wave animation works correctly, but I am struggling to contain it within the dr ...

What could be the reason the forEachRow function is not impacting the second or subsequent pages within the dhtmlx grid?

I'm trying to format the grid rows as they load. My goal is to have the row appear in red with some conditions. It works correctly for the first page, but not for subsequent pages of the grid. Below is my detailed code. If anyone knows why this is hap ...

Is Selenium suitable for testing single page JavaScript applications?

As a newcomer to UI testing, I'm wondering if Selenium is capable of handling UI testing for single-page JavaScript applications. These apps involve async AJAX/Web Socket requests and have already been tested on the service end points, but now I need ...

Synchronize information between mongoDB and firebase bidirectionally

My current situation: Having developed an application using React, NodeJS, and Electron, most of my users utilize the app offline. Next plans: With intentions to cater to mobile users as well, I am considering creating a mobile application using React-N ...

Running Handlebars using NodeJS can sometimes result in a "Cannot find module './parser'" error

After successfully creating and implementing a Handlebars template in the Browser, my next goal is to utilize the Handlebars precompiler, which requires a NodeJS module. I have already downloaded Handlebars for NodeJS along with all dependencies locally (n ...

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

Eliminating duplicate data submissions with jQuery Ajax

Encountering an issue with my jQuery AJAX submission process. JavaScript: $('#myform').submit(function () { if (validateEvenInputs()) { $('#btnevent').attr('disabled', 'disabled'); function ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Utilize JavaScript to parse HTML content retrieved through AJAX requests

My current project involves writing JavaScript code, specifically a Chrome extension, that needs to: Retrieve the contents of a web page using AJAX. Extract specific content from the page by identifying certain elements within the HTML string and retriev ...

Search for the booking object based on the user in MongoDB

In my Next.js app, I have 2 models - Booking and User. The object below represents a booking object. When a user books some dates, a new object is created in the bookings model. On the booking details page, users should be able to see details of their book ...

What causes Express Async Errors to produce unexpected outcomes?

I stumbled upon a fantastic npm package called Express Async Errors that is highly recommended in the documentation. However, when I try to implement it, my server crashes. Here is my Route handler code: Controller const { Genre } = require("../models"); ...

Utilizing the Filter function to extract both the content contained within a class and the class itself

The filter function is working properly, returning multiple divs with a class of post. However, it is only capturing the content inside the div: <h1></h1> and not the entire structure like this: <div class="post"><h1></h1>& ...

Having trouble with my bootstrap slider carousel - it's just not cooperating

I incorporated Bootstrap's carousel to display the various courses on my website, featuring three courses at a time before transitioning to the next set of three. However, I am encountering an issue with this setup. Please see the image below for refe ...

Why won't setInterval function properly with innerHTML?

I've been attempting to include a small feature on my website that displays the running seconds, but for some reason my JavaScript function isn't working. Strangely, it's not throwing any errors either. Here's the code I'm using: f ...

Monitor for the specific parameter in the incoming GET request

My application is using the POST method to submit jobs remotely. After submitting a job, I receive a unique job ID from the POST request that allows me to check the status of the job using a GET request. $http.get('http://localhost:8090/jobs/'+i ...

Is it necessary for JavaScript functions to be stored in a separate file in order to be invoked?

Here is the scenario that unfolded: Within a .php file, I had the following form: <form action="/flash_card/scripts/create_user_gate.php" onsubmit="return validateForm()" method="post"> <table align="center"> ...

Adding CSS styling to a particular component within your Vue application using Vuetify JS

Imagine having a Test.vue file containing 2 v-text-field components. I'm looking to style only the first text field using CSS. Test.vue <template> <div class="test"> <v-text-field></v-text-field> <v-tex ...

Retrieve the most recently added item in the Material-ui Autocomplete component

Currently, I am incorporating the material-ui Autocomplete component with multiple selection feature. In one specific scenario, I require the ability to retrieve only the value of a newly added item. Despite utilizing the onChange listener, the event pro ...