Friday, August 31, 2012

Dirt Simple Text with Three.js

‹prev | My Chain | next›

Up today, I would like to display the text "Game Over" when the raft impacts an obstacle in my Three.js / Physijs game. I can already do it in the JavaScript console, but I need a way to convey to the user that she / he has lost.

I investigate TextGeomtry (example) some, but decide that feels like overkill for my needs. I just want to display regular text.

It turns out that simple HTML will suffice for this. That is how the Three.js stats does it. So I replace the "game over" console.log() with a call to a new gameOver() function:
function drawObstacles() {
  obstacle_markers.forEach(function(marker) {
    // build obstacle

    obstacle.addEventListener('collision', function(object) {
      if (object == raft) gameOver();
      else {
        console.log(object);
      }
    });
  });
}
In gameOver(), I create a new <div>, style it, and position it for maximum impact:
function gameOver() {
  console.log("Game Over!!!!");

  var text = document.createElement('div');
  text.style.position = 'absolute';
  text.innerHTML = '<h1>Game Over!</h1>';
  text.style.backgroundColor = 'white';
  text.style.borderRadius = "5px";
  text.style.padding = "0px 20px";
  text.style.left = "100px";
  text.style.top = "100px";
  document.body.appendChild(text);

  game_over = true;
}
For good measure, I set the global variable game_over to true. In my animate() function I then add a guard clause to stop the animation if the game is over:
function animate() {
  if (game_over) return;

  requestAnimationFrame(animate);
  applyRiverCurrent();
  scene.simulate(); // run physics
  render();
  drawObstacles();
}
With that, I have my desired game-over behavior:


That will do for a stopping point today. Now back to writing Gaming JavaScript. It's deadline day!


Day #495

No comments:

Post a Comment