rotation issue on physijs

658 Views Asked by At

I am working with this library for a short time, and i have a issue that is killing me.

I have 2 cubes, one with phisy.js and another with three.js, and i have a function for rotate them when you press the A, S, D, or W key depending on the rotation of the camera, my code is like this:

    var v = new THREE.Vector3(0, 0, 0);
    if (keys.forward === 1)
        v.x = -1;
    if (keys.right === 1)
        v.z = 1;
    if (keys.backward === 1)
        v.x = 1;
    if (keys.left === 1)
        v.z = -1;

    //get the searched angle
    var angle = camera.rotation.y + Math.atan2(v.x, v.z);
    var rot = normalMesh.rotation.y;
    var diff = angle - rot;

    if (Math.abs(diff) > Math.PI) {
        //find the shortest way to rotate
        if (diff > 0)
            rot += 2 * Math.PI;
        else
            rot -= 2 * Math.PI;
        diff = angle - rot;
    }
    //get the /2 for a smooth rotation, i really need this
    if (diff !== 0)
        rot += diff / 2;
    normalMesh.rotation.set(0, rot, 0);

on the three.js cube works fine, but on the physi.js cube i doesn't work.

I am created a demo for this (i can´t create it on jsfiddle because the web worker)

http://demo.cristobaldiaz.cl/test/

also i left the source code on a zip file ---> http://demo.cristobaldiaz.cl/test/issue.zip

you can check the movement function on http://demo.cristobaldiaz.cl/test/src/app.js line 95

Anyway, if you rotate the camera with the mouse, you can check that the problem occurs when you rotate the cube to the direction of the red mesh.

1

There are 1 best solutions below

0
On

You can remove you rotation update from the animation loop and move it to a physical loop:

scene.addEventListener('update', function(){
    actor.onRender();
})

This way it will always be in sync.

See this page https://github.com/chandlerprall/Physijs/wiki/Callbacks-&-Events for more details.