Tips for adjusting collisions between models using three.js and oimo.js

I am currently working on implementing collision with an object using three.js by importing a model and then creating a body in Oimo to represent it.

My problem arises from the fact that the center of the model does not align with the center of the object. This discrepancy results in inaccurate collision detection at the feet when I enlarge my bounding box. Is there a straightforward solution to this issue through code or perhaps by adjusting the model itself (given that modeling is not within my expertise)?

for ( let i = 0; i < 15; i++ ) {
    loader.load( model, function ( gltf ) {

        let x = startValue += 1;
        let sceneModel = gltf.scene;

        gltf.scene.position.set( x, 20, 0 );
        scene.add( gltf.scene );

        let sizeX = 1;
        let sizeY = 10;
        let sizeZ = 1;

        var body = world.add( {
            type: 'box', // shape type: sphere, box, cylinder
            size: [ sizeX, sizeY, sizeZ ], // shape size
            pos: [ x, 20, 0 ], // initial position
            rot: [ 0, 0, 0 ], // initial rotation
            move: true, // dynamic or static
            density: 1,
            friction: 0.2,
            restitution: 0.2,
            belongsTo: 1, // Collision group belonging bits.
            collidesWith: 1 // Collision group bits to collide with.
        } );
        models.push( gltf.scene )
        bodies.push( body )


        let geometry = new BoxGeometry( sizeX, sizeY, sizeZ );
        let material = new MeshLambertMaterial( { color: 0x00ff00 } );

        let cube = new Mesh( geometry, material );
        cubes.push( cube );
        cube.position.set( x, 20, 0 );
        scene.add( cube );

        let animations = gltf.animations;
        var mix = new AnimationMixer( sceneModel )
        mixer2.push( mix );

        let idleAction2 = mix.clipAction( animations[ 0 ] );
        idleAction2.play();
    }, undefined, function ( error ) {

        console.error( error );

    } );
}

If I set y to 0.1 for the size, the collision works correctly at the feet but the bounding box is too small. Using a size of 1.8 gives the right height, but the unit doesn't touch the ground anymore.

My update

var animate = function () {
    requestAnimationFrame( animate );

    let deltaTime = clock.getDelta();

    if ( mixer2 ) {
        mixer2.forEach( mix => {
            mix.update( deltaTime );
        } );
    }
    if ( world ) {
        world.step();
        bodies.forEach( ( body, index ) => {
            models[ index ].position.copy( body.getPosition() );
            models[ index ].quaternion.copy( body.getQuaternion() );

            cubes[ index ].position.copy( body.getPosition() );
            cubes[ index ].quaternion.copy( body.getQuaternion() );
        } )
    }
    renderer.render( scene, camera );
};

animate();

Answer №1

After some investigation, I finally cracked the code on this one. It turns out that the key lies in adjusting the halfheight value found deep within the shapes member.

    protected render(): void {
        requestAnimationFrame( this.render.bind( this ) );

        let deltaTime = this.clock.getDelta();
        this.world.step();

        this.physicsBodies.forEach( ( data: { body: RigidBody, object: GameModel, cube?: Mesh }, index ) => {

            data.object.update( deltaTime );

            if ( data.object.isDirty ) {
                data.body.position.copy( data.object.getDisplayObject().position );
                data.object.isDirty = false;
            }
            data.object.getDisplayObject().position.copy( data.body.getPosition() );
            data.object.getDisplayObject().position.y -= data.body.shapes.halfHeight;

            let bodyQuaternion = data.body.getQuaternion();
            data.object.getDisplayObject().quaternion.set(
                bodyQuaternion.x,
                bodyQuaternion.y,
                bodyQuaternion.z,
                bodyQuaternion.w
            );
            data.object.updateMixer( deltaTime );
        } );

        this.nonPhysicsBodies.forEach( ( model: GameModel ) => {
            model.updateMixer( deltaTime );
        } );

        this.renderer.render( this.scene, this.camera );

    }

So, every time the render function is called, it's essential to subtract the halfHeight from the body's position.

data.object.getDisplayObject().position.y -= data.body.shapes.halfHeight;

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

Implementing asynchronous progress bar in Node.js using async.series

