HTML and CSS Reference
In-Depth Information
The Update/Render (Repeat) Cycle
In any of our application states, we might need to employ animation and screen up-
dates. We will handle these updates by separating our code into distinct update() and
render() operations. For example, as you might recall, the player ship can move around
the game screen, and when the player presses the up arrow key, the ship's thrust frame
of animation will be displayed rather than its static frame. In the previous examples,
we contained all the code that updates the properties of the ship, as well as the code
that actually draws the ship, in a single function called drawScreen() . Starting with
Example 8-10 , we will rid ourselves of this simple drawScreen() function and instead
employ update() and render() functions separately. We will also separate out the code
that checks for the game-specific key presses into a checkKeys() function.
Let's reexamine the contents of the drawScreen() function from Example 8-8 , but this
time break the function up into separate functions for each set of tasks, as shown in
Example 8-10 .
Example 8-10. Splitting the update and render cycles
function gameStatePlayLevel() {
checkKeys();
update();
render();
}
function checkKeys() {
//check keys
if (keyPressList[38]==true){
//thrust
var angleInRadians = rotation * Math.PI / 180;
facingX = Math.cos(angleInRadians);
facingY = Math.sin(angleInRadians);
movingX = movingX+thrustAcceleration*facingX;
movingY = movingY+thrustAcceleration*facingY;
}
if (keyPressList[37]==true) {
//rotate counterclockwise
rotation−=rotationalVelocity;
}
if (keyPressList[39]==true) {
//rotate clockwise
rotation+=rotationalVelocity;;
}
}
function update() {
Search WWH ::




Custom Search