Wednesday, July 25, 2012

Simple Three.js Bounds, If Not Collisions

‹prev | My Chain | next›

I am nearly done with my Three.js avatar. I have an island for it to walk around. I have the arms and legs animated as it walks. The avatar even spins in the right direction when walking. The only problem left is that I can walk on water:

It is easy enough to bound the avatar. In the render() method, I check the X and Z position of the avatar, stopping motion if necessary:
function render() {
  // ...
  if (controls.object.position.z >  2800) controls.moveLeft = false;
  if (controls.object.position.z < -2800) controls.moveRight = false;
  if (controls.object.position.x >  2800) controls.moveBackward = false;
  if (controls.object.position.x < -2800) controls.moveForward = false;

  // ...
  renderer.render(scene, camera);

The FirstPersonControls are tied to the avatar. So I can access the avatar as controls.object. Then it is a simple matter of disabling the controls before the call to controls.update().

With that, I am prevented from leaving the island:

That is probably sufficient for my needs, but I would like to get collision detection working. My understanding is that rays are needed for collision detected. So I add a wall whose collision that I would like to detect and implement a collision detection function in render():
function detectCollision() {
  var vector = controls.object.position ).normalize();
  var ray = new THREE.Ray(controls.position, vector);
  var intersects = ray.intersectObjects(walls);

  if (intersects.length > 0) console.log(intersects);
Unfortunately, that never works. Even if I place the wall at the origin where the avatar starts, the ray and the walls never intersect.

I am unclear why Rays are needed for collision detection. Position alone ought to be sufficient to determine if two objects overlap. This leads me to believe that I may very well be doing something wrong. But what I am doing wrong eludes me for tonight. I will pick back up with this tomorrow. If I cannot solve it by then, it is probably time to venture back to Gladius land.

Day #458

No comments:

Post a Comment