The Update/Render (Repeat) Cycle
In any of our application states, we might need to employ animation and
screen updates. 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, we’ll 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 ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.