functionaddBackground() {
document.body.style.backgroundColor ='black';
varstars =newTHREE.Geometry();
while(stars.vertices.length < 1000) {
varlat = Math.PI * Math.random() - Math.PI/2;
varlon = 2*Math.PI * Math.random();
stars.vertices.push(newTHREE.Vector3(
1000 * Math.cos(lon) * Math.cos(lat),
1000 * Math.sin(lon) * Math.cos(lat),
1000 * Math.sin(lat)
));
}
varstar_stuff =newTHREE.ParticleBasicMaterial({size: 5});
varstar_system =newTHREE.ParticleSystem(stars, star_stuff);
scene.add(star_system);
}
This is similar to the space background from the planet simulator. Once you
have that, uncomment the addBackground() function in the code outline.
Game Logic
As we saw in Chapter 15, Project: The Purple Fruit Monster Game, on page 133,
it’s not a good idea to process game logic as often as we perform animation
work. So in this game, we again keep the two separate. Add the following
game-logic definition below the addBackground() function body.
functiongameStep() {
if(ball.position.y < -100) resetBall(ball);
setTimeout(gameStep, 1000 / 60);
}
First our game logic tells Physijs to simulate physics in our scene. Then we
check to see if the ball has fallen off the board.
We’re processing game logic sixty times per second. That is, we set the timeout
of that function to 1000 milliseconds divided by 60, or 16.67 milliseconds.
So gameStep() is processed every 16.67 milliseconds, which may seem very
frequent. In computers, though, that is not very frequent. The animation will
get updated at least sixteen times, and probably a lot more, during those
1000 milliseconds.
Truth be told, it doesn’t really matter that we have our game logic separated
in this case. Processing physics in this simple game and deciding if the ball’s
Y position is less than -100 is not too much work for most computers. Still,
this is a good habit to develop when writing games.
Now uncomment the gameStep() function from the code outline and...
Chapter 16. Project: Tilt-a-Board • 156
Prepared exclusively for Michael Powell report erratum • discuss