<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by André Teixeira on Medium]]></title>
        <description><![CDATA[Stories by André Teixeira on Medium]]></description>
        <link>https://medium.com/@andreteixeira?source=rss-399de1196779------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OPHzxpEHJlmfqAV7YFp_rw.jpeg</url>
            <title>Stories by André Teixeira on Medium</title>
            <link>https://medium.com/@andreteixeira?source=rss-399de1196779------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:06:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreteixeira/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a space shooter game with HTML5 canvas & Typescript — Part 3]]></title>
            <link>https://itnext.io/building-a-space-shooter-game-with-html5-canvas-typescript-part-3-f1b2808e85bd?source=rss-399de1196779------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b2808e85bd</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[André Teixeira]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 06:33:37 GMT</pubDate>
            <atom:updated>2020-12-27T10:30:48.360Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a space shooter game with HTML5 canvas &amp; Typescript — Part 3</h3><p>This article is the third part of a series composed by:</p><p><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-1-20663025c7f5">Part 1 — Draw stars</a> ⭐<br><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-2-bf39f584c4be">Part 2 — Draw a spaceship and make it rotate</a> 🚀<br><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-3-f1b2808e85bd">Part 3 — Make the spaceship move and shoot</a> 💨<br>Part 4 — Make a joystick for mobile 🕹️ 📱<br>Part 5 — Enemy ships and collision 💥</p><p>After implementing the steps described in part 1 and part 2 of this series, we have a starry sky and a spaceship able to rotate around/over its center. IMHO this game needs more action. Therefore, part 3 will be about making it flying around and shooting.</p><h3>Acceleration and movement</h3><p>This ship has a rear-engine; consequently, propulsion makes it move in the direction of its nose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*4wLzXodPsiu3dsGL60afew.png" /></figure><p>Given that the game loop invokes the draw method about 60 times per second, we can think about calculating a normal vector and moving the ship 1 step towards it in every cycle.</p><p>The following illustration shows a snapshot of one of the draw method invocations. Let&#39;s take a deeper look at how the calculations would happen on this individual execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*i8j2rNDTILvGgU_ha5Z6Wg.png" /></figure><h4>TL/DR</h4><p>At this point, the spaceship update function already knows positions x, y, and the rotation of the spaceship on every execution. It can be represented in the chart as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*_P02nKIVVrZSsHraFZBHcA.png" /></figure><p>We can now define a constant that will represent the length of the spaceship movement on each iteration. This constant, represented above as the blue vector, is the hypothenuse of the example&#39;s triangle (I will pick for this study the random value 18.0277).</p><p>Knowing that we can use the <strong>Pythagoras theorem</strong> to get the x and y values for p2. Being:</p><pre>sin = opposite leg / hypothenuse;<br>sen = adjacent leg / hypothenuse;</pre><p>We can affirm that:</p><pre>x = sin(33<strong>) * </strong>hypothenuse;<strong><br></strong>y = cos(33<strong>) * </strong>hypothenuse;</pre><p>Or, a generic approach using JavaScript:</p><pre>const x = Math.sin(this.rotation<strong>) * </strong>this.speed<strong>;<br></strong>const y = Math.cos(this.rotation<strong>) * </strong>this.speed<strong>;</strong></pre><h3>Making it fly</h3><p>Following are the attributes needed to make it work:</p><ul><li><strong>Speed</strong> — representing the length of the spaceship displacement over the plane;</li><li><strong>Acceleration</strong> — being the resultant Vector;</li><li><strong>Deceleration</strong> — representing the friction that decreases spaceship movement after the throttle is released.</li></ul><h4>The variables</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb9b7bd9909be1b505b103a2a6b45cc/href">https://medium.com/media/5eb9b7bd9909be1b505b103a2a6b45cc/href</a></iframe><h4>The keyboard listener</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2db1756e6d8f5997c3e4c85827b78f4/href">https://medium.com/media/d2db1756e6d8f5997c3e4c85827b78f4/href</a></iframe><h4>The movement</h4><p>And finally, in the spaceship update method, we apply the change value by adding the new accelerated position to the current spaceship position. We can do it by adding the following block to the spaceship update method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeffd69b2676045948d63ca070f4227d/href">https://medium.com/media/aeffd69b2676045948d63ca070f4227d/href</a></iframe><p>The add and subtract operations, which will add the acceleration vectors to the current position ones, are also needed on the Vector class, in the format:</p><pre>public add(vector: Vector): void {<br>    this.x += vector.x;<br>    this.y += vector.y;<br>}</pre><pre>public subtract(vector: Vector): void {<br>    this.x -= vector.x;<br>    this.y -= vector.y;<br>}</pre><h4>Important details</h4><p>Since the canvas plane origin (0,0) is located on the top left, we need to invert the Y-axis calculation direction by multiplying it by -1.</p><h4>Partial demo</h4><p>You can see a working demo until this point at:<br><a href="http://spaceship-part3-partial.s3-website.eu-central-1.amazonaws.com/">http://spaceship-part3-partial.s3-website.eu-central-1.amazonaws.com/</a></p><h3>Shooting</h3><p>The theory behind firing is not very different. Once the user hits the trigger (space bar), a projectile will be drawn on the top/center of the ship and follow the normal vector projection for the given draw function execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f134435a4c0c1211382fdb8fadebf100/href">https://medium.com/media/f134435a4c0c1211382fdb8fadebf100/href</a></iframe><p>The idea of shooting is the same as moving, with the difference that when a bullet instance is created, it gets the spaceship angle for the given moment. In contrast, the spaceship moving method gets the latest direction for every drawing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ffb583c70e2fe143a11507c4e342815/href">https://medium.com/media/1ffb583c70e2fe143a11507c4e342815/href</a></iframe><p>And as a final step, it is needed to draw and update the game class bullets. We need a list of bullets that will be rendered on their updated location on every game draw (sounds like what we did with the stars on part1, right?).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87ba1162be903cd880253fc45950057d/href">https://medium.com/media/87ba1162be903cd880253fc45950057d/href</a></iframe><h4><strong>The code until this stage is tagged at:</strong></h4><p><a href="https://github.com/ateixeira/spaceship-game/releases/tag/part3_final">https://github.com/ateixeira/spaceship-game/releases/tag/part3_final</a></p><h4>The demo until this part:</h4><p><a href="http://spaceship-part3-final.s3-website-eu-west-1.amazonaws.com/">http://spaceship-part3-final.s3-website-eu-west-1.amazonaws.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b2808e85bd" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-a-space-shooter-game-with-html5-canvas-typescript-part-3-f1b2808e85bd">Building a space shooter game with HTML5 canvas &amp; Typescript — Part 3</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a space shooter game with HTML5 canvas & Typescript — Part 2]]></title>
            <link>https://itnext.io/building-a-space-shooter-game-with-html5-canvas-typescript-part-2-bf39f584c4be?source=rss-399de1196779------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf39f584c4be</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[André Teixeira]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 06:27:14 GMT</pubDate>
            <atom:updated>2020-12-27T10:30:18.029Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a space shooter game with HTML5 canvas &amp; Typescript — Part 2</h3><p>This article is the second part of a series composed by:</p><p><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-1-20663025c7f5">Part 1 — Draw stars</a> ⭐<br><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-2-bf39f584c4be">Part 2 — Draw a spaceship and make it rotate</a> 🚀<br><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-3-f1b2808e85bd">Part 3 — Make the spaceship move and shoot</a> 💨<br>Part 4 — Make a joystick for mobile 🕹️ 📱<br>Part 5 — Enemy ships and collision 💥</p><h3>🚀🚀🚀🚀</h3><p>The next thing we need for a functional game is a spaceship. In Part 1 of this series, we talked about the 3 basic operations that the game loop needs to take care of:</p><ol><li><strong>read user input</strong></li><li><strong>update the game state</strong></li><li><strong>re-paint the canvas</strong></li></ol><p>This article will pass through the steps, not necessarily in the above order.</p><h3>Paint the canvas</h3><p>Let&#39;s start by the 3rd step. What we need now is a Spaceship class, with a draw method that will define how it will look like on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*zEc1UV66ijKLS8KDTwJabw.png" /><figcaption>Spaceship illustration</figcaption></figure><p>On the left, you can see what I want to achieve on the spaceship draw method. I have sketched the illustration on a basic diagramming tool to know the proportions when drawing it on the canvas.</p><p>Its body has 10 squares height, and the widest width is about 3,5 squares. This proportions will be useful when playing around with the width and height variables and the canvas line drawing methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*cBX8iYKzM752YEFJi0A31Q.png" /><figcaption>Spaceship centre</figcaption></figure><p>It is good to note that later when we start implementing the behaviours of this spaceship, we will want it to rotate over its own centre.</p><p>To make our lives easier during a next step, we can already draw the shapes around that centre. On this example, I moved it a bit to the back of the ship, near the engines.</p><h4>The spaceship class</h4><p>This is how the spaceship class initially looks like, being cx and cy the coordinates of the centre of the ship:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5e2afede9d7f7f0a8f1c7d58bc83668/href">https://medium.com/media/d5e2afede9d7f7f0a8f1c7d58bc83668/href</a></iframe><h4>Drawing the parts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*fUtBHmVp4qnM1WIxwW6D8Q.png" /><figcaption>Spaceship illustration 2</figcaption></figure><p>By exploding the illustration, we notice that it is composed of 13 segments. I will try to draw them in the displayed order.</p><p>From the gist above, you can see the step represented as <strong>1</strong> is already included in the draw method (for now I&#39;m happy with a flat bottom for the spaceship).</p><p>Also notice in the first spaceship illustration that segment 1 has 1 square width, corresponding to about <strong>30%</strong> of the total width. So, we can move to the provided X, Y coordinates where the ship will be placed and draw a line to <strong>X + 0.3 * width</strong>.</p><pre>ctx.moveTo(bottomCenter.x, bottomCenter.y);</pre><pre><em>// Half bottom line<br></em>ctx.lineTo(bottomCenter.x + width * 0.3, bottomCenter.y);</pre><p>Segment 2 is not that simple. The <strong>bezierCurveTo </strong>method<strong> </strong>should do the trick for it. It accepts 2 control point coordinates <strong>(x, y)</strong> and a final point coordinate for the curve. To find the control point coordinates quickly and in a more visual way, my trick was to observe the drawing tools proportions.</p><p>This is how the curve looks like on my drawing tool when I select the curved line segment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*WYvvVpwD0ILONnAHQZOpIw.png" /></figure><p>Considering that the start point is the first point of the current path (or the last point of the previous segment), we see that the first control point is close to <strong>x = 1.75 and y = 2</strong>, the second control point is near <strong>x = 1.7</strong> and <strong>y = 8</strong> and the final point is at x = 0 and y = 10. So the second step of the spaceship drawing can be like:</p><pre>ctx.bezierCurveTo(<br>  cx + width,<br>  cy - height * 0.2,<br>  cx + width,<br>  cy - height * 0.8,<br>  cx,<br>  cy - height<br>);</pre><p>The <strong>curveToBezier </strong>method<strong> </strong>is useful here because we need 2 control points for this curve, while the <strong>quadraticCurveTo</strong> method can be used for simpler curves with a single control point, which is the case for the landing platform<strong>.</strong></p><h4>The final drawing method</h4><p>I replicated this steps to build up all the shapes that compose the spaceship. The final code for drawing it is in the following gist:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50d1ce031d982a8383eed8e464381077/href">https://medium.com/media/50d1ce031d982a8383eed8e464381077/href</a></iframe><p>That&#39;s how it looks like for now, and I&#39;m happy enough to proceed to the next steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*p0jGBQB-39v_UWATs5wGpw.png" /></figure><h3>Update Game State</h3><p>Several state changes will be necessary to create intended behaviours, such as:</p><ul><li>Draw the spaceship;</li><li>Rotate the spaceship;</li><li>Move it forward and backwards;</li><li>Fire shots;</li><li>Render enemies;</li></ul><p><strong>Draw the spaceship</strong></p><p>To render the spaceship, we can use the draw method we just created. All we need is to invoke it on the SpaceshipGame draw method. This is how I call it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b966fb374567833447546d41d2e9af7b/href">https://medium.com/media/b966fb374567833447546d41d2e9af7b/href</a></iframe><p><strong>Rotate the spaceship</strong></p><p>The second intended behaviour is to make the spaceship rotate once the user selects the direction controls (left and right). You can see in the spaceship draw method a parameter for rotation. It will draw the spaceship rotated to the angle that we provide during its call.</p><p>So if the game loop is uninterruptedly calling the spaceship draw method and passing a rotation value, all we need is to read the user input and update the game state for rotating accordingly.</p><p>The following lines are making it happen:</p><pre>ctx.translate(cx, cy);<br>ctx.rotate(this.rotationRadians);<br>ctx.translate(-cx, -cy);</pre><p>You can notice a translation before and after rotation, this is because we want to rotate over the centre of the spaceship. Otherwise, the result will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*P2CbSBe2cOZgquLmggmi6w.gif" /></figure><h3>Read User Input</h3><p>For the actual status of this game, we are interested (for now) in the keyboard events for the arrow keys (and WASD keys as well). So let’s add an eventListener to the constructor:</p><pre>window.addEventListener(&quot;keydown&quot;,this.keyboardListener.bind(this));window.addEventListener(&quot;keyup&quot;, this.keyboardListener.bind(this));</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/064848d12b1b13e37aa618c0295c7488/href">https://medium.com/media/064848d12b1b13e37aa618c0295c7488/href</a></iframe><h4>The code until this stage is tagged at:</h4><p><a href="https://github.com/ateixeira/spaceship-game/releases/tag/part1_final">https://github.com/ateixeira/spaceship-game/releases/tag/part2_final</a></p><h4>The demo for part 2 final code:</h4><p><a href="http://spaceship-part2-final.s3-website.eu-central-1.amazonaws.com/">http://spaceship-part2-final.s3-website.eu-central-1.amazonaws.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf39f584c4be" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-a-space-shooter-game-with-html5-canvas-typescript-part-2-bf39f584c4be">Building a space shooter game with HTML5 canvas &amp; Typescript — Part 2</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a space shooter game with HTML5 canvas & Typescript — Part 1]]></title>
            <link>https://itnext.io/building-a-space-shooter-game-with-html5-canvas-typescript-part-1-20663025c7f5?source=rss-399de1196779------2</link>
            <guid isPermaLink="false">https://medium.com/p/20663025c7f5</guid>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[André Teixeira]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 06:14:30 GMT</pubDate>
            <atom:updated>2020-12-27T10:28:05.074Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a space shooter game with HTML5 canvas &amp; Typescript — Part 1</h3><p>This article is the first part of a series composed by:</p><p><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-1-20663025c7f5">Part 1 - Draw stars</a> ⭐<br><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-2-bf39f584c4be">Part 2 - Draw a spaceship and make it rotate</a> 🚀<br><a href="https://andreteixeira.medium.com/building-a-space-shooter-game-with-html5-canvas-typescript-part-3-f1b2808e85bd">Part 3 - Make the spaceship move and shoot</a> 💨<br>Part 4 - Make a joystick for mobile 🕹️ 📱<br>Part 5 - Enemy ships and collision 💥</p><p>A few months ago, while starting my daily activities I got hooked by an amazing <a href="https://www.google.com/doodles#archive">Google’s Doodle</a>. A very simple game to play, celebrating a cricket tournament somewhere, on which I spent more time than expected.</p><p>Of course, the game was fun, but what I found on developer tools just after the first round was beyond:</p><pre>&lt;canvas width=”1080&quot; height=”608&quot; tabindex=”0&quot;&gt;&lt;/canvas&gt;</pre><p>It was not the first time I saw this tag, but it was the first time I was actually thinking about possible usages for it. Now, years later, I’m going to implement the idea I had that day, revisiting a space shooter game that I implemented at some point during college.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bjC69JzeNRNcnj83" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The project</h3><p>With this exercise, I want to have fun while learning new things. I will explore the possibilities of HTML5 canvas and remember some basic 2D physics concepts that have been on standby for a long time. I will make it using Typescript and will do my best to do it from scratch, avoiding dependencies as much as possible.</p><blockquote>Game source: <a href="https://github.com/ateixeira/spaceship-game">https://github.com/ateixeira/spaceship-game</a><br>Game demo (latest): <a href="http://spaceship.andreteixeira.nl/">https://spaceship.andreteixeira.nl/</a></blockquote><h3><strong>The structure</strong></h3><p>I have set up a typescript base project to get started, which I will not detail here. But I created a tag for the empty base project <a href="https://github.com/ateixeira/spaceship-game/tree/empty_project">commit</a>.</p><p>It has the basic configuration of:</p><ul><li>TypeScript</li><li>Babel</li><li>Webpack</li><li>Webpack dev server</li><li>SASS</li></ul><p>After checking it out, you can install dependencies and start it executing:</p><pre><strong>npm install</strong></pre><pre><strong>npm run serve.</strong></pre><h3><strong>Create the canvas element</strong></h3><p>The first step is to create a canvas element and append it to the document body. I will create a class <strong>SpaceshipGame</strong> and use it as my game shell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/093695952547c5d0da53dbe96d8707b2/href">https://medium.com/media/093695952547c5d0da53dbe96d8707b2/href</a></iframe><p>We also need to import and execute it in our entry point file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c83ddafdb5438e2fc2701954f410bc12/href">https://medium.com/media/c83ddafdb5438e2fc2701954f410bc12/href</a></iframe><h3>The game loop</h3><p>A game loop is a pattern used by most of the games, and it performs at least 3 operations in which we are interested in the current exercise. It runs uninterruptedly during the gameplay, and for each iteration of the loop it:</p><ul><li><strong>parses the user inputs</strong></li><li><strong>updates the state</strong></li><li><strong>(re)draw the scenes</strong></li></ul><h4>Simplest approach</h4><p>The first and simplest loop that comes to mind has the following shape:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/489d2a884e3e6eae94f3a04ae229161b/href">https://medium.com/media/489d2a884e3e6eae94f3a04ae229161b/href</a></iframe><p>A simple while loop that runs until someone makes it stop (let&#39;s say, for instance, by pressing the pause button). But this piece of code brings some problems, i.e.:</p><ol><li>Since JavaScript is single-threaded, loops are blocking operations;</li><li>We don&#39;t have control over the speed of this loop, and it can vary a lot depending on the hardware and how complex the operations you are performing in each step.</li></ol><h4><strong>A better (but still not ideal) approach</strong></h4><p>We can solve the blocking UI problem by wrapping the loop function into a DOM timing event method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac8347b78e0a69a4ed9dc7fd0110aae9/href">https://medium.com/media/ac8347b78e0a69a4ed9dc7fd0110aae9/href</a></iframe><p>This will put some time between game function calls and give the thread space to perform other tasks. But with this approach, we still don&#39;t have total control over the number of loop iterations per second. Given the way the Event Loop works, you may calculate some state changes that will never get drawn.</p><p>It can lead to a cranky animation or a situation where you end up processing too many operations per second. More than the human eye can absorb or greater than the player&#39;s screen refresh rate (usually 60 fps).</p><h4>The way to go</h4><p>So in the JavaScript world, the best approach is to use the event loop as our game loop as well. And we can do it by using <strong>requestAnimationFrame </strong>and let it callback our code to keep the game running.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d1cdd5c81c6d6f88cce6c95af6b366c/href">https://medium.com/media/2d1cdd5c81c6d6f88cce6c95af6b366c/href</a></iframe><h3>Creating the stars ⭐⭐</h3><p>Let&#39;s move forward and start making the game. I&#39;m beginning with setting up the space (shooting will probably be in a next part of this series).</p><p>As a start, I&#39;m happy with several stars randomly distributed across the canvas. We can think about them as points over a plane. My initial idea for it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*e1YTREMfpHcwGM6ysRzgbw.png" /></figure><p>Each star will be an instance of a class with a random (X, Y) position attribute and a draw method to define how it will be presented on the screen (for now, the following snippet shows a simple circle).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2c041be3784b36004ee985c0cef1388/href">https://medium.com/media/d2c041be3784b36004ee985c0cef1388/href</a></iframe><p>You may have noticed that the position attribute, representing the stars, is an instance of the Vector class created by its random static method.</p><blockquote>You may also ask why I&#39;m using a vector representation while I just said the stars could be represented as points over the plane. Well, for the current vision that I have for the implementation, it is enough to represent our points as vectors. It can change later though.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89e198cd12c2acd8f7f17ef9bf77796f/href">https://medium.com/media/89e198cd12c2acd8f7f17ef9bf77796f/href</a></iframe><p>Now we add a config step on the SpaceshipGame class:</p><pre>private config() {<br>  this.stars = [];<br>  const { width, height } = this.canvas;</pre><pre>  for (let i = 0; i &lt; this.STARCOUNT; i++) {<br>    this.stars.push(new Star(width, height));<br>  }<br>}</pre><p>After executing this.config() on the constructor, you can see on your debugger or with a simple console.log that several Stars objects were created with random positions, just as we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*k_nReUKkkqhDH_Tm9qejsQ.png" /></figure><p>Then it is time to iterate over this list of Stars and draw each of them on the canvas. Inside the game draw method, a simple for loop invoking the Star draw method will make them all appear on the canvas (on the random positions calculated by the previous step).</p><pre>for (let star of this.stars) {<br>  Star.draw(star.position.x, star.position.y, this.ctx);<br>}</pre><p>This is how the spaceshipGame file looks like now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c16e92806ff5dcf538981aea652c463/href">https://medium.com/media/4c16e92806ff5dcf538981aea652c463/href</a></iframe><h4>Making the canvas responsive</h4><p>We are still working with the canvas default dimensions of 150 x 300 px. You may have noticed that the app is showing something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*apnXFoYfPITGRxLK3TqZOA.png" /></figure><p>The first step is to change the dimensions attributes during the canvas creation time. Since I want it to fill up the complete screen, setting width and height to window dimensions should be enough:</p><pre>this.canvas.width = window.innerWidth;<br>this.canvas.height = window.innerHeight;</pre><p>But what you can also see is that if we keep it that way, the canvas will remain in the same size/format by resizing the browser window.</p><p>We can introduce a method to check on every draw if the canvas size matches the window&#39;s size. Whenever it changes, we can resize the canvas:</p><pre>resizeCanvasIfNeeded() {<br>  if (<br>    this.canvas.width !== innerWidth ||<br>    this.canvas.height !== innerHeight<br>  ) {<br>    this.canvas.width = innerWidth; // resize this.canvas<br>    this.canvas.height = innerHeight; // also clears this.canvas<br>    this.config();<br>  } else {<br>    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); <br>  }<br>}</pre><h3>Drawing the stars 🤩</h3><p>This game will definitely not be a success with stars represented as circles… To make it look nice, let&#39;s think about how to improve the Star class draw method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*ATb0pObatO9Cr0othPkTnQ.png" /></figure><p>We can draw star shapes by drawing lines (in black) alternately, connecting points (yellow) over an inner (red) and an outer (blue) radius, as represented by the illustration.</p><p>The function will receive the number of vertices and the size we want the stars to have, so we can dynamically choose their shapes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*UzMsSVnHl1CQr-RUaG7Ttw.png" /></figure><blockquote>It is helpful to remember that:</blockquote><blockquote>x(θ) = cos θ<br>y(θ) = sin θ</blockquote><p>Based on the previous images, we can find theta (θ) dividing half of the circumference (<strong><em>π</em></strong>) by the number of vertices we want the star to have. Then we can alternate the drawing of lines using ctx.lineTo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*Z5-XK09rc7bDnPKh5OLnkg.png" /></figure><h4>Example</h4><p>Here we have a 6 vertices star so that theta will be 30° (or <strong><em>π</em></strong>/6).</p><p>Then we can find the initial x and y positions for the next step by looping and incrementing over the complete circumference.</p><p>This is the final function to draw generic shaped stars:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/084da061d88f2d246c8863148a256288/href">https://medium.com/media/084da061d88f2d246c8863148a256288/href</a></iframe><p>And this is the result of our starred space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bc9lj0kMBGP8FEPwD65Sfw.png" /></figure><p><strong>The code until this stage is tagged at: </strong><a href="https://github.com/ateixeira/spaceship-game/releases/tag/part1_final">https://github.com/ateixeira/spaceship-game/releases/tag/part1_final</a></p><p><strong>The demo for part 1 final code:</strong><br><a href="http://spaceship-part1-final.s3-website.eu-central-1.amazonaws.com/">http://spaceship-part1-final.s3-website.eu-central-1.amazonaws.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20663025c7f5" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-a-space-shooter-game-with-html5-canvas-typescript-part-1-20663025c7f5">Building a space shooter game with HTML5 canvas &amp; Typescript — Part 1</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>