Currently, I am attempting to track the progress of a series of tasks using async series. module.exports = update; function update(){ // Require Deps var async = require('async'); var progress = require('progress'); var tasks ...

I am looking to combine two arrays, potentially containing identical data

I have a task to combine two arrays, one from an API and the other from a database: Array1 (Data from API): { '0': { userid: 'kdkds', name: 'Stephan, email: '<a href="/cdn-cgi/l/email-protection" class="__cf ...

Ways to retrieve the identifier of an iframe

document.getElementById(Iframe_id).contentWindow.addEventListener("blur", blurtest, true); This line of code assigns the blur event to an iframe and it is functioning properly. However, when in function blurtest(e) { alert(e.target.id); } An alert ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

Navbar Username in Next.js with Typescript and Supabase Integration

I'm currently facing an issue with retrieving the username of a user to display in my navbar. The desired username is stored in the "username" column of the table called "profiles" in my Supabase database. However, the data that's populating the ...

Tips for transforming C#.NET code into JavaScript code

A few years back (around 3 or 4 years ago), I recall hearing about a fascinating concept that involved generating client-side JavaScript code from C#.NET source code. It may have been related to validation tasks specifically... Does anyone have more inform ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

Checking for Three.js WebGL compatibility and then switching to traditional canvas if necessary

Is there a way to check for WebGL support in three.js and switch to a standard Canvas render if not available? I'd appreciate any insights from those who have experience with this library. ...

Permitting various valid responses for questions in a multiple-choice test | Utilizing Angular.js and JSON

As a beginner in this realm, I must apologize if my query seems naive. I recently crafted a multiple-choice quiz using HTML, CSS, JavaScript (angular.js), and a JSON data file following a tutorial I stumbled upon. The outcome pleased me, but now I am face ...

I encountered an issue when attempting to execute an action as I received an error message indicating that the dispatch function was not

I just started learning about redux and I am trying to understand it from the basics. So, I installed an npm package and integrated it into my form. However, when I attempt to dispatch an action, I encounter an error stating that 'dispatch is not defi ...

Navigating in Angular is made easy with the Angular routing feature, which allows you to redirect

I have been working through the Angular Tour of Heroes Guide and encountered the section on the "default route". I decided to experiment by removing the pathMatch attribute from the Route associated with an empty string. Below is the code snippet in quest ...

Creating a Breeze js entity using a JSON string and importing it into the breeze cache: A step-by-step guide

Currently, I am developing a mobile single page website that utilizes technologies like breeze js, angular js, web API, and entity framework. To enhance the performance of the site, I have decided to include the breeze metadata in a bundled JavaScript fil ...

``Maintain user engagement with a dynamic menu by utilizing knockout for view switching and CSS

I'm facing a challenge with my single-page application developed using knockout/jquery. The issue lies in handling which view to display as the number of menu items increases, making the code more difficult to manage. I'm looking for a solution t ...

AngularJS - Utilizing Google's Place Autocomplete API Key

Recently, I started digging into Google's APIs and attempting to integrate the Places Autocomplete API with Angular. Although I'm fairly new to autocomplete features in general, I haven't included the jQuery library in my project yet. I&apos ...

Issue with Bootstrap tab display of content

I'm having trouble with the tabs in my page. When I click on each tab, the content doesn't display correctly. Here is my code: <div class="w470px exam" style="border: 1px solid #ddd; margin-top: 30px;"> <ul id="myTab" class="nav nav ...

Filter JavaScript elements by conditions and true/false values

I can't quite recall the answer to this at the moment. Consider an array of Vendors (this is just placeholder data): [ { "user_updated": null, "user_created": "128a84b5-275c-4f00-942e-e8ba6d85c60e", "d ...

The powerful combination of knockout.js, breeze, and dynatree/fancytree offers a dynamic and

This concept is really challenging for me to grasp as I am not accustomed to this particular style of programming or data management. Presently, my main objective is to pass a JSON object retrieved through Breeze into a Dynatree or Fancytree. All the ava ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

Steps for assigning distinct identifiers to information entered through an input form

I have a question that I just can't seem to figure out: So, I have this input form: <form @submit.prevent="customSubmit"> <label>Name</label> <input type="text" v-model="newUser.name" id=&quo ...