<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://devlicio.us/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Christopher Bennage : HTML</title><link>http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx</link><description>Tags: HTML</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP1 (Build: 31106.3070)</generator><item><title>Building a Game With JavaScript: Making Things Move</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2013/03/13/building-a-game-with-javascript-making-things-move.aspx</link><pubDate>Wed, 13 Mar 2013 16:36:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:99712</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;&lt;i&gt;This is a continuation from the &lt;a href="http://dev.bennage.com/blog/2013/01/11/game-dev-02/" target="_blank"&gt;previous post&lt;/a&gt;.&lt;/i&gt;&lt;/p&gt;
&lt;h2&gt;Setting The Stage&lt;/h2&gt;

&lt;p&gt;The game we’re building will have waves of enemy ships fly in to attack the player’s units. Let’s begin by making a simple enemy as well as some dummy targets for them to attack. I’m going to keep the graphics very simple for the moment. Likewise we are going to focus on the enemy behavior and not worry about any player interaction just yet.&lt;/p&gt;

&lt;p&gt;&lt;img style="cursor:default;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-01.png" title="[little, yellow, different]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;Here’s a &lt;a href="http://jsfiddle.net/bennage/HqYeD/18/"&gt;demo&lt;/a&gt; of what we’ll make. Click on the start screen to transition into the game. The little yellow rectangles are our enemy ships. Each one projects its own target as a little red circle. Once it touches its target, it projects a new one and then flies toward it.&lt;/p&gt;

&lt;p&gt;Let’s start from the top down. Our enemy units will “live” in our main screen for the game. (At least for the time being.) This screen needs to expose the same interface that we had for the start screen we made in the last post. We’ll also add a &lt;code&gt;start&lt;/code&gt; method that we’ll call just once in order to initialize things.&lt;/p&gt;
&lt;h3&gt;Implementation&lt;/h3&gt;

&lt;p&gt;Here’s the implementation:&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;  var mainGameScreen = (function () {
    
        // the set of entities we&amp;#39;re updating and rendering
    var entities = [];
    // how many enemy ships do we want to start with
    var numOfEnemyShips = 12;
    
    // intitalize the screen, expected to be called
    // once when transitioning to the screen
    function start() {
        for (var i = 0; i &amp;lt;= numOfEnemyShips; i++) {
            // the numbers passed into `makeEnemyShip` could be anything 
            // they don&amp;#39;t need to be derived from `i`
            entities.push(makeEnemyShip(i * 10, i));
        }
    }

    // drawing the screen means drawing each of its constituents
    function draw(ctx) {
        // first, clean the canvas
        ctx.fillStyle = &amp;#39;black&amp;#39;;
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        // delegate the drawing of each entity to itself
        // note the difference in the way the for loop is set up
        var entityIndex = entities.length - 1;
        for (; entityIndex != 0; entityIndex--) {
            entities[entityIndex].draw(ctx);
        }
    }

    // much like draw, we update each of the screen&amp;#39;s constituents
    function update(elapsed) {
        var entityIndex = entities.length - 1;
        for (; entityIndex != 0; entityIndex--) {
            entities[entityIndex].update(elapsed);
        }
    }

    // this is the object that will be the main screen
    return {
        draw: draw,
        update: update,
        start: start
    };
}());&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;h3&gt;Explanation&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;entities&lt;/code&gt; array will contain a list of the enemies we’re tracking. I used the name “entity” because this is a common term in game development. In general, it means something that has behavior and is drawn to the screen. Thus, you can expect entities to have &lt;code&gt;update&lt;/code&gt; and &lt;code&gt;draw&lt;/code&gt; methods. This is not a hard and fast definition though. You’ll find that the specifics of the definition can vary among engines, frameworks, and developers.&lt;/p&gt;

&lt;p&gt;In our &lt;code&gt;start&lt;/code&gt; function we populate &lt;code&gt;entities&lt;/code&gt; by invoking our (as yet undefined) &lt;code&gt;makeEnemyShip&lt;/code&gt; function. I’m passing in two numbers that &lt;code&gt;makeEnemyShip&lt;/code&gt; will use to set the x and y position of the ship. I could have used random numbers or even hard coded values, however deriving from the loop’s controls makes it easy to cluster all the ships in the upper left corner of the screen.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;draw&lt;/code&gt; and &lt;code&gt;update&lt;/code&gt; functions for the screen are very similar. They both iterate over &lt;code&gt;entities&lt;/code&gt; and invoke the corresponding function on each entity. They also pass along the necessary context. For &lt;code&gt;draw&lt;/code&gt;, this is the 2D drawing context of the canvas and for &lt;code&gt;update&lt;/code&gt; it’s the elapsed time since the last frame.&lt;/p&gt;

