Sunday, September 16, 2012

Physijs Collisions without the Collision

‹prev | My Chain | next›

I rather like my little tilt-a-plane game. It is only 100 lines of code, but demonstrates some nice 3D concepts without too much Three.js / Physijs craziness. The hole in the middle was a little harder than desirable, but still, this might a good sample for Gaming JavaScript.

I need to figure out how to score a win. That is, when the ball falls through the hole, I need to mark the game as won. So, I need something that will register a collision. Any old Physijs shape should do, but I start with a plane:
    // Scoring 
    var score = new Physijs.ConvexMesh(
      new THREE.PlaneGeometry(200, 200),
      new THREE.Material
    );
    score.position.y = -15;
    scene.add(score);
The lack of a third dimension of a plane seems perfect for an object that is intended only to register another object passing it.

But, as I suspected, this is a solid object that prevents my ball from passing through:


I could almost live with this behavior: stopping the game mid-fall is reasonable—perhaps even desirable given the simplicity. For my own edification, I would like to know how to register a collision event without affecting physics. That is, I would like to register the ball falling through the hole, but not interrupt the downward trajectory.

My first try is a collision event listener that immediately removes the "score" plane from the scene:
    score.addEventListener('collision', function() {
      console.log('collision!');
      scene.remove(score);
    });
And, amazingly, that works. When the ball falls through, it keeps falling without any interruption:


Just to make sure that I am not missing something, I comment out the scoring plane's removal. I still see the collision event but the ball comes to rest on the scoring plane:


I really like that solution. It makes sense and it is very short—perfect for Gaming JavaScript. I add some tilting controls and call it a night.

View game in the code editor.


Day #511

No comments:

Post a Comment