Cannon.js combines with Three.js for a sleek car simulation with realistic physics

Currently, I am experimenting with the creation of a simplistic car utilizing physics in Three.js and Cannon.js. My progress so far includes developing the visual and physics aspects of the car along with its wheels. The car can respond to commands involving the up arrow for acceleration and left/right arrows for steering:

// JavaScript code snippet for setting up the scene, camera, and renderer
var container = document.querySelector('body'),
    w = container.clientWidth,
    h = container.clientHeight,
    scene = new THREE.Scene(),
    camera = new THREE.PerspectiveCamera(75, w/h, 0.001, 100),
    renderConfig = {antialias: true, alpha: true},
    renderer = new THREE.WebGLRenderer(renderConfig);
// More code goes here...
// Other code snippets related to setting up the car's physical properties go here...

I am currently facing a challenge in implementing realistic wheel rotation behavior using Cannon.js. Previously, I tried manually updating the rotation of the wheels in the

world.addEventListener('postStep')
callback, but encountered issues when the car turned, leading to misaligned tires...

If anyone has insights on how to properly configure wheel rotations with Cannon.js, I would greatly appreciate any guidance!

Answer №1

Ah-ha moment! Instead of applying the hacky rotation to the mesh, I should have applied it to the geometry!

The simple fix below involves adding just one line to the loop for vehicle.wheelInfos:

cylinder.geometry.rotateZ(Math.PI/2);

var container = document.querySelector('body'),
    w = container.clientWidth,
    h = container.clientHeight,
    scene = new THREE.Scene(),
    camera = new THREE.PerspectiveCamera(75, w/h, 0.001, 100),
    renderConfig = {antialias: true, alpha: true},
    renderer = new THREE.WebGLRenderer(renderConfig);

// Rest of the JavaScript code remains unchanged from the original text.

render();
* {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
html,
body,
canvas {
  width: 100%;
  height: 100%;
  background: #aaa;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.js'></script>

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

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...

What is the best method to retrieve JSON data from a Rest API?

In my JavaScript code, I am creating an object: var t = null; $.getJSON('http://localhost:53227/Home/GetData', function (data) { alert(data); t = data; }); alert(t); After ...

Collaborating information between 2 controllers using a shared Service in Angular.js

(function () { 'use strict'; angular.module('ShoppingListCheckOff', []) .controller('ToBuyController', ToBuyController) .controller('AlreadyBoughtController', AlreadyBoughtController) .service("ShoppingListCheckOffS ...

Encountering an issue where the P3D sketch does not function properly when running

Currently, I am in the process of converting a project I developed in Processing [Java Mode] to an online platform for web viewing. The project involves P3D rendering to showcase a 3D environment that allows for rotation and manipulation of three data sets ...

Harnessing the power of $map in MongoDB for updating objects within query pipelines

After retrieving a list of objects from a call to db.collection.aggregate(), the results look like this: { _id: <some_id>, count: 400, results: [ { _id: 1, ... travel_guess: 0.1934042214126773, }, { _id: 2, ...

Tips for updating the left positioning of a Div element on the fly

Although my title may not fully explain my goal, I am dealing with dynamically created div elements. When a user triggers an ajax request to delete one of the divs, I want to remove it from the DOM upon success. The issue arises in adjusting the layout aft ...

What is the best way to cancel a request within an HTTP-interceptor?

Within an application, I have established the following URL structure for the API: // public public/url-xyz // private dashboard/url-xyz To avoid unnecessary requests, what is the most effective method for canceling a request? My current approach involv ...

Express Concurrency: Managing Multiple Tasks Simultaneously

Looking to create an API using Express that is capable of processing requests either through multithreading or multiprocessing. For example, the following API has a 5-second sleep before responding. If I make 3 quick calls to it, the first response will ta ...

Leveraging the On Keyup Function in Real-Time

How can I modify this code to run after an ajax call using .live method? var element=document.getElementById('txt_url'); element.onkeyup=function(){ var input=element.value; if(input=='') return; if(input.indexOf('h ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

Creating a visual comparison by using knockout side by side

I'm currently working on a project that requires me to display multiple items side by side for comparison. The ideal layout would be similar to Amazon's, where each item is represented by a vertical column with all relevant information about tha ...

Preventing Duplicate Entries in Angular Data Posting

I am currently trying to submit a form to a PHP page that will then return a table of data. The process works perfectly fine if I do not include any parameters in the post request. However, as soon as I try to add parameters for the query, I encounter an n ...

Issues with the .change(function() JavaScript in Internet Explorer versions less than 9

I'm experiencing issues with this script in Internet Explorer versions below 9. Can someone please help me identify what is wrong with my script? Thank you. IE7 and IE8 are showing the following error: SCRIPT87: Invalid argument. Found ...

Exploring the basics of Three.js: a step-by-step guide using a shadertoy example on transforming patterns with objects

Check out this snippet, inspired by the second live example found at : html, body { height: 100%; margin: 0; } #c { width: 100%; height: 100%; display: block; } <canvas id="c"></canvas> <script type="module"> // Three.j ...

Utilize SVGs efficiently by loading them once and reusing them

Is it possible to use the same SVG element twice on a web page without having to load it again? I am changing the CSS of the SVG using JavaScript, so I believe the SVG must be directly embedded in the HTML rather than included as an object. Both instance ...

What steps can I take to remove the dark areas in my see-through material?

While displaying a 3D shoe model in the browser using three.js, I encountered an issue with a half-transparent material set for the heel. The problem arises when I use the orbitControls in the project and rotate the model to a certain angle, which then rev ...

"Utilizing Jest Globals to Provide an Empty Input for a Function: A Step-by-

I have developed a function that outputs null when the input is empty: const testFunc = (param) => { if (param) { //blabla } return null; }; To verify the return null behavior with an empty param, I want to utilize describe...it...: describe( ...

I am struggling to make callback functions function properly with an ajax GET request

I'm struggling to extract specific elements from a JSON file retrieved from an external REST API and store them in a local dictionary variable for use in my JavaScript code. While my AJAX GET request is successful, I'm facing an issue where I can ...

Increasing the element in a react reducer state array results in doubling the element with each append

store.js const initialState = { messagelist: [] } const reducerAllMessages = (state=initialState, action) => { if(action.type === "newMessage") { console.log("state", state); return {...state, messagelist:[. ...