<?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 Sacha Morgese on Medium]]></title>
        <description><![CDATA[Stories by Sacha Morgese on Medium]]></description>
        <link>https://medium.com/@sachamorgese?source=rss-6f97aff91890------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nTtf8pjXRsJyn1bn.</url>
            <title>Stories by Sacha Morgese on Medium</title>
            <link>https://medium.com/@sachamorgese?source=rss-6f97aff91890------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:08:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachamorgese/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[HTML5 ゲーム開発 第 1 部]]></title>
            <link>https://medium.com/henngeblog/html5-%E3%82%B2%E3%83%BC%E3%83%A0%E9%96%8B%E7%99%BA-%E7%AC%AC-1-%E9%83%A8-3577c7da0fcf?source=rss-6f97aff91890------2</link>
            <guid isPermaLink="false">https://medium.com/p/3577c7da0fcf</guid>
            <category><![CDATA[hdejp]]></category>
            <category><![CDATA[html5-games]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[hdeknow]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sacha Morgese]]></dc:creator>
            <pubDate>Tue, 23 Oct 2018 04:54:02 GMT</pubDate>
            <atom:updated>2018-10-23T04:54:02.288Z</atom:updated>
            <content:encoded><![CDATA[<p>8月のMTSを用意していた時に勉強になったこと</p><p><strong>校正: </strong><a href="https://medium.com/@doi.t.npdp"><strong>Toshiya Doi</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qGsTWrbp-Wx_Qvu-qtRsg.jpeg" /></figure><p><strong>この投稿について</strong></p><p>ゲームが好きな人は少なくとも一生に一回は「自分のゲームを作って見たい」と思うかもしれない。私は何回も思ったことがある。実を言うと、中学校の頃、親友と一緒に紙でゲームを作るために、数え切れないほどの時間を使っていた。変なキャラクターと可笑しい武器を作ったり、罠を仕掛けたりするのは楽しかった。 高校でプログラミングを勉強することにする理由の一つになった。<br>しかし、2000年代初頭のインターネットは、今とは大分違うものでした。若者だった私はどうゲーム開発を勉強すれば良いのか分からなかったし、率先力もなかったので諦めた。</p><p>数ヶ月前、HTML5 Games: Novice to Ninjaと言う本を貰って、Kindle Fireに入れていたが、2−3ヶ月くらいその本の存在を忘れていた。7月末MTSで発表することになったら思い出してきた。<br>社内にフロントエンドエンジニアが２人しかいないので、JavaScriptが分からなくても楽しめるトピックについて話したいと思っていた。全ての選択肢を検討したら、JSとフロントエンドの経験がある私がHTML5でゲーム開発を行うのは手間あまりかからないかなと思って、やってみた。</p><p>もちろん間違えていた。ゲーム開発はやっぱり難しい。数時間でできると思ったことが数週間かかった。素晴らしいものを作ろうと思っていたが、結局簡単なデモしか発表できなかった。必要な時間と知識を軽く見すぎた。あと、何か勉強したら使う分だけじゃなくて、だいたい全て理解したいタイプだ。普通の人から見たら時間の無駄かもしれないけど、すぐ出発して何回も地図を見るために止まるより、長く準備して旅行中で止まらない方が好き。<br>色々難しかったが、価値がある気がする。まだ分からないことが多いけど、「わかった！」と思える瞬間がたくさんあった。</p><p><strong>基本概念</strong></p><p>ゲーム開発は難しいが、基本概念は割と難しくない。ゲームを作るのはアニメーションと似ている。フレームを次々に描いたら、動いているように見える。もちろん、アニメーションは何回再生しても変わらないが、ゲームはユーザーが操作できるので、何が描かれるのは決まってなくて毎回違う。</p><p>ゲーム開発では、全てのフレームを描く代わりに、コンピューターに何を描いてもらいたいか指示して、ユーサー操作や衝突を検討した後で描いてもらう。だいたい1秒に60回コンピューターがループでユーザー入力を受け取って、全てを少し動かして、衝突判定してフレームを描く。このループの概念は昔のASCIIゲームから現代のゲーム機のAAA作品まで全てに当てはまる。</p><p>現代的なゲーム開発ツール（例：Unity）はめんどくさいタスクをエンジンに任せて、ユーザーをゲームデザインに集中させてくれる。しかし、裏では上で説明したようなことが起こっているので、いざゲームの細部を作り込もうと思うと、やはりこのループの基本概念を理解していなければならない。</p><p>今まで行ったことはどんなゲームにも当てはまるが、HTML5ゲーム開発は？</p><p><strong>HTML5ゲーム開発</strong></p><p>簡単に言うと、HTML5ゲーム開発とはブラウザで実行できるフロントエンドの技術を利用するゲームの開発だ。HTML、CSS、JSを使うことができたら、もうブラウザで実行できる簡単なゲームを作ることができる。しかし、それはずっと前からできる。すごく面白いゲームを作ることができても、HTML5ゲーム開発と言えば、Canvas APIの話になる。</p><p>CanvasはFlashの代わりとしてAppleが開発した使いやすくて力強いAPIだ。CanvasはJavaScriptを通してピクセル一つ一つのグラフィックスを自由に描画できる。２次元グラフィックスでも３次元グラフィックスでも使えるが、このブログで私が経験ある２次元のゲーム開発のみに集中する。</p><p>では、HTML5のメリットは？</p><p>主にはJavaScript。一番流行ってる開発言語の一つなので、コミュニティが大きく、StackOverflowなどでこれだけ多くのサポートを受けられる言語は他にない。ブラウザで実行できるゲームは、アップデートをリリースしたらユーザーがダウンロードせずにすぐに遊べるようになるし、自動的に更新するブラウザはいつも最新のAPIを利用したりできる。また、ブラウザさえあれば、他のツールをインストールしなくても遊べることは素晴らしくない？</p><p><strong>やってみよう！</strong></p><p>では、ゲーム開発の最初の一足として、Canvasの使い方の例を見よう。<br>Canvasはシンプルに描画するためのAPIだが、先ほど言った通りに、次々にフレームを書いたら、動いているように見える。</p><p>まず、四角を描いてみよう。HTML5を作成しよう。Bodyを見たら、boardというクラスを持ってるDIVの中にcanvasタグがある。</p><pre>---------------------------- index.html ----------------------------</pre><pre>&lt;!DOCTYPE <strong>html</strong>&gt;<br>&lt;<strong>html lang=&quot;en&quot;</strong>&gt;<br>&lt;<strong>head</strong>&gt;<br>    &lt;<strong>meta charset=&quot;UTF-8&quot;</strong>&gt;<br>    &lt;<strong>title</strong>&gt;Game&lt;/<strong>title</strong>&gt;<br>    &lt;<strong>style</strong>&gt;<br>        <strong>body </strong>{<br>            <strong>margin</strong>: 30<strong>px auto</strong>;<br>            <strong>text-align</strong>: <strong>center</strong>;<br>            <strong>color</strong>: <strong>#999</strong>;<br>        }<br><br>        <strong>#board canvas </strong>{<br>            <strong>border</strong>: 1<strong>px solid #333</strong>;<br>            <strong>background-color</strong>: <strong>#000</strong>;<br>            <strong>-webkit-box-shadow</strong>: 0<strong>px </strong>0<strong>px </strong>24<strong>px </strong>0<strong>px rgba</strong>(0,0,0,1);<br>            <strong>-moz-box-shadow</strong>: 0<strong>px </strong>0<strong>px </strong>24<strong>px </strong>0<strong>px rgba</strong>(0,0,0,1);<br>            <strong>box-shadow</strong>: 0<strong>px </strong>0<strong>px </strong>24<strong>px </strong>0<strong>px rgba</strong>(0,0,0,1);<br>            <strong>border-radius</strong>: 10<strong>px</strong>;<br>        }<br>    &lt;/<strong>style</strong>&gt;<br>&lt;/<strong>head</strong>&gt;<br>&lt;<strong>body</strong>&gt;<br>&lt;<strong>div id=&quot;board&quot;</strong>&gt;<br>    &lt;<strong>canvas width=&quot;640&quot; height=&quot;480&quot;</strong>&gt;&lt;/<strong>canvas</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>script src=&quot;script.js&quot;</strong>&gt;&lt;/<strong>script</strong>&gt;<br>&lt;/<strong>body</strong>&gt;<br>&lt;/<strong>html</strong>&gt;</pre><p>次はスクリプトファイルを作成しよう。</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>const </strong>canvas = <strong><em>document</em></strong>.querySelector(<strong>&#39;#board canvas&#39;</strong>);<br><strong>const </strong>ctx = canvas.getContext(<strong>&#39;2d&#39;</strong>);<br>console.log(ctx)</pre><p>ブラウザで実行したら、上に作ったcanvasが見える。四角を描画しよう。</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>[...]</strong></pre><pre><strong>const </strong>{ width: w, height: h } = canvas;</pre><pre><strong>let </strong>x = w / 2;<br><strong>let </strong>y = h / 2;</pre><pre>// 色彩を設定<br>ctx.fillStyle = &#39;yellow&#39;</pre><pre>// 四角作成<br>ctx.fillRect(x, y, 50, 50)</pre><p>出た！黄色の四角！なぜ？<br>fillStyleで色彩を設定して、四角を描いた。fillStyleでCSSプロパティ、rgbやhslも使えます。最初の二つめの引数は座標（0, 0は左上の角）、最後の二つめは幅と高さ。座標を変えたら、四角の位置も変わります。最後の二つの引数を変えたらサイズが変わります。</p><p>中央寄せして見よう！</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>[...]</strong></pre><pre><strong>const </strong>{ width: <strong><em>w</em></strong>, height: <strong><em>h </em></strong>} = <strong><em>canvas</em></strong>;<br><br><strong>let <em>rectW </em></strong>= 50; //四角幅<br><strong>let <em>rectH </em></strong>= 50; //四角高さ<br><strong>let <em>x </em></strong>= <strong><em>w </em></strong>/ 2 - <strong><em>rectW </em></strong>/ 2;<br><strong>let <em>y </em></strong>= <strong><em>h </em></strong>/ 2 - <strong><em>rectH </em></strong>/ 2;<br><em>// </em>色彩を設定<em><br></em><strong><em>ctx</em></strong>.<strong>fillStyle </strong>= <strong>&#39;yellow&#39;<br></strong><em>// </em>四角作成<em><br></em><strong><em>ctx</em></strong>.fillRect(<strong><em>x</em></strong>, <strong><em>y</em></strong>, <strong><em>rectW</em></strong>, <strong><em>rectH</em></strong>)</pre><p>まずはcanvasから幅と高さを受け取って、wとh定数に割り当てる。少し計算したら黄色の四角は中央寄せになる。</p><p>もちろん四角だけじゃなく、たくさんの形できるが、四角以外に特別なコマンドはない。他の形はpathを使って描画できるが、この投稿では話さない。なぜかと言うと、pathを使うのは四角よりも複雑なので、説明する時間はあまりない。また、画像とSVGを挿入することもできる。気になったら、MDNのCanvas API ページ を参考にしてください。(tutorialもある)。</p><p><strong>我ループ、故に我あり</strong></p><p>Canvasを使って、描画できるようになったから、ループの番だ。ゲームじゃなければ各フレームのアウトプットを勝手に決めて描画できるが、ゲームを作りたいと思っているのであまり意味がない。ここで必要なのは、１秒に６０回呼ばれる関数を書いて、毎回ユーザーインプットを受け取って、四角の位置を処理して、描画することである。</p><p>どうやってループを作るか？もし、Whileなどを使ったら、ブラウザが固まって何もできないだろう。JSだからSetTimeoutとSetIntervalが使えるが、ゲーム開発の場合には一貫性がない（参考：here）。60fpsを目指す場合、16.7ms毎にフレームを描く必要があるので、一貫性のあるツールをつかわないといけない。運の良いことに、requestAnimationFrameという関数がある。引数として関数を受け取って、次のフレームを呼ぶ。ループじゃなくても、main関数で呼び出したら、ループのように動く。</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>function </strong><em>loop</em>() {<br>  <em>// 次のフレイムでも実行したいからメイン関数でも呼び出す<br>  requestAnimationFrame</em>(<em>loop</em>)<br>  <em>// 見えなくなったら、リセットする<br>  </em><strong>if</strong>(<strong><em>x </em></strong>&gt;= <strong><em>w </em></strong>+ <strong><em>rectW</em></strong>) {<br>    <strong><em>x </em></strong>= 0 - <strong><em>rectW<br>  </em></strong>}<br>  <em>// 各フレイムはxに１を足して、四角が右に１px進む<br>  </em><strong>else </strong>{<br>    <strong><em>x </em></strong>+= 1<br>  }<br>  <em>// </em>色彩を設定<em><br>  </em><strong><em>ctx</em></strong>.fillStyle<strong> </strong>= <strong>&#39;yellow&#39;<br>  </strong><em>// 四角作成<br>  </em><strong><em>ctx</em></strong>.fillRect(<strong><em>x</em></strong>, <strong><em>y</em></strong>, <strong><em>rectW</em></strong>, <strong><em>rectH</em></strong>)<br>}</pre><pre>// 次のフレイムloop関数を呼び出す<br><em>requestAnimationFrame</em>(<em>loop</em>)</pre><p>四角が動いてる！ベーシックなアニメーションを作れた！すごくない？<br>あ、ちょっとまって、動いてるだけじゃなくて、何か跡をつけてる。もちろん！新しいフレイムを描く前、スクリーンを消さないといけない！</p><pre>----------------------------- script.js ----------------------------</pre><pre><em>[...]</em></pre><pre><em>// </em>色彩（黒）を設定<em><br></em><strong><em>  ctx</em></strong>.fillStyle = <strong>&#39;black&#39;<br></strong><em>//</em><strong> </strong>背景を黒に!<br> <em> </em><strong><em>ctx</em></strong>.fillRect(0, 0, w, h)</pre><pre><em>// </em>色彩（黄色）を設定<em><br>  </em><strong><em>ctx</em></strong>.fillStyle<strong> </strong>= <strong>&#39;yellow&#39;</strong></pre><p>いいね！x += で数字を変えたらスピードが上がる！</p><p>ちょっと時間かかったけど何か動いてる。まだ操作できないけど… キーボード操作を作ろう！</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>class </strong>KeyControls {<br>  constructor() {<br>    <em>// 押したキーを保管するオブジェクト<br>    </em><strong>this</strong>.<strong>keys </strong>= {};<br>    // キーを押したら…<em><br>    </em><strong><em>document</em></strong>.addEventListener(<br>      <strong>&#39;keydown&#39;</strong>,<br>      e =&gt; {<br>        <strong>if </strong>([37, 38, 39, 40].indexOf(e.<strong>which</strong>) &gt;= 0) {<br>          <em>// 矢印押したらスクロールしないように<br>          </em>e.preventDefault();<br>        }<br>        <em>// 押したキーをtrueにする<br>        </em><strong>this</strong>.<strong>keys</strong>[e.<strong>which</strong>] = <strong>true</strong>;<br>      },<br>      <strong>false</strong>,<br>    );<br><br>    <strong><em>document</em></strong>.addEventListener(<br>      <strong>&#39;keyup&#39;</strong>,<br>      e =&gt; {<br>        <em>// 話したキーをfalseにする<br>        </em><strong>this</strong>.<strong>keys</strong>[e.<strong>which</strong>] = <strong>false</strong>;<br>      },<br>      <strong>false</strong>,<br>    );<br>  }<br>  <em><br>  // スペース（キー３２）を押したらtrueを返す<br>  </em><strong>get </strong>action() {<br>    <strong>return this</strong>.<strong>keys</strong>[32];<br>  }<br><br>  <strong>get </strong>x() {<br>    <em>// ←、またはAを押されたら −1 返す<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[37] || <strong>this</strong>.<strong>keys</strong>[65]) <strong>return </strong>-1;<br>    <em>// →またはDを押されたら 1 返す<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[39] || <strong>this</strong>.<strong>keys</strong>[68]) <strong>return </strong>1;<br>    <strong>return </strong>0;<br>  }<br><br>  <strong>get </strong>y() {<br>    <em>//  ↑、またはWを押されたら −1 返す<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[38] || <strong>this</strong>.<strong>keys</strong>[87]) <strong>return </strong>-1;<br>        <em>//  ↓、またはSを押されたら −1 返す<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[40] || <strong>this</strong>.<strong>keys</strong>[83]) <strong>return </strong>1;<br>    <strong>return </strong>0;<br>  }<br>}</pre><p>難しく見えるかもしれないが、ただのキーハンドリングするクラスだ。キーを押したら、this.keys.keyCodeがtrueになって、離したらfalseになる。また、xとyのgettersを呼び出したら１か−１を返す。</p><p>script.jsで実行しよう</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>class </strong>KeyControls {<br>[...]<br>}</pre><pre><strong>const <em>controls </em></strong>=　<strong>new </strong>KeyControls<br><br><strong>const <em>canvas </em></strong>= <strong><em>document</em></strong>.querySelector(<strong>&#39;#board canvas&#39;</strong>);<br><strong>const <em>ctx </em></strong>= <strong><em>canvas</em></strong>.getContext(<strong>&#39;2d&#39;</strong>);<br><br><strong>const </strong>{ width: <strong><em>w</em></strong>, height: <strong><em>h </em></strong>} = <strong><em>canvas</em></strong>;<br><br><strong>let <em>rectW </em></strong>= 50;<br><strong>let <em>rectH </em></strong>= 50;<br><strong>let <em>x </em></strong>= <strong><em>w </em></strong>/ 2 - <strong><em>rectW </em></strong>/ 2;<br><strong>let <em>y </em></strong>= <strong><em>h </em></strong>/ 2 - <strong><em>rectH </em></strong>/ 2;<br><strong>let <em>color </em></strong>= 0;<br><br><strong>function </strong><em>loop</em>() {<br>  <em>// 次のフレイムでも実行したいからメイン関数でも呼び出す<br>  requestAnimationFrame</em>(<em>loop</em>)<br>  <strong><em>x </em></strong>+= <strong><em>controls</em></strong>.x;<br>  <strong><em>y </em></strong>+= <strong><em>controls</em></strong>.y;<br>  <br>  <em>// アクションキー（スペース）を押すと色が変わる<br>  </em><strong>if </strong>(<strong><em>controls</em></strong>.action) {<br>    <strong><em>color </em></strong>+= 10;<br>    <strong>if </strong>(<strong><em>color </em></strong>&gt; 360) {<br>      <strong><em>color </em></strong>-= 360;<br>    }<br>  }<br><br>  <em>// 黒を設定して、背景を”消す”<br>  </em><strong><em>ctx</em></strong>.<strong>fillStyle </strong>= <strong>&#39;black&#39;</strong><em><br>  </em><strong><em>ctx</em></strong>.fillRect(0, 0, <strong><em>w</em></strong>, <strong><em>h</em></strong>)<br>  <br>  <em>// HSLで色彩を設定する<br>  </em><strong><em>ctx</em></strong>.<strong>fillStyle </strong>= <strong>`hsl(</strong>${<strong><em>color</em></strong>}<strong>, 50%, 50%)`</strong>;<br>  <strong><em>ctx</em></strong>.fillRect(<strong><em>x</em></strong>, <strong><em>y</em></strong>, 50, 50);<br>}<br><br><em>requestAnimationFrame</em>(<em>loop</em>)</pre><p>やっとできた！四角は中央寄せになってるが、xとyがcontrolsに結び付けられてる。色は０になってるが、スペースを押したら変わる！（参考：CSS property hsl）</p><p>自由に四角を動かすことができるようになった！おめでとう！もちろんゲームと言えないがどんなゲームでもここから始まる！おめでとう！</p><p><strong>最後に</strong></p><p>時間がかかって、作ったものがあまりよくないけど、良いゲームを作ることがこの投稿の目的ではない。第 1 部なので、基本概念を理解してもらえばいいなと思って、一通り全て紹介できたと思う。</p><p>ループとか各フレームを描くなどと聞いて、基本概念を思い出すことができるなら、基本が理解できていると思う。もちろん、まだ扱ってないことの方が多いが、どんなに大きなゲームになってもこの概念は現れる。</p><p>この次のステップとして、webpackのようなモジュールバンドラや、オブジェクト指向開発の説明をしたいけど、第一部の投稿としてはこのあたりで止まって良いと思う。次は画像を挿入したり、シューター向けエンジンの作り方を説明する。</p><p>読んでくれてありがとう！続きを楽しみにして！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3577c7da0fcf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/henngeblog/html5-%E3%82%B2%E3%83%BC%E3%83%A0%E9%96%8B%E7%99%BA-%E7%AC%AC-1-%E9%83%A8-3577c7da0fcf">HTML5 ゲーム開発 第 1 部</a> was originally published in <a href="https://medium.com/henngeblog">henngeblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTML5 Game Development Part 1]]></title>
            <link>https://medium.com/henngeblog/html5-game-development-part-1-c2e8a2e2a2b5?source=rss-6f97aff91890------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e8a2e2a2b5</guid>
            <category><![CDATA[html5-games]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[hdetech]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[hdeknow]]></category>
            <dc:creator><![CDATA[Sacha Morgese]]></dc:creator>
            <pubDate>Mon, 22 Oct 2018 03:06:34 GMT</pubDate>
            <atom:updated>2018-10-22T03:06:34.214Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>HTML 5 Game Development Part 1</strong></h3><h4>What I learned while preparing my presentation for the August MTS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qGsTWrbp-Wx_Qvu-qtRsg.jpeg" /></figure><h4><strong>About this article</strong></h4><p>I think every gamer has thought at least once in his/her life “I want to make my own game!”, and I am no different. As a matter of fact, I would spend countless hours in junior high creating adventure games on paper to play with my best friend during school, and it was a lot of fun. It was fun coming up with ridiculous characters and absurd weapons and it was fun to have my friend fall into my traps and struggle to solve my puzzles (don’t feel bad for him, he would do the exact same thing the next day). It was one of the reasons why I decided to study some programming in high school. However, in the early 2000s, the internet was a different place than today and I lacked both the means and the initiative to start and learn some game programming on my own.</p><p>A few months ago I ended up receiving (legally) a pdf copy of a book called HTML5 Games: Novice to Ninja, put it in my Kindle Fire and kinda forgot about it until I was asked to make a presentation for our Monthly Technical Session ad HDE. Being one of the few front-end developers at the company I was thinking of talking about something that would be entertaining for everyone, not only to people with knowledge of JavaScript. After considering all the options I decided to make a presentation about Game Development in HTML5, thinking that my knowledge of JavaScript and front-end, in general, would allow me to create a working demo in just a few hours of work.</p><p>I was wrong. Of course, I was wrong. Game development is hard.<br>The few hours I thought I needed became a couple week full of reading, learning and wanting to bang my head on the wall and even though I had great ideas for the presentation, in the end, I could only show a working demo taken from the book. A little disappointing, yes, but only because I underestimated the time required to grasp the basics. On top of that, I am the kind of developer who doesn’t like to learn something new focusing only on the parts necessary to complete the task. I really like to understand as deeply as I can the tools that I am using and everything around them. It might sound like a waste of time to many, but I prefer to spend a little more time preparing for the trip instead of having to stop several times to look at the map.</p><p>It was a worthwhile journey, although just a prelude to something much, much bigger, and I had quite a few “EUREKA” moments that I like to think improved my skills as a coder.</p><h4>Fundamentals concepts</h4><p>Game development is hard, but the basics concepts that all games have in common are not hard to understand. Creating a videogame is pretty much like creating an animation on paper. Draw a lot of frames one after another and the human eye will do the magic and give the impression of motion. As simple as that. Of course, there’s a huge difference between an anime, where the outcome is always the same, and a game, where the user input dictates what the next frame will be, but the concept is the same.</p><p>In game development we don’t draw each individual frame, we tell the computer what to do and it draws for us, taking into consideration user input and collisions/changes. And this happens constantly, in a loop that fetches user input, moves everything a little, calculates collisions/changes and then draws the scene, usually 60 times per second. This concept is as true for old indie ASCII games as it is for AAA productions on modern platforms and everything in between.</p><p>A lot of modern tools for game development (Unity is probably the most popular out there) allow the user to focus on creating content offloading some cumbersome tasks to the engine, but what happens when you look under the hood is what I described in the previous paragraph. That means that mastering these concepts is the only way to be able to change each individual part of your product.</p><p>What said so far is generic and true for all kind of games and platforms, what about HTML 5 Game Development then?</p><h4>HTML 5 Game Development</h4><p>To put it simple, HTML 5 Game Development is what we call game development that runs in a browser, that uses the exact same languages and tools of front-end development. By knowing HTML, CSS and JavaScript it is already possible to create simple games able to run on your every platform equipped with a browser. But that has been possible for a long time and, although some pretty addictive games can be created using that technology, to talk about HTML 5 game development is to talk about the canvas API.</p><p>Created by Apple as an alternative to Flash, canvas is a simple yet powerful api that allows to draw graphics via scripting, having control on every single individual pixel. It can be used for both 2D graphics and 3D graphics (through webgl), but in this series of articles I will focus on 2D since it is the only context I have experience with and doesn’t require use to learn to use a completely different language.</p><p>Okay, great but… why HTML 5 then? What are the advantages?</p><p>JavaScript is one of the most popular programming languages in the world (first on GitHub) and that means the community and the support you can receive is unparalleled.<br>Making a game that runs in a browser means that the user doesn’t have to update it, since every time they run it they are automatically using the latest version.<br>And since browser nowadays get updated automatically, that means you can use everything your target browsers support without having to worry about leaving some users behind, since it simply what happen.<br>Also, since it runs in a browser, the users don’t need to install any extra library or tool. Isn’t it great?</p><h4>Let’s get to it!</h4><p>Let’s see how Canvas works with a couple of simple examples, moving our first steps in game development.<br>Canvas is nothing more but a simple way to draw things, but as I said before, animating means to draw one frame after another to give that impression of movement.</p><p>Let’s create a simple square. We’ll start by adding an html file. As you can see it doesn’t contain anything but a canvas nested in a div.</p><pre>---------------------------- index.html ----------------------------</pre><pre>&lt;!DOCTYPE <strong>html</strong>&gt;<br>&lt;<strong>html lang=&quot;en&quot;</strong>&gt;<br>&lt;<strong>head</strong>&gt;<br>    &lt;<strong>meta charset=&quot;UTF-8&quot;</strong>&gt;<br>    &lt;<strong>title</strong>&gt;Game&lt;/<strong>title</strong>&gt;<br>    &lt;<strong>style</strong>&gt;<br>        <strong>body </strong>{<br>            <strong>margin</strong>: 30<strong>px auto</strong>;<br>            <strong>text-align</strong>: <strong>center</strong>;<br>            <strong>color</strong>: <strong>#999</strong>;<br>        }<br><br>        <strong>#board canvas </strong>{<br>            <strong>border</strong>: 1<strong>px solid #333</strong>;<br>            <strong>background-color</strong>: <strong>#000</strong>;<br>            <strong>-webkit-box-shadow</strong>: 0<strong>px </strong>0<strong>px </strong>24<strong>px </strong>0<strong>px rgba</strong>(0,0,0,1);<br>            <strong>-moz-box-shadow</strong>: 0<strong>px </strong>0<strong>px </strong>24<strong>px </strong>0<strong>px rgba</strong>(0,0,0,1);<br>            <strong>box-shadow</strong>: 0<strong>px </strong>0<strong>px </strong>24<strong>px </strong>0<strong>px rgba</strong>(0,0,0,1);<br>            <strong>border-radius</strong>: 10<strong>px</strong>;<br>        }<br>    &lt;/<strong>style</strong>&gt;<br>&lt;/<strong>head</strong>&gt;<br>&lt;<strong>body</strong>&gt;<br>&lt;<strong>div id=&quot;board&quot;</strong>&gt;<br>    &lt;<strong>canvas width=&quot;640&quot; height=&quot;480&quot;</strong>&gt;&lt;/<strong>canvas</strong>&gt;<br>&lt;/<strong>div</strong>&gt;<br>&lt;<strong>script src=&quot;script.js&quot;</strong>&gt;&lt;/<strong>script</strong>&gt;<br>&lt;/<strong>body</strong>&gt;<br>&lt;/<strong>html</strong>&gt;</pre><p>We are going to create the script file next. The first lines of our script.js are the following.</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>const </strong>canvas = <strong><em>document</em></strong>.querySelector(<strong>&#39;#board canvas&#39;</strong>);<br><strong>const </strong>ctx = canvas.getContext(<strong>&#39;2d&#39;</strong>);<br>console.log(ctx)</pre><p>Let’s open our html file in a browser and you can admire your softly styled canvas. Ok, nothing special so far, the fun part starts now. Let’s draw a square!</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>[...]</strong></pre><pre><strong>const </strong>{ width: w, height: h } = canvas;</pre><pre><strong>let </strong>x = w / 2;<br><strong>let </strong>y = h / 2;</pre><pre>// Set the color<br>ctx.fillStyle = &#39;yellow&#39;</pre><pre>// Create the square<br>ctx.fillRect(x, y, 50, 50)</pre><p>And magic! A yellow square appeared. But how?<br>Well, we simply told our canvas to set the color (we can use CSS properties such as rgb and hsl there instead of a simple yellow) and then to fill a rectangle.<br>The numbers we passed as parameters are x and y coordinates (with 0, 0 being the top-left corner), width and height.<br>Want to move the square around? Try to play with the first two numbers. Want to make it bigger or make it a rectangle? Play with the last two.</p><p>Let’s center it now.</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>[...]</strong></pre><pre><strong>const </strong>{ width: <strong><em>w</em></strong>, height: <strong><em>h </em></strong>} = <strong><em>canvas</em></strong>;<br><br><strong>let <em>rectW </em></strong>= 50;<br><strong>let <em>rectH </em></strong>= 50;<br><strong>let <em>x </em></strong>= <strong><em>w </em></strong>/ 2 - <strong><em>rectW </em></strong>/ 2;<br><strong>let <em>y </em></strong>= <strong><em>h </em></strong>/ 2 - <strong><em>rectH </em></strong>/ 2;<br><em>// Set the color<br></em><strong><em>ctx</em></strong>.<strong>fillStyle </strong>= <strong>&#39;yellow&#39;<br></strong><em>// Create the square<br></em><strong><em>ctx</em></strong>.fillRect(<strong><em>x</em></strong>, <strong><em>y</em></strong>, <strong><em>rectW</em></strong>, <strong><em>rectH</em></strong>)</pre><p>In the first line (after getting the context) we are getting the width and height of the current canvas. We are then declaring two variables for the rectangle width and height and two for the coordinates. Our yellow rectangle is now centered. Great job!</p><p>Rectangles aren’t the only shapes we can create using canvas but are the only shapes with a dedicated command. Everything else is drawn using a “path”, but we won’t talk about that in this article for a couple of reasons. First, it is way more complicated than drawing rectangles and this article doesn’t need to be any longer. Second, you can import images and SVGs made using different tools. To learn more check the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas">Canvas API</a> page on <a href="https://developer.mozilla.org/">MDN</a> (or become a pro following the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial">tutorial</a>).</p><h4>I loop, therefore I am</h4><p>As I said before, an animation is nothing more than a series of images drawn one after another. We could draw each single frame one at the time and that would work but would be kinda pointless since we are trying to make games here. What we will do, instead, is creating a function that runs once per frame (60 times per second) and will draw each time the same rectangle but in a slightly different place.</p><p>How do we create a loop though? Using something like a while would lock the entire browser right away. SetTimeout and SetInterval work, but are a little too inconsistent to guarantee a frame each 16.7 seconds (more about those issues <a href="https://humanwhocodes.com/blog/2011/05/03/better-javascript-animations-with-requestanimationframe/">here</a>) and consistency is crucial when it comes to games. Luckily, JavaScript helps us achieve our goal by using a function called <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">requestAnimationFrame</a>. It takes a function as a callback and executes it on the next frame. To make it work as a loop we need to call it in our main function to make it sure it’s executed on the next frame as well.</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>function </strong><em>loop</em>() {<br>  <em>// We need to call requestAnimationFrame again to tell it to run on the next refresh<br>  requestAnimationFrame</em>(<em>loop</em>)<br>  <em>// A simple check to make the square reappears once out of the screen<br>  </em><strong>if</strong>(<strong><em>x </em></strong>&gt;= <strong><em>w </em></strong>+ <strong><em>rectW</em></strong>) {<br>    <strong><em>x </em></strong>= 0 - <strong><em>rectW<br>  </em></strong>}<br>  <em>// Each frame adds 1 to the x coordinate, moving right 1 pixel<br>  </em><strong>else </strong>{<br>    <strong><em>x </em></strong>+= 1<br>  }<br>  <em>// Set the color<br>  </em><strong><em>ctx</em></strong>.fillStyle<strong> </strong>= <strong>&#39;yellow&#39;<br>  </strong><em>// Create the square<br>  </em><strong><em>ctx</em></strong>.fillRect(<strong><em>x</em></strong>, <strong><em>y</em></strong>, <strong><em>rectW</em></strong>, <strong><em>rectH</em></strong>)<br>}</pre><pre>// On the next frame, run our loop function<br><em>requestAnimationFrame</em>(<em>loop</em>)</pre><p>The square is moving! You just created a basic animation, isn’t it great?<br>But wait, it’s not just moving, it looks like it’s leaving a trail. Of course it is! We are leaving what we drew on our previous frame on the screen. Let’s get rid of that by deleting everything on screen.</p><pre>----------------------------- script.js ----------------------------</pre><pre><em>[...]</em></pre><pre><em>// Set the color to black to &#39;clean&#39; the screen<br></em><strong><em>  ctx</em></strong>.fillStyle = <strong>&#39;black&#39;<br></strong><em>//</em><strong> </strong>Paint it black!<br> <em> </em><strong><em>ctx</em></strong>.fillRect(0, 0, w, h)</pre><pre><em>// Set the color<br>  </em><strong><em>ctx</em></strong>.fillStyle<strong> </strong>= <strong>&#39;yellow&#39;</strong></pre><p>Oh, now we’re talking! You can make it go faster by increasing the amount of pixels to add every frame.</p><p>Well, it took us a while but we’re finally able to se something move. It is still far from being interactive. Let’s create some keyboard controls to move our square.</p><p>Since we are working with a single JS file (to make things simple for this post), we will write this on top of everything we wrote before.</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>class </strong>KeyControls {<br>  constructor() {<br>    <em>// Keys will store the keys we are currently pressing<br>    </em><strong>this</strong>.<strong>keys </strong>= {};<br>    <em>// Bind event handlers<br>    </em><strong><em>document</em></strong>.addEventListener(<br>      <strong>&#39;keydown&#39;</strong>,<br>      e =&gt; {<br>        <strong>if </strong>([37, 38, 39, 40].indexOf(e.<strong>which</strong>) &gt;= 0) {<br>          <em>// To avoid scrolling the page with arrows<br>          </em>e.preventDefault();<br>        }<br>        <em>// Set the pressed keys to true<br>        </em><strong>this</strong>.<strong>keys</strong>[e.<strong>which</strong>] = <strong>true</strong>;<br>      },<br>      <strong>false</strong>,<br>    );<br><br>    <strong><em>document</em></strong>.addEventListener(<br>      <strong>&#39;keyup&#39;</strong>,<br>      e =&gt; {<br>        <em>// set the released key to false<br>        </em><strong>this</strong>.<strong>keys</strong>[e.<strong>which</strong>] = <strong>false</strong>;<br>      },<br>      <strong>false</strong>,<br>    );<br>  }<br>  <br><em>  // Return true if the action button (space) is pressed<br>  </em><strong>get </strong>action() {<br>    <strong>return this</strong>.<strong>keys</strong>[32];<br>  }<br><br>  <strong>get </strong>x() {<br>    <em>// Return -1 if left arrow or A key are pressed<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[37] || <strong>this</strong>.<strong>keys</strong>[65]) <strong>return </strong>-1;<br>    <em>// Return 1 if right arrow or D key are pressed<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[39] || <strong>this</strong>.<strong>keys</strong>[68]) <strong>return </strong>1;<br>    <strong>return </strong>0;<br>  }<br><br>  <strong>get </strong>y() {<br>    <em>//  Return -1 if up arrow or W key are pressed<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[38] || <strong>this</strong>.<strong>keys</strong>[87]) <strong>return </strong>-1;<br>    <em>// Return 1 if down arrow or S key are pressed<br>    </em><strong>if </strong>(<strong>this</strong>.<strong>keys</strong>[40] || <strong>this</strong>.<strong>keys</strong>[83]) <strong>return </strong>1;<br>    <strong>return </strong>0;<br>  }<br>}</pre><p>It might look complicated at first, but by checking the code you can see it doesn’t do anything but taking every key we press and setting it to true inside the keys object and setting it to false the moment we release it.</p><p>In addition, it returns +1 or -1 for the x and y getters, depending on the button pressed.</p><p>Let’s see it in action.</p><pre>----------------------------- script.js ----------------------------</pre><pre><strong>class </strong>KeyControls {<br>[...]<br>}</pre><pre><strong>const <em>controls </em></strong>=　<strong>new </strong>KeyControls<br><br><strong>const <em>canvas </em></strong>= <strong><em>document</em></strong>.querySelector(<strong>&#39;#board canvas&#39;</strong>);<br><strong>const <em>ctx </em></strong>= <strong><em>canvas</em></strong>.getContext(<strong>&#39;2d&#39;</strong>);<br><br><strong>const </strong>{ width: <strong><em>w</em></strong>, height: <strong><em>h </em></strong>} = <strong><em>canvas</em></strong>;<br><br><strong>let <em>rectW </em></strong>= 50;<br><strong>let <em>rectH </em></strong>= 50;<br><strong>let <em>x </em></strong>= <strong><em>w </em></strong>/ 2 - <strong><em>rectW </em></strong>/ 2;<br><strong>let <em>y </em></strong>= <strong><em>h </em></strong>/ 2 - <strong><em>rectH </em></strong>/ 2;<br><strong>let <em>color </em></strong>= 0;<br><br><strong>function </strong><em>loop</em>() {<br>  <em>// We need to call requestAnimationFrame again to tell it to run on the next refresh<br>  requestAnimationFrame</em>(<em>loop</em>)<br>  <strong><em>x </em></strong>+= <strong><em>controls</em></strong>.x;<br>  <strong><em>y </em></strong>+= <strong><em>controls</em></strong>.y;<br>  <br>  <em>// We will be able to change the color with the action button<br>  </em><strong>if </strong>(<strong><em>controls</em></strong>.action) {<br>    <strong><em>color </em></strong>+= 10;<br>    <strong>if </strong>(<strong><em>color </em></strong>&gt; 360) {<br>      <strong><em>color </em></strong>-= 360;<br>    }<br>  }<br><br>  <em>// Set the color to black to &#39;clean&#39; the screen<br>  </em><strong><em>ctx</em></strong>.<strong>fillStyle </strong>= <strong>&#39;black&#39;<br>  </strong><em>// Paint it black!<br>  </em><strong><em>ctx</em></strong>.fillRect(0, 0, <strong><em>w</em></strong>, <strong><em>h</em></strong>)<br>  <br>  <em>// Set the color using hsl (hue, saturation, lightness)<br>  </em><strong><em>ctx</em></strong>.<strong>fillStyle </strong>= <strong>`hsl(</strong>${<strong><em>color</em></strong>}<strong>, 50%, 50%)`</strong>;<br>  <strong><em>ctx</em></strong>.fillRect(<strong><em>x</em></strong>, <strong><em>y</em></strong>, 50, 50);<br>}<br><br><em>requestAnimationFrame</em>(<em>loop</em>)</pre><p>In this last version of our script file we are ready to go. The x and y values are centered at first but now are bound to the controls file. The color is set to 0 but can be changed by pressing the action button (check out to the <a href="https://www.w3schools.com/colors/colors_hsl.asp">CSS property hsl</a> to know more).</p><p>You can now move the square around freely. Congratulations, you have created the most basic form of video game. It lacks everything you need to make it good, it’s not fun, it’s not pretty and it has no goal, but it’s where everything begins. And you made it by just writing a few lines of code. Congratulations!</p><h4>Conclusion</h4><p>It took a while to get here and what we have isn’t that great, but the purpose of this article wasn’t to make a good game. Since it’s part 1 of what will hopefully be a series of articles, I just wanted you to understand the fundamentals and I think we covered them all.</p><p>You should now be familiar with the concept of loop, with drawing each single frame to give the impression of animation and implementing controls. There’s a lot more to learn (we haven’t even touched collisions) but trust me when I say these are basic concepts that you will find in pretty much every single game out there.</p><p>I think it’s a good point to stop since everything that comes after is way too complicated to be done without using any module bundler and involves a lot of object oriented programming. I will do my best to explain how to import images and create a simple engine for a simple shooter next time.</p><p>Thanks for reading and stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e8a2e2a2b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/henngeblog/html5-game-development-part-1-c2e8a2e2a2b5">HTML5 Game Development Part 1</a> was originally published in <a href="https://medium.com/henngeblog">henngeblog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>