Fixed restart bug in Three.js game cube-roll

While I was looking for a game to help develop, I found the game cube-roll on github.

The bug I fixed was issue 1 : cannot restart game, the problem occurred after you play a round, the game will freeze and you were not able to restart it.

This turned out to be a fun project to work on, it was challenging at the start. Since, I have never worked on a game before so I didn’t know what the code was doing. But after looking through the code for a bit, I found out that the game was using Three.js. Three.js is a javascript 3D library I was able to learn a bit more from their docs on what the code was doing.

After learning the code, I found out were the problem was, it turned out most of the code was already their it was just not working correctly. The problem resided in the main function, when the game is over and the user pressed enter, it would cue a .once() command in the main. Originally it just called the main again to restart the game. The problem was the game never got cleared so the old game was still running.

In order to fix the issue I used the following code, it first calls the constructor on the world object hence clearing and restarting the game. I then pass that world object back to main to restart the game. The important factor was I am not ever creating a new world just resting it.

sync function main(connectToServer, world = undefined) {
  renderPause = true;
  if(!world){
    world = await new World();
  }
  world.playerControls.once('enterWhenGameOver', async () => {
    await world.constructor();
    main(false,world);
  });
  if (connectToServer) {
      server = await initServer;
      server.on('clientKeyUp', key => {
        world.playerControls.processRemoteControl(key);
      });
  }
  renderPause = false;
  if (!tickingStarted) {
    tick(world, server);
  }
}

The reason I do not want to loose the world object is because it is being used in the tick() function. The tick function is what refreshes the game it contains a reference to the world object, so that is the reason I needed to keep the same instance of world object when the restarts.

function tick(world, server) {
  requestAnimationFrame(() => tick(world, server));
  if (!renderPause) {
    tickingStarted = true;
    world.update();
    world.render();
    server && server.stream();
  }
}

Here is a link to my PR: https://github.com/mklan/cube-roll/pull/3

 

Leave a Reply

Your email address will not be published. Required fields are marked *