Cannon.JS ensures that walls are impenetrable

I am currently experimenting with three.js and cannon.js, but I have encountered an issue where I am unable to create solid walls or any stationary objects that can block the player's movement.

Below is the code I have been working on so far. I would appreciate any insights you might have. While I usually prefer to troubleshoot on my own, this particular challenge of creating solid barriers is proving to be quite challenging, and I welcome any information that could help me overcome this obstacle.

if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var initScene;
var MARGIN = 10;
var MARGINSIDE = 0;

var WIDTH = window.innerWidth || ( 2 + 2 * MARGINSIDE );
//var WIDTH = window.innerWidth/3 || ( 2 + 2 * MARGINSIDE );
//var HEIGHT = window.innerHeight/3 || ( 2 + 2 * MARGIN );
var HEIGHT = window.innerHeight || ( 2 + 2 * MARGIN );

var SCREEN_WIDTH = WIDTH -2 * MARGINSIDE;
var SCREEN_HEIGHT = HEIGHT -2 * MARGIN;

var FAR = 10000;
var DAY = 0;

var stats, camera, scene, renderer;

var mesh, geometry;

var sunLight, pointLight, ambientLight, hemiLight;

var parameters

var clock = new THREE.Clock();
var inRender = true;
var inResize = false;

// cannon physics
var world;
var worldScale = 100;
var timeStep = 1/60;
var walls=[], balls=[], ballMeshes=[], boxes=[], boxMeshes=[];
var solidMaterial;
var playerMaterialPhy;

var playerRigid;
var playerPhysicsMesh;

var UNITSIZE = 250
var WALLHEIGHT = UNITSIZE / 3;

var map = [ // 1  2  3  4  5  6  7  8  9
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], // 0
           [1, 1, 0, 0, 0, 0, 0, 1, 1, 1,], // 1
           [1, 1, 0, 0, 2, 0, 0, 0, 0, 1,], // 2
           [1, 0, 0, 1, 0, 2, 0, 0, 0, 1,], // 3
           [1, 0, 0, 2, 0, 0, 2, 1, 0, 1,], // 4
           [1, 0, 0, 0, 2, 0, 0, 0, 0, 1,], // 5
           [1, 1, 1, 0, 0, 0, 0, 0, 1, 1,], // 6
           [1, 1, 1, 0, 0, 0, 0, 0, 1, 1,], // 7
           [1, 1, 1, 1, 1, 1, 0, 0, 1, 1,], // 8
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1,], // 9
           ], mapW = map.length, mapH = map[0].length;

// player
var loader;
var player;
var playerMaterial;
var playerMap = { map:undefined, normal:undefined};
var players=[];
var playerName = "LegoElvis";
var scaleFactor = 5;
var velocity = {x : 0, z : 0};

var playerControls = {
    moveForward: false,
    moveBackward: false,
    moveLeft: false,
    moveRight: false,
    bodyOrientation: 0,
    maxSpeed: 275,
    maxReverseSpeed: -275,
    frontAcceleration: 600,
    backAcceleration: 600,
    frontDecceleration: 600,
    angularSpeed: 2.5,
    speed: 0
};

var shadowConfig = {
    Visible: false,
    Near: 750,
    Far: 4000,
    Fov: 75,
    Bias: -0.0002,
    Darkness: 0.5,
    Resolution:1024
};

var ...

initScene = function () {
    ...
}

...

function animate() {

    requestAnimationFrame( animate );

    if(inRender || inResize){
        var delta = clock.getDelta();
        if(player!=null)updatePlayer(delta);
        updatePhysics();
        render();
        stats.update();
    }

    inResize = false;
}

function render() {
    ...
       renderer.render( scene, camera );
}

function tell(s){
    document.getElementById("debug").innerHTML = s;
}

...
    
window.onload = initScene;

Answer №1

When you are updating the player's movement in the function updatePlayerMove, it involves setting the position of the Cannon.js body that corresponds to the player. However, constantly overriding the body's position prevents it from updating on its own.

This method of setting body positions can lead to unstable physics simulations, resulting in significant and erroneous overlaps. Additionally, it may allow the player to walk through walls.

