Align the object with the path it is following

Currently, I am in the process of learning about vectors and their application in moving objects within ThreeJS. For an experiment, I am propelling a box using a specified velocity and an arbitrary gravity vector.

Additionally, I am attempting to align the object with the curved trajectory it follows. Initially, it seems to be on track, but then veers off course midway through.

Moreover, the resources I have been studying are not in JavaScript, and they utilize operations like:

position = position + velocity * delta;
velocity = velocity + gravity * delta;

However, replicating this exact process in JS is not possible. Therefore, I have been multiplying by a scalar. Is this the correct approach?

Below is the render function I have implemented:

function render(){
    var delta = clock.getDelta();

    velocity.add(velocity.clone().multiplyScalar(delta));
    velocity.add(gravity.clone().multiplyScalar(delta));

    box.position.add(velocity);

    var theta = velocity.angleTo(z);
    box.rotation.x = (theta);

    requestAnimationFrame(render);
    renderer.render(scene, camera);
}

UPDATE: After considering WaclawJasper's suggestion, I made the following adjustments in my code. You can view the updated demo on JSFIDDLE DEMO HERE

function render(){
    var delta = clock.getDelta();

    velocity.addScaledVector(gravity, delta);
    position.add(velocity);

    axis.crossVectors(up, velocity.clone().normalize()).normalize();
    radians = Math.acos(up.dot(velocity.clone().normalize()));
    box.quaternion.setFromAxisAngle(axis, radians);

    box.position.set(position.x, position.y, position.z);

    requestAnimationFrame(render);
    renderer.render(scene, camera);
}

Answer №1

In JavaScript, there is no support for operator overloading. However, the expression

position = position + velocity * delta
essentially means adding the product of velocity and delta to the position. Unlike in other languages, where operations can have different meanings based on the types of their arguments, in this case, delta is a number and velocity is a vec3, indicating that the vector should be scaled. Luckily, ThreeJS offers the addScaledVector method to handle this functionality easily.

When it comes to rotation, a simple approach is to align the model's orientation with its velocity direction. This can be achieved using the matrix4.lookAt function. By utilizing

matrix4.lookAt(v3(0,0,0),velocity, UP)
, you can obtain the correct rotation matrix and simply apply it to the model.

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

Whenever I execute the 'ng serve' command, I encounter an issue with ineffective mark-compacts close to the heap limit, resulting in an allocation failure and a JavaScript

I'm currently using Angular 9 and Node.js 12. When I input ng serve, I encounter the following problem: C:\Users\homz\my-app>ng serve 93% after chunk asset optimization SourceMapDevToolPlugin vendor.js generate SourceMap <--- ...

Swapping out components or features within AngularJS

Is it possible to make my dependencies interchangeable in AngularJS? For example, if I have a service named myService stored within the module myDependency, how can I switch out myDependency with a new service without disrupting the main application? Shou ...

What is the size limit for JSON requests in Node.js?

I am seeking information about the req object in nodeJS. Let's say I have a code that sends data in JSON format to my server using an AJAX POST method. Now, imagine a scenario where a user manipulates my client code to send an excessively large JSON f ...

When positioned at high or low angles, the camera starts acting strangely

In my Three.js scene, I have a camera that I need to move and change its angle around a specific focal point. The focal point is actually the camera's position, and during rendering, I translate the camera by using the cameraBuff vector to position it ...

Efficient ways to clear all input fields within a React div component

import "./App.css"; import { useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { addUser} from "./features/Users"; function App() { const dispatch = useDispatch(); const use ...

Submitting a form in a Chrome packaged app

Exploring Chrome packaged apps for the first time and facing a common issue that involves two questions. Attempting to create a basic form to submit data to a server using Ajax and POST. However, running into the restriction of not being able to use inlin ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

Tips for triggering a method when clicking instead of using v-for in Vue.js

I need help arranging an array of objects based on their ratings. Currently, I am able to display the items from highest to lowest rating using the v-for method. But, I would like to first display the objects in their original order and then have a button ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

Cloud Function experiences a timeout error when attempting to subscribe an FCM token to a topic within the HTTP function

Example Code: Main.ts: import * as admin from "firebase-admin" import fetch, { Headers } from "node-fetch"; interface FooPayload { topic: string, token: string, } exports.foo = functions.https.onCall(async (data, context) => { ...

Encountered an Error in Express.js: Unable to POST /users

I am currently in the process of learning the MEAN stack by following a tutorial and have encountered an error. Unfortunately, I am having difficulty identifying exactly where I went wrong. While attempting to test routes in Postman by creating a user, I ...

Utilizing VueJs (Quasar) to access vuex store within the router

Recently, I have been diving into learning Vuex and creating an authentication module. Following a tutorial, I reached a point where I needed to use the store in the router. However, after importing my store at the top of the router index.js file, I notice ...

It is impossible to remove or trim line endings with regex in Node.JS

I'm having trouble with using process and util in a NodeJS script. Even after trimming, line breaks persist in the resulting string (as seen in the console.log() output below). I'm unsure why this is happening. var util = require("util"); proces ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

Encountering a build error in Next.js 13 when attempting to fetch an API route within a server component

I encountered an issue while building my next app (yarn run build). To troubleshoot, I created a new clean project and tested it. The problem seems to be with my route (/api/categories/route.ts) export async function GET() { return new Response(JSON.str ...

The scenario of two users simultaneously gaining control access in socket.io creating a race condition

There is a need to ensure that only one user at a time is notified for an available room. I am implementing a solution to prevent multiple users from being notified simultaneously for the same room. socket.on('Check', function (room) { io.in(r ...

What is causing the local storage to not persist after refreshing the page?

Even after a browser refresh, the button text 'completed' should remain intact depending on whether the variable item is true (after the button click). I have experimented with Chrome and believe the issue is not related to the browser. <temp ...

Sending data from a PHP array to a JavaScript array within a PHP function

I have been scouring Stack Overflow for a solution to my problem, but I haven't found one that fits my specific issue. I recently took over a project from a former coworker that involves managing all the videos and images for my company. My current di ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

Position the div in the center and enhance the function to dynamically adjust when the user attempts to resize the window

var windowHeight = $(window).height(); var windowWidth = $(window).width(); var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max( ...