From our earlier work, we’re familiar with wrapping 3D shapes and materials
inside a physics-aware mesh. We’ve also seen the various color settings. In
this case, we make our ball a very shiny red (0xff0000 is red). We set its castShad-
ow property to true so that it will have a shadow. Lastly, we add it to the scene.
All very standard—except for the resetBall() function that we add now.
functionresetBall(ball) {
ball.__dirtyPosition = true;
ball.position.set(-33, 50, -65);
ball.setLinearVelocity(0,0,0);
ball.setAngularVelocity(0,0,0);
}
dirty Starts with Two Underscores
Be sure to add two underscores before dirtyPosition. It’s not _dirtyPosition.
The setting is __dirtyPosition. If you use only one underscore, there
will be no errors, but the movement controls won’t work.
This resetBall() function starts with the very funny ball.__dirtyPosition setting. Pro-
grammers have odd senses of humor and the dirty position is an example of
this. Programmers often use the word “dirty” to mark something that has
been changed, usually in a wrong way.
In this case, we’re doing something very wrong by changing the ball’s position.
In real life, things do not just change position. The same is true in a 3D
physics world. Things cannot just be in a new place all of a sudden. But we
need to change the ball’s position at the beginning of the game and whenever
the game resets.
So __dirtyPosition is our way of telling the game physics, “Look, I know this is
wrong, but I know what I’m doing and I need the following position to change
right away.” And, since we asked so politely, the game physics will answer,
“No trouble at all! Just don’t forget that setting if you ever need to do it again.”
Isn’t That Premature Generalization?
Back in Functions: Use and Use Again, I said programmers should
never write pretty code first. We could have added that position
code directly inside addBall(). We didn’t for two reasons. First, we
already know we’ll need to reset the game—just like we talked about
with Project: The Purple Fruit Monster Game. Second, I didn’t want
you to have to change a whole bunch of code after you type it.
Still, be cautious when doing something like this.
report erratum • discuss
Outline the Game • 149
Prepared exclusively for Michael Powell