Monday, August 13, 2012

Physijs Controls

‹prev | My Chain | next›

Up today, I hope to build on last night's progress on adding Physijs to my Three.js avatar island. Last night, I was able to add a Physijs box around my avatar:


It interacts with other Physijs objects (like the ball) as desired, but it breaks the first person controls that I had been using. So tonight I am going to add my own controls tonight.

The easiest way that I can accomplish this is to add a document event listener for keydowns:
document.addEventListener("keydown", function(event) {
  var code = event.which || event.keyCode;
  console.log(code);
  if (code == 0x57) { // w
    console.log("moveForward");
    a_frame.setLinearVelocity({z: -100, y: 0, x: 0 });
  }
  else if (code == 0x41) { // a
    console.log("moveleft");
    a_frame.setLinearVelocity({z: 0, y: 0, x: -100 });
  }
  else if (code == 0x53) { // s
    console.log("moveBackward");
    a_frame.setLinearVelocity({z: 100, y: 0, x: 0 });
  }
  else if (code == 0x44) { // d
    console.log("moveRight");
    a_frame.setLinearVelocity({z: 0, y: 0, x: 100 });
  }
});
And that works pretty much as desired. Except that I run into the same problem that I saw with Box2D.js and Gladius–the avatar keeps moving even after I let go of the movement keys.

So I try the same solution that I used over there. I set the linear damping to zero:
a_frame.setDamping(10);
Only that doesn't work at all. My avatar is ejected out into space.

So I am stuck adding a corresponding keydown event listener:
document.addEventListener("keyup", function(event) {
  var code = event.which || event.keyCode;
  console.log(code);
  if (code == 0x57) { // w
    console.log("stopForward");
    a_frame.setLinearVelocity({z: 0, y: 0, x: 0 });
  }
  else if (code == 0x41) { // a
    console.log("stopleft");
    a_frame.setLinearVelocity({z: 0, y: 0, x: 0 });
  }
  else if (code == 0x53) { // s
    console.log("stopBackward");
    a_frame.setLinearVelocity({z: 0, y: 0, x: 0 });
  }
  else if (code == 0x44) { // d
    console.log("stopRight");
    a_frame.setLinearVelocity({z: 0, y: 0, x: 0 });
  }
});
That works, but it is not entirely satisfactory. If I am hold W and A at the same time, then letting go of either will stop the avatar. I can live with that, but I would certainly prefer something a little more robust. Shame the damping seems broken.

I'll sleep on that and hopefully come up with something better tomorrow.


Day #477

No comments:

Post a Comment