Rotating items to reset their y-angle in Three.js

In my three.js game project, I am developing cars that move in different directions based on their y-rotation angle. For instance, a rotation of 90 degrees. To move them forward, I use the object.translateZ() method, but I am facing an issue.

Utilizing physijs for car simulation, collisions between cars can alter their y-rotation, requiring them to gradually return to their original rotation as if they are maneuvering back onto the road after a crash. Without this adjustment, the city in my game becomes very chaotic.

Below is a snippet of the code I am currently using:

var targetRotation = 90
var rotation = car.mesh.rotation.y * 180 / Math.PI //converting to degrees

My goal is to implement a method to smoothly transition the car's rotation towards the target rotation angle.

Any assistance would be greatly appreciated! (Ideally, a function would be the perfect solution)

Answer №1

In my experience with similar tasks in different systems (2D, not Three.js), the key is to gradually adjust the angle until it is approximately close to the target angle. The idea is to ensure that the increment in the angle is not greater than the turning speed to avoid overshooting the desired value.

The rate of increment depends on how quickly you want the object to turn.

It is also important to determine whether it is more efficient to increase or decrease the angle (turn clockwise or counterclockwise) based on the proximity to 360 or 0 degrees. This prevents unnecessary long turns. The comparison can be made by checking if the difference is greater or less than 180.

The modulus operator can be used to calculate the actual angle within the range of -360 to 360 degrees.

var currentAngle = car.mesh.rotation.y * 180 / Math.PI; //convert car's angle to degrees
var targetAngle = 90; //desired angle 
var turningSpeed = 1; //degree increment per update 
currentAngle = currentAngle % 360; //get the remainder in the 0-360 range
if (Math.abs(targetAngle - currentAngle) >= turningSpeed) {
  var addto = 0
  if (targetAngle - currentAngle < 0) {
    addto = 360
  }
  if (targetAngle - currentAngle + addto <= 180) { 
    currentAngle += turningSpeed;  
  }
  else {
    currentAngle -= turningSpeed;
  }
}
else { 
  currentAngle = targetAngle; 
} 
car.mesh.rotation.y = (currentAngle * Math.PI) / 180; //convert back to radians

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

Issues with jQuery code functionality within web forms

After creating a jQuery script to alter the CSS of a table row, I tested it on JSFiddle and it worked perfectly. However, when implemented into my web project, it doesn't seem to be functioning as intended. See the code below: HTML: <script src ...

Can information be saved to a JSON file without using a server-side language?

Previously, I've come across questions where the recommended solution involves using a server-side language. However, since I don't have knowledge of a server-side language yet, I was curious to know if it's possible to achieve this with my ...

jQuery interprets every PHP response as having a status of 0

I've been working on a way for javascript to verify the existence of a user in a MySQL database. My method involves using jQuery to send the user details to a PHP script that will then check the database. The data is successfully sent to the PHP scr ...

The Jquery Datatable fails to display the accurate number of rows based on the selections made in the dropdown

I am working on an ajax call that returns a table. In the success method, I am using $("#tableID").dataTable();. Although it shows paging and the number of rows in the dropdown, it is displaying all rows instead of only the number of rows selected in the d ...

Combine two comma-separated strings in JavaScript to create an array of objects

I have two strings separated by commas that I want to transform into an array of objects. { "id": "1,2,3", "name": "test 1, test 2, test 3" } Is there a way to convert this into the desired object format? { &q ...

How can I specify which node_modules to include when using electron-packager in Electron?

I am in the process of packaging my electron app, and it specifically requires the mqtt and node-notifier modules. What I want to do is exclude all node_modules except for these two modules. Let's say I want to exclude the following files from packag ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...

Does the webpack style loader load only application-specific CSS, or is it designed to handle all CSS files?

I am in the process of improving the modularity of my front-end design by delving into webpack. This tool provides a style loader, which enables you to import a css file and inject it into the document like this: require("style/url!file!./file.css"); // = ...

Adjust the button's hue upon clicking it

The current function is operational. Upon pressing the button, it toggles between displaying "click me" and "click me again". However, I desire the button to appear blue when showing "click me" and red when displaying "click me again". <!DOCTYPE html ...

The Material UI list element fails to appear on the screen

I am encountering an issue where I am trying to display a Material UI list within a drop-down menu (using the Material UI drawer component) for mobile view, but the actual list is not appearing as expected. The code snippet for the list is as follows: con ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

Cache for AngularJS $http.jsonp requests

I'm struggling with caching a JSONP request and have tested out different approaches without success. I attempted $http.jsonp(url, { cache: true }) and $http({ method: 'JSONP', url: url, cache: true }), but neither worked as expected. As a ...

Jssor's dynamic slider brings a touch of sophistication to preview upcoming images

Incorporating the jssor nearby slider to create a nearly fullscreen display. The goal is to set the opacity of upcoming images to 0.25 when they are not in the main viewport, giving the edges of the upcoming and previous slides a slight transparency. < ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Transmitting information securely and remotely between two online platforms

I own two websites and another at When a user clicks on something on example1.com, I want it to trigger a popup from example2.com. Then, I need to send some data back to example1.com using GET parameters and be able to detect it using jQuery or JavaScrip ...

Encountering a situation where attempting to retrieve JSON data results in receiving an undefined

After fetching JSON data from the API , I successfully printed out text to the console with the correct data. However, when attempting to access any of its properties, they are returning as undefined. var url = "http://www.omdbapi.com/?t=batman&y=& ...

Angular is able to select an element from a specified array

I'm currently struggling with using Angular to manipulate a TMDB API. I am having difficulty retrieving an item from an array. Can someone provide assistance? Here is the response that the array returns: { "id": 423108, "results ...

Retrieval of entity through REST Endpoint using ODataSetName for Custom Entity

In my restendpoint.js file, I have a function called retrieveRecord which is defined on this website I am working on a function that should trigger whenever the Programme (a lookup field) on the Application entity changes. The goal is to fetch the attribu ...