Search code examples
javascriptthree.jsgame-physicsgame-development

How to prevent character from rotating when moving at an angle to an incline


You can see the problem when moving at an angle to the collider: https://8observer8.github.io/webgl10-js/lighthouse-oimophysics-webgl-js/

enter image description here

I use OimoPhysics but there is no such tag. This is a task common to all physics engines. There is a ball that slides down an inclined surface. It will rotate around an axis pointing upwards in the direction of greatest friction. It can only rotate around the upward axis, rotations around the other axes are frozen.

I created the issue on OimoPhysics GitHub page: https://github.com/saharan/OimoPhysics/issues/65

Another issue on Cannon ES GitHub page with source code in Three.js: https://github.com/pmndrs/cannon-es/issues/183

enter image description here

But Ammo.js doesn't have this problem. I just replaced OimoPhysics with Ammo.js and the problem went away: https://8observer8.github.io/webgl10-js/lighthouse-ammo-webgl-js/

enter image description here

Ammo.js works for bigger angle (42 degrees) too:

enter image description here


Solution

  • I solved this problem. You need to set the rotation factor to (0, 0, 0) when W and S were pressed, and to (0, 1, 0) when A and D were pressed.

    Example on OimoPhysics and Three.js: https://playcode.io/1508199

                if (input === "u") {
                    /* ... */
                    playerBody.setRotationFactor(new OIMO.Vec3(0, 0, 0));
                }
    
                if (input === "d") {
                    /* ... */
                    playerBody.setRotationFactor(new OIMO.Vec3(0, 0, 0));
                }
    
                if (input === "l") {
                    /* ... */
                    playerBody.setRotationFactor(new OIMO.Vec3(0, 1, 0));
                }
    
                if (input === "r") {
                    /* ... */
                    playerBody.setRotationFactor(new OIMO.Vec3(0, 1, 0));
                }
    

    enter image description here