Search code examples
javascriptthree.jsphysijs

Three.js PointerLockControls and Physisjs collision detection


I'm working on a Three.js project using PointerLockControls (full modified code). I'd like to implement collision detection for the playehr. I'm going about this by making a new Physijs cylinder object, and then passing it along with the camera to PointerLockControls:

  var player = new Physijs.CylinderMesh( new THREE.CylinderGeometry( 2, 2, 10, 32) , playerMaterial );
  player.position.set(0, 5, 0);
  player.addEventListener( 'collision', handleCollision );
  scene.add(player);

  controls = new PointerLockControls( camera, player );

In PointerLockControls, I then attach the outer object (yaw rotation handler) to the passed player object, and then move the player object in the world.

velocity.x -= velocity.x * 10 * dt;
velocity.z -= velocity.z * 10 * dt;
velocity.y -= 9.8 * 20 * dt;

if (moveForward) velocity.z -= 180 * dt;
if (moveBackward) velocity.z += 180 * dt;
if (moveLeft) velocity.x -= 180 * dt;
if (moveRight) velocity.x += 180 * dt

player.translateX( velocity.x * dt );
player.translateY( velocity.y * dt );
player.translateZ( velocity.z * dt);

However, upon testing, both the player object and the camera phase through the floor, or, if translateY is commented out, do nothing but jerkily vibrate in place when I try to move them.

Where did I go wrong setting this up? It seems to me the problem comes fromIs attaching the yawObject to a player object and then moving that even the right way to go about collision detection with my setup?


Solution

  • Found answer to my own question: Physijs does not support three.js style object manipulation. If we want to use translate() like I did in my code, we need to update the object's dirty position parameter like so:

    player.translateX( velocity.x * dt );
    player.translateY( velocity.y * dt );
    player.translateZ( velocity.z * dt );
    player.__dirtyPosition=true;
    

    Above will make the movement work.