Instead, consider controlling the player body using velocity. By doing so, Cannon.js will handle the player's response, leading to a more stable physics environment:

playerRigid.velocity.set(vx,vy,vz);

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

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

I'm baffled by why I keep receiving the error message "Unknown provider: $routeProvider <- $route <- AppController" in AngularJS, even though I have already

I've exhausted all the solutions I found on stackoverflow without success. Apologies if this is a duplicate question. My goal is to reset the content of my Bootstrap table with a button click using the function $route.reload(). However, when I includ ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

What is the best way to execute a series of asynchronous JavaScript functions one after the other?

As I attempt to call the following functions in succession, their return does not always happen in the expected order. Upon discovering asynchronous functions and the concept of using "callbacks," I realized there might be a solution for executing these f ...

Changing the size on click using Jquery

I'm attempting to make a button shrink another element using jQuery. Here's what I have so far: $( "#img1" ).click(function() { $("#img2").css("-moz-transform:scale", "0.7, 0.7"); }); However, this solution doesn't seem to be functio ...

Send information to a function until the array reaches its maximum length

I am facing a challenge where I have a function that accepts multiple arrays as arguments, but the data available to me is already within an array called mainArr. This mainArr consists of several array items that need to be passed as arguments to the funct ...

retrieve HTML content by its ID stored in a variable

In my JavaScript code, I have a variable named "value" that contains HTML data. I am trying to extract the data from a specific ID that is located within the element with ID #myDiv. var value="<div > <p class="">Hi <a href="/ ...

Is it possible to retrieve the final digit from a URL using NUXT/Vue?

My dilemma involves utilizing the SWAPI API to display a single result, whether it be a person or a planet. However, instead of providing a direct ID for each item, the API returns a complete URL in this format: "url": "http://swapi.dev/api/ ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

Introducing unnecessary DOM elements when displaying flash messages

When a user saves in my Rails application, it triggers an Ajax request to save the post and then runs the update.js.erb file. This file contains some jQuery code: $('body').append('<div class="message">Saved</div>'); Due t ...

Chosen option within the AntD Select component

Using the AntD select component, there seems to be an issue where it displays "id" instead of "name" when selecting options. Is there a solution available for this problem? const MyComponent = () => { const data = [ { id: "5c83c2d ...

What is the process for transforming a nested dictionary in JSON into a nested array in AngularJS?

I am looking to create a form that can extract field values from existing JSON data. The JSON I have is nested with dictionary structures, but I would like to convert them into arrays. Is there a way to write a recursive function that can retrieve the key ...

The error message regarding pdf.worker.min is stating that the use of 'import' and 'export' is limited to within module code and cannot be used outside of it

Upon attempting to deploy a build to Vercel, I encountered the following error message: Failed to compile. static/media/pdf.worker.min.50acc843.mjs from Terser x 'import', and 'export' cannot be used outside of module code ,-[18:1 ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

combine two separate typescript declaration files into a single package

Can anyone help me figure out how to merge two typescript definition packages, @types/package-a and @types/package-b, into one definition package? package-a.d.ts [export package-a {...}] package-b.d.ts [exports package-b {...}] package-mine.d.ts [ export ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

Maintaining the active state in Bootstrap, even when manually entering a URL, is essential for smooth

Check out this fully functional plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview This example includes a navigation with 2 links (routing to 2 ui-router states), and a jQuery method that ensures the active class remains on the active lin ...

tips for accessing variables within app.get

Is there a way to make a variable or a set of variables inside app.get accessible throughout the entire project? I am working on capturing information from an SMS text message, organizing it into the "messageData" variable, and then sending it to the "Mess ...

The onchange() function appears to be undefined, could it be inaccessible from the index.html file?

I have encountered an issue while trying to assign an 'onchange' attribute to a <select> tag in my HTML. The function I defined as filterChanged() in my main.js file (which is bundled into bundle.js) cannot be accessed when the onchange eve ...

Do you know the term for when JavaScript is utilized to display specific sections of a png image?

Imagine you have an image file in the format of a PNG which includes various icons intended for use on a website. How can JavaScript be utilized to choose and showcase a specific icon from that image? It's a technique I've observed in practice, b ...