&lt;p&gt;Notice how the loop is structured differently from the loop in &lt;code&gt;start&lt;/code&gt;. This is a performance optimization; though it has little consequence with so small an array. On some browsers, the call to &lt;code&gt;length&lt;/code&gt; is a bit expensive. (Especially in cases when the array isn’t an array, but something that is &lt;a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177"&gt;array-like&lt;/a&gt;.) This adds up when you make the call once per iteration of the loop. We move it out of the loop so that we only call it once. Check out &lt;a href="http://jsperf.com/loop-iteration-length-comparison-variations"&gt;this test&lt;/a&gt;. Performance optimizations are tricky and change every time new browsers are released. It’s easy to get confused, and I recommend profiling your code frequently to look for hot spots rather than just guessing about optimizations. I hope to talk more about them later, but if you want more now check out the book &lt;a href="http://www.amazon.com/Performance-JavaScript-Faster-Application-Interfaces/dp/059680279X"&gt;High Performance JavaScript&lt;/a&gt; by &lt;a href="http://www.nczonline.net/"&gt; Nicholas C. Zakas&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I had originally written my loops using the newer &lt;a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach"&gt;Array.forEach&lt;/a&gt; to iterate over &lt;code&gt;entities&lt;/code&gt;. However, this proved to be &lt;strong&gt;significantly&lt;/strong&gt; slower than a &lt;code&gt;for&lt;/code&gt; loop.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The screen’s &lt;code&gt;draw&lt;/code&gt; method also resets the canvas at the beginning of each iteration. If we did not do this, then every thing we drew on previous frames would still be present. For the start screen, I used &lt;code&gt;clearRect&lt;/code&gt; however here I used &lt;code&gt;fillRect&lt;/code&gt; with a solid color.&lt;/p&gt;

&lt;p&gt;Here’s a function that will produce a simple enemy. It follows the same structure we’ve been using, &lt;code&gt;update&lt;/code&gt; to handle the behavior and &lt;code&gt;draw&lt;/code&gt; to actually draw it on the screen.&lt;/p&gt;
&lt;h2&gt;Some Bad Guys&lt;/h2&gt;

&lt;p&gt;Our enemy ships are a little more complicated than the screen they live on. Visually, they &lt;em&gt;appear&lt;/em&gt; to have two components. The little yellow rectangle that moves about the screen and the phantom target that they project as a little red circle. In the final game, they will target one of the player’s units. However, the logic is very similar. In fact, it may become useful in debugging to how each enemy ship render something over it’s actual target.&lt;/p&gt;
&lt;h3&gt;Implementation&lt;/h3&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;// alias (and pre-compute) the angle of 
// a full circle (360°, but in radians)
var fullCircle = Math.PI * 2;

// invoke this function to create an emeny ship entity
// to add to the main game screen
function makeEnemyShip(x, y) {
    
    // position is set based upon the values
    // provided to the function
    var position = {
        x: x,
        y: y
    };
    // the diretion the ship is facing
    var orientation = 0;

    // how quickly can the ship turn?
    var turnSpeed = fullCircle / 50;
    // how quickly can the ship move?
    var speed = 2;
    
    // the phantom target the ship
    // is pursing
    var target = findNewTarget();    

    // the function invoked from the screen&amp;#39;s update
    function update(elapsed) {
        // determine how close we are to our target
        var y = target.y - position.y;
        var x = target.x - position.x;
        var d2 = Math.pow(x, 2) + Math.pow(y, 2);
        if (d2 &amp;lt; 16) {
            // we&amp;#39;ve essentially &amp;quot;touched&amp;quot; it,
            // so create a new target
            target = findNewTarget();
        } else {

            // what&amp;#39;s the different between our orientation
            // and the angle we want to face in order to 
            // move directly at our target
            var angle = Math.atan2(y, x);
            var delta = angle - orientation;
            var delta_abs = Math.abs(delta);

            // if the different is more than 180°, convert
            // the angle a corresponding negative value
            if (delta_abs &amp;gt; Math.PI) {
                delta = delta_abs - fullCircle;
            }

            // if the angle is already correct,
            // don&amp;#39;t bother adjusting
            if (delta !== 0) {
                // do we turn left or right?
                var direction = delta / delta_abs;
                // update our orientation
                orientation += (direction * Math.min(turnSpeed, delta_abs));
            }
            // constrain orientation to reasonable bounds
            orientation %= fullCircle;

            // use orientation and speed to update our position
            position.x += Math.cos(orientation) * speed;
            position.y += Math.sin(orientation) * speed;
        }

    }
    
    // the function invoked from the screen&amp;#39;s draw
    function draw(ctx) {
        
        // save the context&amp;#39;s state before we translate
        // and rotate
        ctx.save();

        // translate to the entity&amp;#39;s position
        ctx.translate(position.x, position.y);
        // rotate the canvas according to the 
        // entity&amp;#39;s orientation
        ctx.rotate(orientation);
        
        // now we begin the actual drawing
        ctx.fillStyle = &amp;#39;yellow&amp;#39;;
        // using negative number to center 
        // around the translated origin
        ctx.fillRect(-3, -1, 6, 2);
        // restore the canvas since we&amp;#39;re 
        // done drawing the entity 
        ctx.restore();

        // now we draw the phantom target
        // though we&amp;#39;ll do so without translating
        // since it&amp;#39;s so simle to draw
        ctx.beginPath();
        ctx.fillStyle = &amp;#39;rgba(255,0,0,0.5)&amp;#39;;
        ctx.arc(target.x, target.y, 2, 0, Math.PI * 2, true);
        ctx.fill();
    }

    // create a random x,y within the bounds of the canvas
    // note, we&amp;#39;ve hard coded the bounds
    function findNewTarget() {
        var target = {
            x: Math.round(Math.random() * 600),
            y: Math.round(Math.random() * 300)
        };

        return target;
    }

    // return an instance of the enemy,
    // it&amp;#39;s state is captured in the closure
    // of the functions
    return {
        draw: draw,
        update: update
    }
}&lt;/pre&gt;&lt;h3&gt;&lt;/h3&gt;&lt;h3&gt;Explanation&lt;/h3&gt;

&lt;p&gt;Each enemy ship will be responsible for tracking its own state. In this code, the state is captured in a closure. In later code, we’ll track the track in a more traditional way. (I haven’t ran tests yet but I think that using a closure may have a performance impact.)&lt;/p&gt;

&lt;p&gt;All of these variables represent the enemy ship’s state.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var position = { x: 0, y: 0 };
var orientation = 0;
var turnSpeed = fullCircle / 50;
var speed = 2;
var target = findNewTarget();  
&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;code&gt;position&lt;/code&gt; is the location on the screen where we will render our ship.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Technically, the is the position in “world space”. World space is the logical space that entities in your game “live in”. This is distinct from “screen space”, which corresponds to the actual pixels on the screens. You can think of it this way: in your game you might have a circle with a radius of 10 and located at (100,100). However, where you draw it on the screen will depend upon where the player is viewing it from. If the player zooms in, the circle will grow larger but this doesn’t change the logical position or radius of the circle. We use the term “projection” to describe this. We project from world space into screen space based upon how the player is viewing the game world. The simplest project of course is just 1:1. Which means that there is no difference between world space and screen space. That’s what will stick with for the moment.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;orientation&lt;/code&gt; is the direction the ship is currently facing. Our ship will always travel in the direction of its orientation. This constraints causes the ship travel in smooth arcs as opposed to abruptly changing its course.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;turnSpeed&lt;/code&gt; and &lt;code&gt;speed&lt;/code&gt; represent how quickly the ship can turn and how fast it can travel respectively. We won’t be modifying these values after setting them, which means the ship will turn and travel at constant rates. These values represent the rates of change for &lt;code&gt;orientation&lt;/code&gt; and &lt;code&gt;position&lt;/code&gt;. Note also, we defined &lt;code&gt;turnSpeed&lt;/code&gt; in terms of &lt;code&gt;fullCircle&lt;/code&gt;. This is an alias for &lt;code&gt;Math.PI * 2&lt;/code&gt;; we are dealing in &lt;a href="http://en.wikipedia.org/wiki/Radian"&gt;radians&lt;/a&gt; and not degrees.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;target&lt;/code&gt; is a value with the shape &lt;code&gt;{ x: Number, y: Number }&lt;/code&gt;. The ship will always attempt to move towards this value by adjusting its &lt;code&gt;orientation&lt;/code&gt;.&lt;/p&gt;
&lt;h4&gt;Update&lt;/h4&gt;

&lt;p&gt;The &lt;code&gt;update&lt;/code&gt; function is the real meat of the enemy ship. First, we check to see if we are close to our target. If we are close enough, we consider our goal accomplished and we set a new target. Otherwise, we change our &lt;code&gt;orientation&lt;/code&gt; so that we are flying toward our current target.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var y = target.y - position.y;
var x = target.x - position.x;
var d2 = Math.pow(x, 2) + Math.pow(y, 2);&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;&lt;img style="cursor:default;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-02.png" title="[calculating the distance]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;Here, &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; are really the distance between &lt;code&gt;target&lt;/code&gt; and &lt;code&gt;position&lt;/code&gt; along the respective axises. We want to know these values in order to calculate the distance between them. In general, you use the &lt;a href="http://en.wikipedia.org/wiki/Pythagorean_theorem"&gt;Pythagorean theorum&lt;/a&gt; to calculate distance. &lt;em&gt;For deeper dive into the math, watch &lt;a href="http://www.khanacademy.org/video/distance-formula"&gt;Distance Formula&lt;/a&gt; on Khan Academy.&lt;/em&gt; Finding the actual real distance uses a square root and calculating a square root is an expensive operation that’s best to avoid whenever you can.&lt;/p&gt;

&lt;p&gt;We can bypass the need by working with the distance² (hence the variable name &lt;code&gt;d2&lt;/code&gt;). We compare this against the hard-coded value of 16 (that’s 4²). In other words, if the distance between the ship and its target is less than 4 units we find a new target.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;if (d2 &amp;lt; 16) {
    target = findNewTarget();
}&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;Once we’ve established what the ship’s target should be, we want the ship to move toward the target. As I’ve just mentioned, I’ve chosen to have the ship move at a constant speed. This means that it does not slow down or speed up. The only thing it can do is to change the direction it’s facing (&lt;code&gt;orientation&lt;/code&gt;). These sort of constraints determine the personality and character of your game. Bear in mind, you don’t need to simulate the physics to have a fun game. Instead, you need to establish behaviors for your game entities that are merely fun. Fortunately, fun behaviors can often be easier to implement that the actual physics. I recommend taking a look at &lt;a href="http://jsfiddle.net/bennage/HqYeD/18/"&gt;the demo&lt;/a&gt; and tweaking the &lt;code&gt;turnSpeed&lt;/code&gt; and &lt;code&gt;speed&lt;/code&gt; values to get a small taste for how the behavior can affect the game’s character.&lt;/p&gt;

&lt;p&gt;&lt;img style="cursor:default;width:336px;height:252px;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-03.png" title="[what&amp;#39;s the delta between the angles?]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;In order to change the ship’s orientation we need to first determine where the ship &lt;em&gt;ought&lt;/em&gt; to be facing. The values of &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt; we just calculated can be interpreted as a &lt;a href="http://en.wikipedia.org/wiki/Euclidean_vector"&gt;vector&lt;/a&gt;. Meaning, it represents the direction and distance (magnitude) from the ship to the current target. To extract the actual angle (in radian) we use &lt;code&gt;Math.atan2(x,y)&lt;/code&gt;.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var angle = Math.atan2(y, x);
var delta = angle - orientation;&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;So now we have the direction the ship &lt;em&gt;wants&lt;/em&gt; to face, &lt;code&gt;angle&lt;/code&gt;, and the direction that it &lt;em&gt;is&lt;/em&gt; facing, &lt;code&gt;orientation&lt;/code&gt;. We calculate the difference between them and store it as &lt;code&gt;delta&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img style="cursor:default;" class="right" src="http://dev.bennage.com/images/posts/game-dev-move-04.png" title="[turning the wrong way]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;The basic idea is that add the value of &lt;code&gt;turnSpeed&lt;/code&gt; to &lt;code&gt;orientation&lt;/code&gt; once each invocation of &lt;code&gt;udpate&lt;/code&gt; until &lt;code&gt;delta&lt;/code&gt; is 0 (meaning that the ship is flying directly at the target). However, some values of &lt;code&gt;delta&lt;/code&gt; will cause the ship to “turn the wrong way”. For example, imagine that the ship is facing the top of the screen and that we’ve defined that as &lt;code&gt;orientation === 0&lt;/code&gt;. Now, imagine that the target is directly to its right. The value of &lt;code&gt;angle&lt;/code&gt; would be π/2 (or 90°). Adding &lt;code&gt;turnSpeed&lt;/code&gt; to &lt;code&gt;orientation&lt;/code&gt; each frame increments the value from 0 to π/2. However, if the target is directly to the left, then the value of &lt;code&gt;angle&lt;/code&gt; would be 3π/2 (or 270°). Simply incrementing &lt;code&gt;orientation&lt;/code&gt; would cause the ship to turn right and keep turning right. This is unintuitive behavior; we expect the ship to turn the shorted distance. In order to accomplish this, we translate any value of &lt;code&gt;delta&lt;/code&gt; higher than π (180°) by subtracting &lt;code&gt;fullCircle&lt;/code&gt;. This normalizes the value of &lt;code&gt;delta&lt;/code&gt; between -π and π (or between -180° and 180°).&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;var delta_abs = Math.abs(delta);
if (delta_abs &amp;gt; Math.PI) {
    delta = delta_abs - fullCircle;
}
&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;We take the absolute value of &lt;code&gt;delta&lt;/code&gt; because otherwise we’d have to check for &lt;code&gt;delta &amp;lt; -Math.PI&lt;/code&gt; as well. Also, we’ll use &lt;code&gt;delta_abs&lt;/code&gt; again.&lt;/p&gt;

&lt;p&gt;If &lt;code&gt;delta&lt;/code&gt; is 0, we don’t need to change &lt;code&gt;orientation&lt;/code&gt;. When it is different we need to modify the value of &lt;code&gt;orientation&lt;/code&gt;.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;if (delta !== 0) {
    var direction = delta / delta_abs;
    orientation += (direction * Math.min(turnSpeed, delta_abs));
    orientation %= fullCircle;
}
&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
 
&lt;p&gt;First, we decide &lt;em&gt;how much&lt;/em&gt; to change it using &lt;code&gt;Math.min(turnSpeed, delta_abs)&lt;/code&gt;. We could just use &lt;code&gt;turnSpeed&lt;/code&gt;. However if we did it’s likely that &lt;code&gt;delta&lt;/code&gt; would never quite be 0 and (depending on the size of &lt;code&gt;turnSpeed&lt;/code&gt;) it could result is jittery motion. Secondly, we want to decided which &lt;em&gt;direction&lt;/em&gt; to turn: positive values to the right and negative values to the left. We multiply the amount &lt;code&gt;direction&lt;/code&gt; to change the sign, because &lt;code&gt;direction&lt;/code&gt; will only ever be 1 or -1. Finally, we modulo &lt;code&gt;orientation&lt;/code&gt; to ensure that it stays within a range of -2π to 2π. Otherwise, the calculation of &lt;code&gt;delta&lt;/code&gt; would be off.&lt;/p&gt;

&lt;p&gt;Our last step in &lt;code&gt;update&lt;/code&gt; is to modifiy the actual position using the latest &lt;code&gt;orientation&lt;/code&gt; and &lt;code&gt;speed&lt;/code&gt;.&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;position.x += Math.cos(orientation) * speed;
position.y += Math.sin(orientation) * speed;
&lt;/pre&gt;&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;Some basic trigonometry is fairly fundamental for most game development. If you’re mathematically lost at this point, I recommend &lt;a href="https://www.khanacademy.org/math/trigonometry/basic-trigonometry"&gt;reviewing over at Khan Academey&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here’s the geometric interpretation of the code. We want the ship to move a distance of &lt;code&gt;speed&lt;/code&gt; in the direction of &lt;code&gt;orientation&lt;/code&gt;. To do this, we need to project this vector (distance and direction) on the x and y axises. Since the distance is the length of the hypothenuse of right triangle, cosine gives us the x part and sine gives us the y part. We can then add these values to the current position.&lt;/p&gt;
&lt;h4&gt;Draw&lt;/h4&gt;

&lt;p&gt;Drawing the ship to the screen is a bit easier to follow. Here’s the flow of the logic:&lt;/p&gt;

&lt;ul&gt;
    &lt;li&gt;Save the state of the drawing context.&lt;/li&gt;
    &lt;li&gt;Transform the context to make it easier to draw our ship.&lt;/li&gt;
    &lt;li&gt;Draw the ship.&lt;/li&gt;
    &lt;li&gt;Restore the context back to its original state.&lt;/li&gt;
    &lt;li&gt;
&lt;p&gt;Draw the target&lt;/p&gt;&lt;pre class="javascript" style="display:none;" name="code"&gt;  function draw(ctx) {

      ctx.save();

      ctx.translate(position.x, position.y);
      ctx.rotate(orientation);

      ctx.fillStyle = &amp;#39;yellow&amp;#39;;
      ctx.fillRect(-3, -1, 6, 2);

      ctx.restore();

      ctx.beginPath();
      ctx.fillStyle = &amp;#39;rgba(255,0,0,0.5)&amp;#39;;
      ctx.arc(target.x, target.y, 2, 0, Math.PI * 2, true);
      ctx.fill();
  }&lt;/pre&gt;&lt;p&gt;&lt;code&gt;
&lt;/code&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Recall that &lt;code&gt;ctx&lt;/code&gt; is the drawing context for the canvas. The context provide a useful API that allows us to move it around before we draw on it. This is analgous to having a sheet of paper that you might shift and rotate in order to make it easier to draw something complicated. This is the purpose of the &lt;code&gt;translate&lt;/code&gt; and &lt;code&gt;rotate&lt;/code&gt; methods.&lt;/p&gt;

&lt;p&gt;First, we use ‘save’ to establishing a checkpoint for the drawing context that we can easily revert back to using ‘restore.’ The calls to &lt;code&gt;translate&lt;/code&gt; and &lt;code&gt;rotate&lt;/code&gt; modify the state of the drawing context. This modified state is very specific to the drawing of our enemy ship. If we didn’t translate and rotate the canvas, we’d have to do a lot more work to figure out where to draw the four corners of the rectangle.&lt;/p&gt;

&lt;p&gt;I decided that I want my ship to be 6px long and 2px wide. Since I want the middle of the middle of my ship to be the point where it rotates, I shift by half the length and half the width. Hence, the values passed to &lt;code&gt;ctx.fillRect(-3, -1, 6, 2)&lt;/code&gt;. This point the new origin (0,0) at the middle of the rectangle, and it makes our call to &lt;code&gt;rotate&lt;/code&gt; behave intuitively. If we used &lt;code&gt;ctx.fillRect(0, 0, 6, 2)&lt;/code&gt; instead, then the ship would appear to rotate around its upper left corner. We’ll use these same techniques once we switch to using &lt;em&gt;sprites&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;After we restore the context’s state, we draw the target. We don’t bother using &lt;code&gt;rotate&lt;/code&gt; because it’s meaningless to rotate a simple circle. Likewise, we don’t bother &lt;code&gt;translate&lt;/code&gt; since the drawing logic is so simple.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The canvas is a broad topic in itself. I recommend taking a look at the tutorials over at &lt;a href="https://developer.mozilla.org/en-US/docs/HTML/Canvas"&gt;MDN&lt;/a&gt;. A handy reference for the APIs themselves can be found on &lt;a href="http://msdn.microsoft.com/en-us/library/ff975057"&gt;MSDN&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2013/03/05/game-dev-03/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=99712" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>Building a Game With JavaScript: Start Screen</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2013/01/14/building-a-game-with-javascript-start-screen.aspx</link><pubDate>Mon, 14 Jan 2013 19:58:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70774</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;p&gt;&lt;em&gt;This is a continuation from the &lt;a href="http://dev.bennage.com/blog/2012/12/07/game-dev-01/"&gt;previous post&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Specification&lt;/h2&gt;

&lt;p&gt;Many games have a start screen or main menu of some sort. (Though I love games like &lt;a href="http://www.braid-game.com/"&gt;Braid&lt;/a&gt; that bypass the whole notion.) Let&amp;#8217;s begin by designing our start screen.&lt;/p&gt;

&lt;p&gt;&lt;img class="right" src="http://dev.bennage.com/images/posts/game-dev-startscreen-01.png" title="[our simple start screen]" style="width:600px;" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;We&amp;#8217;ll have a solid color background. Perhaps the ever lovely cornflower blue. Then we&amp;#8217;ll draw the name of our game and provide an instruction to the player. In order to make sure we have the player&amp;#8217;s attention, we&amp;#8217;ll animate the color of the instruction. It will morph from black to red and back again.&lt;/p&gt;

&lt;p&gt;Finally, when the player clicks the screen we&amp;#8217;ll transition to the main game. Or at least we&amp;#8217;ll stub out the transition.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s a &lt;a href="http://jsfiddle.net/bennage/HqYeD/2/"&gt;demo&lt;/a&gt; based on the code we&amp;#8217;ll cover later in this post (as well as that from the previous post.)&lt;/p&gt;

&lt;h2&gt;Implementation&lt;/h2&gt;

&lt;p&gt;Here&amp;#8217;s the code to implement our start screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://gist.github.com/4371311#file-startscreen-js"&gt;(Go look at the Gist.)&lt;/a&gt;&lt;/p&gt;


&lt;h2&gt;Explanation&lt;/h2&gt;

&lt;p&gt;Recall that our start screen is meant to be invoked by our game loop. The game loop doesn&amp;#8217;t know about the specifics of the start screen, but it does expect it to have a &lt;em&gt;certain shape&lt;/em&gt;. This enables us to swap out screen objects without having to modify the game loop itself. The shape that the game loop expects is this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{
    update: function(timeElapsedSinceLastFrame) { },
    draw: function(drawingContext) { }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Update&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s begin with the start screen&amp;#8217;s &lt;code&gt;update&lt;/code&gt; function. The first bit of logic is this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;hue += 1 * direction;
if (hue &amp;gt; 255) direction = -1;
if (hue &amp;lt; 0) direction = 1;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Perhaps &lt;code&gt;hue&lt;/code&gt; is not the best choice of variable names. It represents the red component for an &lt;a href="http://en.wikipedia.org/wiki/RGB_color_model"&gt;RGB color&lt;/a&gt; value. The range of values for this component is &lt;code&gt;0&lt;/code&gt; (no red) to &lt;code&gt;255&lt;/code&gt; (all the reds!). On each iteration of our loop we &amp;#8220;move&amp;#8221; the hue towards either the red or black.&lt;/p&gt;

&lt;p&gt;The variable &lt;code&gt;direction&lt;/code&gt; can be either &lt;code&gt;1&lt;/code&gt; or &lt;code&gt;-1&lt;/code&gt;. A value of &lt;code&gt;1&lt;/code&gt; means we are moving towards &lt;code&gt;255&lt;/code&gt; and a value of &lt;code&gt;-1&lt;/code&gt; means we are moving towards &lt;code&gt;0&lt;/code&gt;. When we cross a boundary, we flip the direction.&lt;/p&gt;

&lt;p&gt;Keen observers will ask why we bother with &lt;code&gt;1 * direction&lt;/code&gt;. In our current logic, it&amp;#8217;s an unnecessary step and unnecessary steps in game development are generally bad. In this case, I wanted to separate the rate of change from the direction. In order words, you could modify that expression to &lt;code&gt;2 * direction&lt;/code&gt; and the color would change twice as fast.&lt;/p&gt;

&lt;p&gt;This leads us to another important point. Our rate of change is tied to how quickly our loop iterates; most likely 60fps. However, it&amp;#8217;s not guaranteed to be 60fps and that makes this approach a dangerous practice. Once way to detach ourselves from the loop&amp;#8217;s speed would be to use the elapsed time that is being passed into our &lt;code&gt;update&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s say that we want to it to take 2 full seconds to go from red to black regardless of how often the &lt;code&gt;update&lt;/code&gt; function is called. There&amp;#8217;s a span of 256 discrete values between red and black. To make our calculations clear, let&amp;#8217;s say there are 256 units and we&amp;#8217;ll label these units &lt;strong&gt;R&lt;/strong&gt;. Also, the elapsed time will be in milliseconds (ms). For a given frame, if were are given a slice of elapsed time in ms, we&amp;#8217;ll want to calculate how many &lt;strong&gt;R&lt;/strong&gt; units to increase (or decrease) &lt;code&gt;hue&lt;/code&gt; by for that slice. Our rate of change can be defined as &lt;code&gt;256 **R** / 2000 **ms**&lt;/code&gt; or 0.128 &lt;strong&gt;R/ms&lt;/strong&gt;. (You can read that as &amp;#8220;0.128 units of red per millisecond&amp;#8221;.) This rate of change is a constant for our start screen and as such we can define it once (as opposed to calculating it inside the &lt;code&gt;update&lt;/code&gt; function).&lt;/p&gt;

&lt;p&gt;Now that we have the rate of change , we only need to multiply it by the elapsed time received in &lt;code&gt;update&lt;/code&gt; to determine how many &lt;strong&gt;R&lt;/strong&gt;s we want. A revised version of the function would look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var rate = 0.128; // R/ms

function update(elapsed) {
    var amount = rate * elapsed;
    hue += amount * direction;
    if (hue &amp;gt; 255) direction = -1;
    if (hue &amp;lt; 0) direction = 1;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One consequence of this change is that hue will no longer be integral values (as much as that can be said in JavaScript.) This means that we&amp;#8217;d really want to have two values for the hue: an actual value and a rounded value. This is because the RBG model requires an integral value for each color component.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function update(elapsed) {
    var amount = rate * elapsed;
    hue += amount * direction;
    if (hue &amp;gt; 255) direction = -1;
    if (hue &amp;lt; 0) direction = 1;

    rounded_hue = Math.round(hue);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Draw&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s turn our attention to &lt;code&gt;draw&lt;/code&gt; for a moment. One of the first things you &lt;em&gt;generally&lt;/em&gt; do is to clear the entire screen. This is simple to do with the canvas API&amp;#8217;s &lt;code&gt;clearRect&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that &lt;code&gt;ctx&lt;/code&gt; is an instance of &lt;a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#canvasrenderingcontext2d"&gt;CanvasRenderingContext2D&lt;/a&gt; and not a &lt;a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element"&gt;HTMLCanvasElement&lt;/a&gt;. However, there is a handy back reference to the canvas element that we use to grab the actual width and height.&lt;/p&gt;

&lt;p&gt;There are other options other than clearing the entire canvas, but I&amp;#8217;m not going to address this in this post. Also, there are some performance considerations. See the article listed under references.&lt;/p&gt;

&lt;p&gt;After clearing the screen, we want to draw something new. In this case, the game title and the instructions. In both cases I want to center the text horizontally. I created a helper function that I can provide with the text to render as well as the vertical position (y).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function centerText(ctx, text, y) {
    var measurement = ctx.measureText(text);
    var x = (ctx.canvas.width - measurement.width) / 2;
    ctx.fillText(text, x, y);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;measureText&lt;/code&gt; returns the width in pixels that the rendered text will take up. We use this in combination with the canvas element&amp;#8217;s width to determine the x position for the text. &lt;code&gt;fillText&lt;/code&gt; is responsible for actually drawing the text.&lt;/p&gt;

&lt;p&gt;The rendering context &lt;code&gt;ctx&lt;/code&gt; is stateful. Meaning that, what happens when you call methods like &lt;code&gt;measureText&lt;/code&gt; or &lt;code&gt;fillText&lt;/code&gt; depends on the state of the rendering context. The state can be modified by setting its properties.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var y = ctx.canvas.height / 2;
ctx.fillStyle = &amp;#39;white&amp;#39;;
ctx.font = &amp;#39;48px monospace&amp;#39;;
centerText(ctx, &amp;#39;My Awesome Game&amp;#39;, y);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The properties &lt;code&gt;fillStyle&lt;/code&gt; and &lt;code&gt;font&lt;/code&gt; change the state of the rendering context and hence affect the methods calls inside of &lt;code&gt;centerText&lt;/code&gt;. This state applies to all future methods calls. This means that all calls to &lt;code&gt;fillText&lt;/code&gt; will use the color white until you can the &lt;code&gt;fillStyle&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Notice too that we are calculating the x and y values for the text on every frame. This is potentially wasteful since these values are unlikely to change. However, if we want to respond to changes in canvas size (or even changes to the text itself) then we&amp;#8217;d want to continue calculating these on every frame. Otherwise, if we were confident that we didn&amp;#8217;t need to do this, we could calculate these values once and cache them.&lt;/p&gt;

&lt;p&gt;Now let&amp;#8217;s use the red component calculated in &lt;code&gt;update&lt;/code&gt; to render the instructional text.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var color = &amp;#39;rgb(&amp;#39; + hue + &amp;#39;,0,0)&amp;#39;;

ctx.fillStyle = color;
ctx.font = &amp;#39;24px monospace&amp;#39;;
centerText(ctx, &amp;#39;click to begin&amp;#39;, y + 30);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;fillStyle&lt;/code&gt; can be set in a number of ways. Earlier, we used the simple value &lt;code&gt;white&lt;/code&gt;. Here were are using &lt;code&gt;rgb()&lt;/code&gt; to set the individual components explicitly. Any &lt;a href="https://developer.mozilla.org/en-US/docs/CSS/color"&gt;CSS color&lt;/a&gt; &lt;em&gt;should&lt;/em&gt; work with &lt;code&gt;fillStyle&lt;/code&gt;.  (I won&amp;#8217;t be too surprised if some don&amp;#8217;t though.)&lt;/p&gt;

&lt;p&gt;Now you might be wondering why we bothered calculating &lt;code&gt;hue&lt;/code&gt; inside &lt;code&gt;update&lt;/code&gt; since &lt;code&gt;hue&lt;/code&gt; is all about what to draw on the screen. The reason is that &lt;code&gt;draw&lt;/code&gt; is concerned with the &lt;em&gt;mechanics&lt;/em&gt; of rendering. Anything that is modeling the game state should live in &lt;code&gt;update&lt;/code&gt;. The tell in this example is that &lt;code&gt;hue&lt;/code&gt; is dependent on elapsed time and the &lt;code&gt;draw&lt;/code&gt; doesn&amp;#8217;t know anything about that.&lt;/p&gt;

&lt;h3&gt;Update (again)&lt;/h3&gt;

&lt;p&gt;Moving back to &lt;code&gt;update&lt;/code&gt;, the next bit deals with input from the player. In the sample code I&amp;#8217;ve extracted the input logic away. The key thing here is that we are not relying on events to tell us about input from the player. Instead we have some helper, &lt;code&gt;input&lt;/code&gt; in this case, that gives us the current state of the input. If event-driven logic says &amp;#8220;tell me when this happens&amp;#8221; then our game logic says &amp;#8220;tell me if this is happening now&amp;#8221;. The primary reason for this is to be deterministic. We can establish at the beginning of our &lt;code&gt;update&lt;/code&gt; what the current input state is and that it won&amp;#8217;t change before the next invocation of the function. In simple games this might be inconsequential, but in others it can be a subtle source of bugs.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var isButtonDown = input.isButtonDown();

var mouseJustClicked = !isButtonDown &amp;amp;&amp;amp; wasButtonDown;

if (mouseJustClicked &amp;amp;&amp;amp; !transitioning) {
    transitioning = true;
    // do something here to transition to the actual game
}

wasButtonDown = isButtonDown;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We only want transition when the mouse button has been released. In this case, &amp;#8220;released&amp;#8221; is defined as &amp;#8220;down on the last frame but up on this one&amp;#8221;. Hence, we need to track what the mouse button&amp;#8217;s state was on the &lt;em&gt;last&lt;/em&gt; frame. That&amp;#8217;s &lt;code&gt;wasButtonDown&lt;/code&gt; and it lives outside of &lt;code&gt;update&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Secondly, we don&amp;#8217;t want to trigger multiple transitions. That is, if our transition takes some time (perhaps due to animation) then we want to ignore subsequent clicks. We have our &lt;code&gt;transitioning&lt;/code&gt; variable outside of &lt;code&gt;update&lt;/code&gt; to track that for us.&lt;/p&gt;

&lt;p&gt;More to come&amp;#8230;&lt;/p&gt;

&lt;h2&gt;Reference&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.html5rocks.com/en/tutorials/canvas/performance/"&gt;Canvas Performace&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2013/01/11/game-dev-02/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70774" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>Building a Game With JavaScript</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2012/12/10/building-a-game-with-javascript.aspx</link><pubDate>Mon, 10 Dec 2012 08:32:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70577</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;em&gt;&lt;strong&gt;update:&lt;/strong&gt; I just realized that the gist was not being rendered here. I&amp;#39;ve added the code inline.&lt;/em&gt;
&lt;div class="entry-content"&gt;&lt;p&gt;&lt;em&gt;See the &lt;a href="http://dev.bennage.com/blog/2012/12/07/a-n00bs-look-at-html5-game-development/"&gt;introduction post&lt;/a&gt; for context.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;The Loop&lt;/h2&gt;

&lt;p&gt;In general, game development begins with the game loop. If you come from the business world of software development, this will be strange. You don&amp;#8217;t rely on events. &lt;a href="http://haacked.com/"&gt;Phil Haack&lt;/a&gt; once asked me &amp;#8220;why a loop?&amp;#8221;, to which I responded &amp;#8220;uh&amp;#8230;&amp;#8221;. However, a much better answer would have been &lt;a href="http://stackoverflow.com/questions/2565677/why-is-a-main-game-loop-is-necessary-for-developing-a-game"&gt;this one on stackoverflow&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Okay, so we should use a master loop. If our runtime is the browser, how do setup this loop? There&amp;#8217;s a relatively new API called &lt;a href="http://www.w3.org/TR/animation-timing/"&gt;&lt;code&gt;requestAnimationFrame&lt;/code&gt;&lt;/a&gt; and that&amp;#8217;s what most folks recommend. Check out these for details:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://paulirish.com/2011/requestanimationframe-for-smart-animating/"&gt;Paul Irish&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://ie.microsoft.com/testdrive/Graphics/RequestAnimationFrame/Default.html"&gt;The IE Team&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;(I do recall reading something negative along the way about the API, but I couldn&amp;#8217;t find it again.)&lt;/p&gt;

&lt;p&gt;I used the &lt;code&gt;requestAnimationFrame&lt;/code&gt; &lt;a href="https://gist.github.com/1579671"&gt;shim&lt;/a&gt; referenced in the Paul Irish post above. The shim is only necessary for older browsers that have not implemented the API. &lt;em&gt;By the way, we refer to each iteration of the loop as a &amp;#8220;frame&amp;#8221; because of the analogy with traditional animation.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;Implementation&lt;/h3&gt;

&lt;p&gt;Now that we&amp;#8217;ve ensured that &lt;code&gt;requestAnimationFrame&lt;/code&gt; is present we can get to our game loop. Here is my game&amp;#8217;s bootstrap code (well, an early version of it):&lt;/p&gt;

&lt;pre&gt;
var canvas,        // the visible canvas element    
    surface,       // the 2d context of `canvas`
    currentScreen; // the currently rendered screen for the game

function beginLoop() {
    var frameId = 0;
    var lastFrame = Date.now();

    function loop() {
        var thisFrame = Date.now();

        var elapsed = thisFrame - lastFrame;

        frameId = window.requestAnimationFrame(loop);

        currentScreen.update(elapsed);
        currentScreen.draw(surface);

        lastFrame = thisFrame;
    }

    loop();
}


canvas = document.querySelector(&amp;#39;canvas#board&amp;#39;);
canvas.setAttribute(&amp;#39;width&amp;#39;, 800);
canvas.setAttribute(&amp;#39;height&amp;#39;, 600);

surface = canvas.getContext(&amp;#39;2d&amp;#39;);

currentScreen = startScreen;
beginLoop();
&lt;/pre&gt;
&lt;p&gt;The &lt;a href="https://gist.github.com/4238210"&gt;gist is also available&lt;/a&gt;.&lt;/p&gt;


&lt;p&gt;The heart of this the &lt;code&gt;loop&lt;/code&gt; function. It has the following step:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;capture the current time&lt;/li&gt;
&lt;li&gt;calculate the time that has elasped since the last frame&lt;/li&gt;
&lt;li&gt;execute the game&amp;#8217;s logic for the frame (that&amp;#8217;s the update and draw invocations)&lt;/li&gt;
&lt;li&gt;request the next invocation of &lt;code&gt;loop&lt;/code&gt; using &lt;code&gt;requestAnimationFrame&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;record the current time of the this frame for calculations in the next one&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;&lt;em&gt;N.B. This code doesn&amp;#8217;t use &lt;code&gt;frameId&lt;/code&gt; yet. The idea is that this handle could be used to halt the loop.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;beginLoop&lt;/code&gt; function is there merely to provide a closure for some of the variables used to track the state of the loop. It kicks off the loop with its initial invocation of &lt;code&gt;loop&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The big mystery inside of &lt;code&gt;loop&lt;/code&gt; is the &lt;code&gt;currentScreen&lt;/code&gt; object. Here I was thinking ahead (which can be dangerous). I know that my game will have at least two &amp;#8220;screens&amp;#8221;, possibly more:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;start menu screen&lt;/li&gt;
&lt;li&gt;main game screen (where the action takes place)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I wanted the loop logic to work with both (as well as any future screens). I expect screen objects to have two methods:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;update&lt;/code&gt; takes the time elapsed since the last frame and is responsible for updating the state of the game.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;draw&lt;/code&gt; takes the drawing context (from the canvas) and is responsible for rendering the current state of the game.&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;You&amp;#8217;ll also see that I grab a canvas element and capture its drawing context. If you are not familiar with the canvas APIs, I recommend that you &lt;a href="https://developer.mozilla.org/en-US/docs/HTML/Canvas"&gt;start here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Why two different methods for game logic?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Keeping the &lt;code&gt;update&lt;/code&gt; and &lt;code&gt;draw&lt;/code&gt; functions separate is important. When frames becomes expensive to compute, the game may respond with lag or non-deterministic behavior. Too avoid this, you might want your game to skip over some logic during a particular iteration of the loop. However, it&amp;#8217;s very likely that you &lt;em&gt;won&amp;#8217;t&lt;/em&gt; want to drop calls to &lt;code&gt;update&lt;/code&gt;. It&amp;#8217;s not necessary a big deal if you skip &lt;em&gt;rendering&lt;/em&gt; a couple of frames, however if skip calculating the location of a projectile then it might mysteriously &amp;#8220;pass through&amp;#8221; its target. This will become more relevant to us in particular, because I&amp;#8217;d like to all the player to control the speed of game (a common feature of many tower defense games).&lt;/p&gt;

&lt;p&gt;Right now &lt;code&gt;update&lt;/code&gt; and &lt;code&gt;draw&lt;/code&gt; are always called for each iteration of the loop, so the distinction is academic in this context. We could though calculate our frame rate in &lt;code&gt;loop&lt;/code&gt; and occasionally skip invoking &lt;code&gt;draw&lt;/code&gt; if the rate slowed down.&lt;/p&gt;

&lt;p&gt;Now we have enough in place to begin working on our start menu screen.&lt;/p&gt;

&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2012/12/07/game-dev-01/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70577" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item><item><title>a n00b’s Look at HTML5 Game Development</title><link>http://devlicio.us/blogs/christopher_bennage/archive/2012/12/08/a-n00b-s-look-at-html5-game-development.aspx</link><pubDate>Sat, 08 Dec 2012 18:45:00 GMT</pubDate><guid isPermaLink="false">40756a8b-6212-4073-9d98-6c26781577de:70574</guid><dc:creator>Christopher Bennage</dc:creator><slash:comments>0</slash:comments><description>&lt;h2&gt;Preamble&lt;/h2&gt;

&lt;p&gt;Something disgusting, like six years ago, I &lt;a href="http://www.43things.com/things/view/33927/develop-a-video-game"&gt;listed on 43Things&lt;/a&gt; that I wanted to write a video game. I&amp;#8217;ve actually made numerous arrested attempts ever since I started programming with my TI-94a back in 1983. My last attempt has been much less arrested (though still incomplete).&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve learned a lot in my most recent endeavor, so it&amp;#8217;s time to share. You can follow the &lt;a href="https://github.com/bennage/sidera"&gt;actual work in progress&lt;/a&gt;, but my plan it to recreate the steps I&amp;#8217;ve gone though over the course of a few posts.&lt;/p&gt;

&lt;h2&gt;Goals&lt;/h2&gt;

&lt;p&gt;I am too ambitious. With that in mind, I created a set of constraints for making a game.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;keep gameplay simple&lt;/li&gt;
&lt;li&gt;don&amp;#8217;t worry about art (that can come later)&lt;/li&gt;
&lt;/ul&gt;


&lt;p&gt;I started off wanting to make a game for the Windows 8 store. I decided afterwards that I will target modern browsers in general. This means that I took no dependencies on the WinJS libraries. (Though the Windows store is still my endgame.)&lt;/p&gt;

&lt;p&gt;I also decided to &lt;em&gt;not&lt;/em&gt; use any frameworks (such as &lt;a href="http://impactjs.com/"&gt;ImpactJS&lt;/a&gt;). Not because they are bad, but because I want to learn why I need them.&lt;/p&gt;

&lt;h2&gt;Gameplay&lt;/h2&gt;

&lt;p&gt;&lt;img class="right" src="http://dev.bennage.com/images/posts/sidera-early-build.png" title="[screen capture of the current build of my game]" alt="" /&gt;&lt;/p&gt;

&lt;p&gt;This is my spec (well, more or less).&lt;/p&gt;

&lt;p&gt;I decided to make a simple &lt;a href="http://en.wikipedia.org/wiki/Tower_defense"&gt;tower defense&lt;/a&gt; game. My inspiration is &lt;a href="http://old.casualcollective.com/#games/TSG"&gt;The Space Game&lt;/a&gt; from the Casual Collective, as well as plenty of influence from StarCraft.&lt;/p&gt;

&lt;p&gt;The player will build structures in an asteroid field. Waves of enemy ships will attempt to destroy those structures. The player has to manage resources such as minerals and solar power, and fend of the attacks. Structures will cost minerals to build and require power to operate.&lt;/p&gt;

&lt;p&gt;The player can navigate the map (up, down, left, right) as well as zooming in and out. There will be a minimap.&lt;/p&gt;

&lt;p&gt;Graphics will be sprite-based. The game should be touch-friendly (really, I want touch to be primary).&lt;/p&gt;

&lt;h2&gt;Resources&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://buildnewgames.com/"&gt;Build New Games&lt;/a&gt;, a collaboration between Microsoft and &lt;a href="http://bocoup.com/"&gt;Bocoup&lt;/a&gt;, is an excellent set of articles on HTML/JavaScript game development.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;My friend, &lt;a href="http://mattmadegames.com/"&gt;Matt Peterson&lt;/a&gt;, currently a graduate student at &lt;a href="https://www.digipen.edu/"&gt;DigiPen&lt;/a&gt;, who&amp;#8217;s advice and guidance has been most useful.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;a href="http://dev.bennage.com/blog/2012/12/07/game-dev-01/"&gt;next »&lt;/a&gt;
&lt;/div&gt;
&lt;em&gt;Comment on this post at &lt;a href="http://dev.bennage.com/blog/2012/12/07/a-n00bs-look-at-html5-game-development/"&gt;dev.bennage.com&lt;/a&gt;&lt;/em&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://devlicio.us/aggbug.aspx?PostID=70574" width="1" height="1"&gt;</description><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/Game+Development/default.aspx">Game Development</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/javascript/default.aspx">javascript</category><category domain="http://devlicio.us/blogs/christopher_bennage/archive/tags/HTML/default.aspx">HTML</category></item></channel></rss>