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 {
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'); = 'absolute';
  text.innerHTML = '<h1>Game Over!</h1>'; = 'white'; = "5px"; = "0px 20px"; = "100px"; = "100px";

  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;

  scene.simulate(); // run physics
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