You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
koehr.ing/dist/blog/2019-05-03-freddy-vs-json.html

675 lines
42 KiB
HTML

4 months ago
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="utf-8">
4 months ago
<base href="https://koehr.ing/">
4 months ago
<title>Weblog aka Blog // the codeartist — programmer and engineer based in Berlin</title>
<meta name="description" content="Homepage, Portfolio and CV of Norman Köhring" />
<meta content="The personal page and weblog of Norman Köhring" name=description>
<meta content="Norman Köhring" name=author>
<meta content="the codeartist — programmer and engineer based in Berlin" name=DC.title>
<meta content="52.4595, 13.5335" name=ICBM>
<meta content="52.4595; 13.5335" name=geo.position>
<meta content=DE-BE name=geo.region>
<meta content=Berlin name=geo.placename>
<meta content="width=device-width,initial-scale=1.0" name=viewport>
<link href=https://koehr.in rel=author>
<link href=https://koehr.in rel=canonical>
<link href=https://k0r.in rel=alternate>
<link href=https://koehr.ing rel=me>
<link href=@Koehr@mstdn.io rel=me>
<link href=https://sr.ht/~koehr/ rel=me>
<link href=https://git.k0r.in rel=me>
<link href=https://threads.net/@coffee_n_code rel=me>
<link href=https://instagram.com/@coffee_n_code rel=me>
<link href=https://ko-fi.com/koehr rel=me>
<link href=https://reddit.com/user/koehr rel=me>
<link href=https://koehr.in/rss.xml rel=alternate title=RSS type=application/rss+xml>
<link href=/favicon.png rel=icon type=image/x-icon>
<link href=/style.css rel=stylesheet>
</head>
<body>
<main id="til" class="posts">
<header>
<h1>Weblog</h1>
</header>
<h1>Freddy vs JSON: how to make a top-down shooter</h1>
<p><em>Written 2019-05-03</em></p>
<p>I will tell you how I created a simple top-down shooter in JavaScript without using any additional libraries. But this article is not replicating the full game but instead tries to show which steps to take to start writing a game from scratch.</p>
<!--more-->
<p>A couple of years ago (Oh it's almost a decade! Am I that old already?), when the Canvas API got widely adopted by most browsers, I started experimenting with it. The fascination was high and I immediately tried to use it for interactive toys and games.</p>
<p>Of course, the games I made (and make) are usually not very sophisticated. That is mainly because I create them only for fun and without much eye-candy or even sound. What really fascinates me is the underlying mechanics. Otherwise, I could just use one of those <a href="https://github.com/collections/javascript-game-engines">awesome game engines</a>, that exist already.</p>
<p>To share some of the fun, I created a tiny top down shooter for a tech session in my company (<a href="https://wunder.dog">we're hiring, btw</a>). The <a href="https://github.com/nkoehring/FreddyvsJSON">result can be found on Github</a>. I commented the code well so it should be quite helpful to just read it. But if you want to know how I created the game step-by-step, this article is for you.</p>
<h2>The Game</h2>
<p>To give you an impression of what I created:</p>
<p><img src="https://github.com/nkoehring/FreddyvsJSON/raw/master/screenshot.jpg" alt="screenshot"></p>
<p>The little gray box is your ship. You are controlling the little gray box with either WASD or Arrow keys and you can shoot tiny yellow boxes at your enemies — the red boxes — by pressing Space or Enter. The enemies shoot back though. They don't really aim well, but at some point they'll flood the screen with tiny red boxes. If they hit you, they hurt. Every time you get hurt you shrink, until you completely disappear. The same happens with your opponents.</p>
<h2>Preconditions</h2>
<p>This post is not about the game itself but about the underlying mechanics and some of the tricks used to make it work. My intention is to provide an entry for understanding more complex game development for people with some existing programming experience. The following things are helpful to fully understand everything:</p>
<h3>Fundamental Game Engine Mechanics</h3>
<p>Most — if not all — game engines have the same fundamental building blocks:</p>
<ul>
<li>The <code>state</code>, that defines the current situation (like main menu, game running, game lost, game won, etc).</li>
<li>A place to store all the objects and related data.</li>
<li>The <code>main loop</code>, usually running sixty times per second, that reads the object information, draws the screen and applies updates to object data</li>
<li>An <code>event handler</code> that maps key presses, mouse movements and clicks to data changes.</li>
</ul>
<h3>The Canvas Element</h3>
<p>The Canvas element allows you to handle pixel based data directly inside the browser. It gives you a few functions to draw primitives. It is easy to draw, for example, a blue rectangle but you need more than one action to draw a triangle; to draw a circle you need to know how to use arcs.</p>
<p>Exactly because drawing rectangles is the easiest and fastest thing to do with the Canvas API, I used them for everything in Freddy vs JSON. That keeps the complexities of drawing more exciting patterns or graphics away and helps focus on the actual game mechanics. This means, after initializing the canvas besides setting colors we only use two functions:</p>
<pre><code class="language-js">const ctx = canvas.getContext('2d') // this is the graphics context
ctx.fillStyle = '#123456' // use color #123456
ctx.fillText(text, x, y) // write 'text' at coords x, y
ctx.fillRect(x, y, width, height) // draw filled rectangle
</code></pre>
<h2>Step One: Some HTML and an initialized Canvas</h2>
<p>Because the code is going to run in the browser, some HTML is necessary. A minimal set would be just the following two lines:</p>
<pre><code class="language-html">&lt;canvas id=&quot;canvas&quot; /&gt;
&lt;script src=&quot;./app.js&quot;&gt;&lt;/script&gt;
</code></pre>
<p>This works but of course some styling would be great. And maybe having a title? Check out a <a href="https://github.com/nkoehring/FreddyvsJSON/blob/master/index.html">complete version on Github</a>.</p>
<p>Initializing a Canvas is also pretty simple. Inside <code>app.js</code> following lines are necessary:</p>
<pre><code class="language-js">const canvas = document.getElementById('canvas')
// you can set height and width in HTML, too
canvas.width = 960
canvas.height = 540
const ctx = canvas.getContext('2d')
</code></pre>
<p>I chose rather arbitrary values for width and height. Feel free to change them to your liking. Just know that higher values obviously will result in more work for your computer.</p>
<h2>Step Two: Game Mode / States</h2>
<p>To avoid creating a <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud">big ball of mud</a> it is common to use a <a href="https://en.wikipedia.org/wiki/Finite-state_machine">state machine</a>. The idea is to describe the high level states and their valid transitions and using a central state handler to control them.</p>
<p>There libraries that help with state machines, but it is also not too hard to create this yourself. In the game I created I used a very simple state machine implementation: The possible states and their transitions are described in <a href="https://en.wikipedia.org/wiki/Enumerated_type">Enum-like objects</a>. Here some code to illustrate the idea. The code uses some rather new language features: <a href="https://developer.mozilla.org/en-US/docs/Glossary/Symbol">Symbols</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names">Computed Property Names</a>.</p>
<pre><code class="language-js">const STATE = {
start: Symbol('start'), // the welcome screen
game: Symbol('game'), // the actual game
pause: Symbol('pause'), // paused game
end: Symbol('end') // after losing the game
}
const STATE_TRANSITION = {
[STATE.start]: STATE.game, // Welcome screen =&gt; Game
[STATE.game]: STATE.pause, // Game =&gt; Pause
[STATE.pause]: STATE.game, // Pause =&gt; Game
[STATE.end]: STATE.start // End screen =&gt; Welcome screen
}
</code></pre>
<p>This is not a full state machine but does the job. For the sake of simplicity I violate the state machine in one occasion though: There is no transition from the running game to the end of the game. This means I have to jump directly, without using the state handler, to the end screen after the player dies. But this saved me from a lot of complexity. Now the state control logic is effectively only one line:</p>
<pre><code class="language-js">newState = STATE_TRANSITION[currentState]
</code></pre>
<p>Freddy vs JSON uses this in the click handler. A click into the canvas changes the state from welcome screen to the actual game, pauses and un-pauses the game and brings you back to the welcome screen after losing. All that in only one line. The new state is set to a variable that is respected by the central update loop. More on that later.</p>
<p>Of course much more could be done with a state. For example weapon or ship upgrades could be realised. The game could transition towards higher difficulty levels and get special game states like an upgrade shop or transfer animations between stages. Your imagination is the limit. And the amount of lines in your state handler, I guess.</p>
<h2>Step Three: Data Handling</h2>
<p>Games usually have to handle a lot of information. Some examples are the position and health of the player, the position and health of each enemy, the position of each single bullet that is currently flying around and the amount of hits the player landed so far.</p>
<p>JavaScript allows different ways to handle this. Of course, the state could just be global. But we all (should) know that global variables are the root of all evil. Global constants are okay because they stay predictable. Just don't use global variables. If you're still not convinced, please read this <a href="https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil">entry on stackexchange</a>.</p>
<p>Instead of global variables, you can put everything into the same scope. A simple example is shown next. The following code examples use template literals, a new language feature. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">Learn more about template literals here</a>.</p>
<pre><code class="language-js">function Game (canvas) { // the scope
const ctx = canvas.getContext('2d')
const playerMaxHealth = 10
let playerHealth = 10
function handleThings () {
ctx.fillText(`HP: ${playerHealth} / ${playerMaxHealth}`, 10, 10)
}
}
</code></pre>
<p>This is nice because you have easy access just like with global variables without actually using global variables. It still opens the door to potential problems if you only have one big scope for everything, but the first game is probably small enough to get away with not thinking about this too much.</p>
<p>Another way is to use classes:</p>
<pre><code class="language-js">class Game {
constructor (canvas) {
this.ctx = canvas.getContext('2d')
this.playerMaxHealth = 10
this.playerHealth = 10
}
handleThings () {
const max = this.playerMaxHealth
const hp = this.playerHealth
ctx.fillText(`HP: ${hp} / ${max}`, 10, 10)
}
}
</code></pre>
<p>That looks like a bit more boilerplate but classes are good to encapsulate common functionality. They get even better if your game grows and you want to stay sane. But in JavaScript they are just syntactical sugar. Everything can be achieved with functions and function scopes. So it is up to you, what you use. The two last code examples are essentially the same thing.</p>
<p>Now that we decided on how to save all the data (Freddy vs JSON uses a class so I'll use classes here too) we can further structure it... or not. Freddy vs JSON saves everything flat. That means for example that each player attribute gets its own variable instead of using a player object that contains a lot of properties. The latter is probably more readable so you might want to go this path. Object access is also pretty fast nowadays so there is probably not a noticeable difference if you write <code>this.player.health</code> instead of <code>this.playerHealth</code>. If you are really serious about performance though, you might want to investigate this topic further. You can check out my <a href="https://jsperf.com/nested-and-flat-property-access/1">jsperf experiment</a> for a start.</p>
<p>Data manipulation happens in the update loop or when handling events. The next steps explain these topics further.</p>
<h2>Step Four: The Main Loop</h2>
<p>If event based changes are enough, like on a website, a separate loop wouldn't be necessary. The user clicks somewhere, which triggers an event that updates something and eventually re-renders a part of the page. But in a game some things happen without direct user interaction. Enemies come into the scene and shoot at you, there might be some background animation, music plays, and so on. To make all this possible a game needs an endlessly running loop which repeatedly calls a function that checks and updates the status of everything. And to make things awesomely smooth it should call this function in a consistent interval — at least thirty, better sixty times per second.</p>
<p>The following code examples use another rather new language feature called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow Functions</a>.</p>
<p>Typical approaches to run a function in an regular interval would include the usage of <code>setInterval</code>:</p>
<pre><code class="language-js">let someValue = 23
setInterval(() =&gt; {
someValue++
}, 16)
</code></pre>
<p>Or <code>setTimeout</code></p>
<pre><code class="language-js">let someValue = 42
function update () {
someValue++
setTimeout(update, 16)
}
update()
</code></pre>
<p>The first version just runs the function endlessly every sixteen milliseconds (which makes sixty-two and a half times per second), regardless of the time the function itself needs or if is done already. The second version does its potentially long running job before it sets a timer to start itself again after sixteen milliseconds.</p>
<p>The first version is especially problematic. If a single run needs more than sixteen milliseconds, it runs another time before the first run finished, which might lead to a lot of fun, but not necessarily to any useful result. The second version is clearly better here because it only sets the next timeout after doing everything else. But there is still a problem: Independent of the time the function needs to run it will wait an additional sixteen milliseconds to run the function again.</p>
<p>To mitigate this, the function needs to know how long it took to do its job and then substract that value from the waiting time:</p>
<pre><code class="language-js">let lastRun
let someValue = 42
function update () {
someValue++
const duration = Date.now() - lastRun
const time = duration &gt; 16 ? 0 : 16 - time
setTimeout(update, time)
lastRun = Date.now()
}
lastRun = Date.now()
update()
</code></pre>
<p><code>Date.now()</code> returns the current time in milliseconds. With this information we can figure out how much time has passed since the last run. If more than sixteen milliseconds have passed since then just start the update immediately and crush that poor computer (or better slow down the execution time and be nice to the computer), otherwise wait as long as necessary to stay at around sixty runs per second.</p>
<p>Please note that Date.now() is not the best way to measure performance. To learn more about performance and high resolution time measurement, check out: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance">https://developer.mozilla.org/en-US/docs/Web/API/Performance</a></p>
<p>Cool. This way you can also slow everything down to a chill thirty frames per second by setting the interval to thirty-three milliseconds. But lets not go that path. Lets do what the cool kids with their shiny new browsers do. Lets use <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">requestAnimationFrame</a>.</p>
<p><code>requestAnimationFrame</code> takes your update function as an argument and will call it right before the next repaint. It also gives you the timestamp of the last call, so that you don't have to ask for another one, which potentially impacts your performance. Lets get down to the details:</p>
<pre><code class="language-js">function update () {
/* do some heavy calculations */
requestAnimationFrame(update)
}
update()
</code></pre>
<p>This is the simplest version. It runs your update function as close as possible to the next repaint. This means it usually runs sixty times per second, but the rate might be different depending on the screen refresh rate of the computer it runs on. If your function takes longer than the duration between screen refreshes, it will simply skip some repaints because it is not asking for a repaint before it is finished. This way it will always stay in line with the refresh rate.</p>
<p>A function that does a lot of stuff might not need to run that often. Thirty times per second is usually enough to make things appear smooth and some other calculations might not be necessary every time. This brings us back to the timed function we had before. In this version we use the timestamp that <code>requestAnimationFrame</code> is giving us when calling our function:</p>
<pre><code class="language-js">let lastRun
function update (stamp) {
/* heavy work here */
lastRun = stamp
// maybe 30fps are enough so the code has 33ms to do its work
if (stamp - lastRun &gt;= 33) {
requestAnimationFrame(update)
}
}
// makes sure the function gets a timestamp
requestAnimationFrame(update)
</code></pre>
<h2>Step Five: Event Handling</h2>
<p>People usually want to feel like they are in control of what they are doing. This brings us to a point where the game needs to handle input from the user. Input can be either a mouse movement, a mouse click or a key press. Key presses are also separated into pressing and releasing the key. I'll explain why later in this section.</p>
<p>If your game is the only thing running on that page (and it deserves that much attention, doesn't it?) input events can simply be bound to <code>document</code>. Otherwise they need to be bound to the canvas event directly. The latter can be more complicated with key events because key events work best with actual input fields. This means you need to insert one into the page, and make sure it stays focused so that it gets the events. Each click into the canvas would make it lose focus. To avoid that, you can use the following hack:</p>
<pre><code class="language-js">inputElement.onblur = () =&gt; inputElement.focus()
</code></pre>
<p>Or you simply put everything to its own page and bind the event listeners to <code>document</code>. It makes your life much easier.</p>
<p>Side note: People might wonder why I don't use addEventListener. Please use it if it makes you feel better. I don't use it here for simplicity reasons and it will not be a problem as long as each element has exactly one event listener for each event type.</p>
<h3>Mouse Movement</h3>
<p>Mouse movements are not really used in Freddy vs JSON but this post wouldn't be complete without explaining them. So this is how you do it:</p>
<pre><code class="language-js">canvas.onmousemove = mouseMoveEvent =&gt; {
doSomethingWithThat(mouseMoveEvent)
}
</code></pre>
<p>This will be executed on every little movement of the mouse as long as it is on top of the canvas. Usually you want to <a href="https://davidwalsh.name/javascript-debounce-function">debounce</a> that event handler because the event might fire at crazy rates. Another way would be to use it only for something very simple, like to save the mouse coordinates. That information can be used in a function that is not tied to the event firing, like our update function:</p>
<pre><code class="language-js">class Game {
constructor (canvas) {
// don't forget to set canvas width and height,
// if you don't do it, it will set to rather
// small default values
this.ctx = canvas.getContext('2d')
this.mouseX = 0
this.mouseY = 0
// gets called at every little mouse movement
canvas.onmousemove = event =&gt; {
this.mouseX = event.offsetX
this.mouseY = event.offsetY
}
this.update()
}
// gets called at each repaint
update () {
requestAnimationFrame(() =&gt; this.update())
this.fillRect('green', this.mouseX, this.mouseY, 2, 2)
}
}
</code></pre>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent">MouseEvent object</a> contains a lot more useful information. I suggest you to check out the link and read about it.</p>
<p>This should draw two pixel wide boxes wherever you touch the canvas with your mouse. Yeah, a drawing program in ten lines! Photoshop, we're coming for you!</p>
<h3>Mouse Clicks</h3>
<p>But lets get back to reality. Mouse clicks are another important interaction:</p>
<pre><code class="language-js">canvas.onclick = mouseClickEvent =&gt; {
doSomethingWithThat(mouseClickEvent)
}
</code></pre>
<p>The event object again contains all kind of useful information. It is the same type of object that you get from mouse movement. Makes life simpler, doesn't it?</p>
<p>Now to make use of the mouse clicks, lets adapt the former code example:</p>
<pre><code class="language-js">class Game {
constructor (canvas) {
// set canvas.width and canvas.height here
this.ctx = canvas.getContext('2d')
this.mouseX = 0
this.mouseY = 0
this.drawing = false
canvas.onmousemove = event =&gt; {
this.mouseX = event.offsetX
this.mouseY = event.offsetY
}
canvas.onmousedown = () =&gt; {
this.drawing = true
}
canvas.onmouseup = () =&gt; {
this.drawing = false
}
this.update()
}
update () {
requestAnimationFrame(() =&gt; this.update())
if (this.drawing) {
this.fillRect('green', this.mouseX, this.mouseY, 2, 2)
}
}
}
</code></pre>
<p><a href="https://codesandbox.io/s/3qw6q7j535">Check it out on CodeSandbox</a></p>
<p>Now the boxes are only drawn while holding down the mouse button. Boom, one step closer to the ease of use of Photoshop! It is incredible, what you can do with it already. Just check out this incredible piece of art:</p>
<p><img src="https://github.com/nkoehring/FreddyvsJSON/raw/master/blogpost/drawing.jpg" alt="incredible piece of art"></p>
<h3>Key Events</h3>
<p>The last important input comes from key presses. Okay, it is not really the last input type. Other ones would come from joysticks or gamepads. But there are some old-school people like me who still prefer using the keyboard to navigate their space ship.</p>
<p>Input handling is theoretically simple but in practice it is everything but. That's why this section explains not only how key events work but also how to get them right. Look forward to event handling, the relationship between velocity and acceleration, and frame rate agnostic timing...</p>
<p>The simplest version of key event handling looks like this:</p>
<pre><code class="language-js">document.onkeypress = keyPressEvent =&gt; {
doSomethingWithThat(keyPressEvent)
}
</code></pre>
<p>But <code>keypress</code> is deprecated and should not be used. It is anyways better to separate the <code>keyPress</code> into two events: <code>KeyDown</code> and <code>KeyUp</code> and I'll explain why.</p>
<p>For now imagine you have that awesome space ship in the middle of the screen and want to make it fly to the right if the user presses <code>d</code> or <code>ArrowRight</code>:</p>
<pre><code class="language-js">class Game {
constructor(canvas, width, height) {
// we'll need those values
this.width = canvas.width = width;
this.height = canvas.height = height;
this.ctx = canvas.getContext(&quot;2d&quot;);
this.shipSize = 10;
this.shipHalf = this.shipSize / 2.0; // you'll need that a lot
// position the ship in the center of the canvas
this.shipX = width / 2.0 - this.shipHalf;
this.shipY = height / 2.0 - this.shipHalf;
// event is a KeyboardEvent:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
document.onkeypress = event =&gt; {
const key = event.key;
if (key === &quot;d&quot; || key === &quot;ArrowRight&quot;) {
this.shipX++;
}
};
this.update();
}
// convenience matters
rect(color, x, y, w, h) {
this.ctx.fillStyle = color;
this.ctx.fillRect(x, y, w, h);
}
update() {
// clean the canvas
this.rect(&quot;black&quot;, 0, 0, this.width, this.height);
// get everything we need to draw the ship
const size = this.shipSize;
const x = this.shipX - this.shipHalf;
const y = this.shipY - this.shipHalf;
// draw the ship
this.rect(&quot;green&quot;, x, y, size, size);
// redraw as fast as it makes sense
requestAnimationFrame(() =&gt; this.update());
}
}
</code></pre>
<p><a href="https://codesandbox.io/s/2w10vo897n">check it out on CodeSandbox</a></p>
<p>Okay, that is kinda working, at least if you press <code>d</code>. But the arrow key is somehow not working and the ship's movement feels a bit jumpy. That doesn't seem to be optimal.</p>
<p>The problem is that we're relying on repeated key events. If you press and hold a key, the <code>keypress</code> event is repeated a couple of times per second, depending on how you set your key repeat rate. There is no way to use that for a smooth movement because we can not find out how fast the users keys are repeating. Sure, we could try to measure the repeat rate, hoping the user holds the key long enough. But let's try to be smarter than that.</p>
<p>Lets recap: We hold the key, the ship moves. We leave the key, the movement stops. That is what we want. What a happy coincidence that these two events have ...erm.. events:</p>
<pre><code class="language-js">class Game {
constructor(canvas, width, height) {
// we'll need those values
this.width = canvas.width = width;
this.height = canvas.height = height;
this.ctx = canvas.getContext(&quot;2d&quot;);
this.shipSize = 10;
this.shipHalf = this.shipSize / 2.0; // you'll need that a lot
// position the ship in the center of the canvas
this.shipX = width / 2.0 - this.shipHalf;
this.shipY = height / 2.0 - this.shipHalf;
this.shipMoves = false;
// key is pressed down
document.onkeydown = event =&gt; {
const key = event.key;
switch (key) {
case &quot;d&quot;:
case &quot;ArrowRight&quot;:
this.shipMoves = &quot;right&quot;;
break;
case &quot;a&quot;:
case &quot;ArrowLeft&quot;:
this.shipMoves = &quot;left&quot;;
break;
case &quot;w&quot;:
case &quot;ArrowUp&quot;:
this.shipMoves = &quot;up&quot;;
break;
case &quot;s&quot;:
case &quot;ArrowDown&quot;:
this.shipMoves = &quot;down&quot;;
break;
}
};
document.onkeyup = () =&gt; {
this.shipMoves = false;
};
this.update();
}
// convenience matters
rect(color, x, y, w, h) {
this.ctx.fillStyle = color;
this.ctx.fillRect(x, y, w, h);
}
update() {
// move the ship
if (this.shipMoves) {
if (this.shipMoves === &quot;right&quot;) this.shipX++;
else if (this.shipMoves === &quot;left&quot;) this.shipX--;
else if (this.shipMoves === &quot;up&quot;) this.shipY--;
else if (this.shipMoves === &quot;down&quot;) this.shipY++;
}
// clean the canvas
this.rect(&quot;black&quot;, 0, 0, this.width, this.height);
// get everything we need to draw the ship
const size = this.shipSize;
const x = this.shipX - this.shipHalf;
const y = this.shipY - this.shipHalf;
// draw the ship
this.rect(&quot;green&quot;, x, y, size, size);
// redraw as fast as it makes sense
requestAnimationFrame(() =&gt; this.update());
}
}
</code></pre>
<p><a href="https://codesandbox.io/s/nr8r6myz60">check it out on CodeSandbox</a></p>
<p>I felt like adding all directions right away. Now the movement itself is decoupled from the key events. Instead of changing the coordinates directly on each event, a value is set to a movement direction and the main loop takes care of adapting the coordinates. That's great because we don't care about any key repeat rates anymore.</p>
<p>But there are still some problems here. First of all, the ship can only move in one direction at a time. Instead it should always be able to move in two directions at a time, like up- and leftwards. Then the movement stops if the switch from one key to another is too fast. That might happen in a heated situation between your ship and the enemies bullets. Also the movement is bound to the frame rate. If the frame rate drops or the screen refreshes on a different rate on the players computer, your ship becomes slower or faster. And last but not least the ship simply jumps to full speed and back to zero. For a more natural feeling it should instead accelerate and decelerate.</p>
<p>Lots of work. Lets tackle the problems one by one:</p>
<p>Bidirectional movements are easy to do. We just need a second variable. And to simplify things even more, we can set these variables to numbers instead of identifying strings. Here you see why:</p>
<pre><code class="language-js">class Game {
constructor(canvas, width, height) {
/* ... same as before ... */
this.shipMovesHorizontal = 0;
this.shipMovesVertical = 0;
// this time, the values are either positive or negative
// depending on the movement direction
document.onkeydown = event =&gt; {
const key = event.key;
switch (key) {
case &quot;d&quot;:
case &quot;ArrowRight&quot;:
this.shipMovesHorizontal = 1;
break;
case &quot;a&quot;:
case &quot;ArrowLeft&quot;:
this.shipMovesHorizontal = -1;
break;
case &quot;w&quot;:
case &quot;ArrowUp&quot;:
this.shipMovesVertical = -1;
break;
case &quot;s&quot;:
case &quot;ArrowDown&quot;:
this.shipMovesVertical = 1;
break;
}
};
// to make this work, we need to reset movement
// but this time depending on the keys
document.onkeyup = event =&gt; {
const key = event.key;
switch (key) {
case &quot;d&quot;:
case &quot;ArrowRight&quot;:
case &quot;a&quot;:
case &quot;ArrowLeft&quot;:
this.shipMovesHorizontal = 0;
break;
case &quot;w&quot;:
case &quot;ArrowUp&quot;:
case &quot;s&quot;:
case &quot;ArrowDown&quot;:
this.shipMovesVertical = 0;
break;
}
};
this.update();
}
/* more functions here */
update() {
// move the ship
this.shipX += this.shipMovesHorizontal;
this.shipY += this.shipMovesVertical;
/* drawing stuff */
}
}
</code></pre>
<p><a href="https://codesandbox.io/s/v0l8v95nr5">Find the full version on CodeSandbox</a></p>
<p>This not only allows the ship to move in two directions at the same time, it also simplifies everything. But there's still the problem, that fast key presses don't get recognized well.</p>
<p>What actually happens in those stressful moments is correct from the code's point of view: If a key of the same dimension (horizontal or vertical) is pressed, set the movement direction, if it is released set movement to zero. But humans are not very exact. They might press the left arrow (or <code>a</code>) a split second before they fully released the right arrow (or <code>d</code>). This way, the function switches the movement direction for that split second but then stops because of the released key.</p>
<p>To fix this, the <code>keyup</code> handler needs a bit more logic:</p>
<pre><code class="language-js">document.onkeyup = event =&gt; {
const key = event.key;
switch (key) {
case &quot;d&quot;:
case &quot;ArrowRight&quot;:
if (this.shipMovesHorizontal &gt; 0) {
this.shipMovesHorizontal = 0;
}
break;
case &quot;a&quot;:
case &quot;ArrowLeft&quot;:
if (this.shipMovesHorizontal &lt; 0) {
this.shipMovesHorizontal = 0;
}
break;
case &quot;w&quot;:
case &quot;ArrowUp&quot;:
if (this.shipMovesVertical &lt; 0) {
this.shipMovesVertical = 0;
}
break;
case &quot;s&quot;:
case &quot;ArrowDown&quot;:
if (this.shipMovesVertical &gt; 0) {
this.shipMovesVertical = 0;
}
break;
}
};
</code></pre>
<p><a href="https://codesandbox.io/s/x765pl1zm4">Check out the full code at CodeSandbox</a></p>
<p>Much better, isn't it? Whatever we do, the ship is flying in the expected direction. Time to tackle the last problems. Lets go with the easier one first: Acceleration.</p>
<p>For now, the ship simply has a fixed speed. Lets make it faster first, because we want action, right? For that, we'll define the maximum speed of the ship:</p>
<pre><code class="language-js">this.shipSpeed = 5 // pixel per frame
</code></pre>
<p>And use it as a multiplicator:</p>
<pre><code class="language-js"> update() {
// move the ship
this.shipX += this.shipMovesHorizontal * this.shipSpeed;
this.shipY += this.shipMovesVertical * this.shipSpeed;
/* drawing stuff */
}
</code></pre>
<p>And now, instead of jumping to the full speed, we update velocity values per axis:</p>
<pre><code class="language-js"> constructor () {
/* ... */
this.shipSpeed = 5
this.shipVelocityHorizontal = 0
this.shipVelocityVertical = 0
/* ... */
}
/* ...more stuff... */
update () {
// accelerate the ship
const maxSpeed = this.shipSpeed;
// speed can be negative (left/up) or positive (right/down)
let currentAbsSpeedH = Math.abs(this.shipVelocityHorizontal);
let currentAbsSpeedV = Math.abs(this.shipVelocityVertical);
// increase ship speed until it reaches maximum
if (this.shipMovesHorizontal &amp;&amp; currentAbsSpeedH &lt; maxSpeed) {
this.shipVelocityHorizontal += this.shipMovesHorizontal * 0.2;
} else {
this.shipVelocityHorizontal = 0
}
if (this.shipMovesVertical &amp;&amp; currentAbsSpeedV &lt; maxSpeed) {
this.shipVelocityVertical += this.shipMovesVertical * 0.2;
} else {
this.shipVelocityVertical = 0
}
/* drawing stuff */
}
</code></pre>
<p>This slowly accelerates the ship until full speed. But it still stops immediately. To decelerate the ship and also make sure the ship actually stops and doesn't randomly float around due to rounding errors, some more lines are needed. You'll find everything in <a href="https://codesandbox.io/s/kxpn09n077">the final version on CodeSandbox</a>.</p>
<p>Now the last problem has be solved: Framerate-dependent movement. For now, all the values are tweaked in a way that they work nicely at the current speed. Lets assume at sixty frames per second. Now that poor computer has to install updates in the background or maybe it is just Chrome getting messy. Maybe the player has a different screen refresh rate. The result is a drop or increase of the frame rate. Lets take a drop down to the half as an example. Thirty frames per second is still completely smooth for almost everything. Movies have thirty frames per second and they do just fine, right? Yet our ship is suddenly only half as fast and that difference is very noticeable.</p>
<p>To prevent this, the movement needs to be based on actual time. Instead of a fixed value added to the coordinates each frame, a value is added that respects the time passed since the last update. The same is necessary for velocity changes. So instead of the more or less arbitrary five pixels at sixty frames per second we set the value in pixels per millisecond because everything is in millisecond precision.</p>
<pre><code class="language-js">5px*60/s = 300px/s = 0.3px/ms
</code></pre>
<p>This makes the next step rather easy: Count the amount of milliseconds since the last update and multiply it with the maximum speed and acceleration values:</p>
<pre><code class="language-js"> constructor () {
/* ... */
this.shipSpeed = 0.3 // pixels per millisecond
// how fast the ship accelerates
this.shipAcceleration = this.shipSpeed / 10.0
this.shipVelocityHorizontal = 0
this.shipVelocityVertical = 0
/* ... */
// this should always happen right before the first update call
// performance.now gives a high precision time value and is also
// used by requestAnimationFrame
this.lastDraw = performance.now()
requestAnimationFrame(stamp =&gt; this.update(stamp))
}
/* ...more stuff... */
// See the main loop section if &quot;stamp&quot; looks fishy to you.
update (stamp) {
// calculate how much time passed since last update
const timePassed = stamp - this.lastDraw
this.lastDraw = stamp
// accelerate the ship
const maxSpeed = this.shipSpeed * timePassed;
const accel = this.shipAcceleration * timePassed;
let currentAbsSpeedH = Math.abs(this.shipVelocityHorizontal);
let currentAbsSpeedV = Math.abs(this.shipVelocityVertical);
if (this.shipMovesHorizontal &amp;&amp; currentAbsSpeedH &lt; maxSpeed) {
const acceleration =
this.shipVelocityHorizontal += this.shipMovesHorizontal * accel;
} else {
this.shipVelocityHorizontal = 0
}
if (this.shipMovesVertical &amp;&amp; currentAbsSpeedV &lt; maxSpeed) {
this.shipVelocityVertical += this.shipMovesVertical * accel;
} else {
this.shipVelocityVertical = 0
}
/* drawing stuff */
}
</code></pre>
<p><a href="https://codesandbox.io/s/j4rzoq5kqy">Check out the full version at CodeSandbox</a></p>
<p>If everything is the same as before you did everything right. Now independent of the frame rate you ship will move five pixels per millisecond. Unfortunately I didn't find a good way to test that except for changing the refresh rate of your screen or overwriting <code>requestAnimationFrame</code> so I left this part out of the post.</p>
<h2>The End</h2>
<p>Congratulations, you made a fully moving ship. This Post ends here but of course there is so much more to learn about game development. <a href="https://nkoehring.github.io/FreddyvsJSON">Freddy vs JSON</a> adds some more elements but uses only techniques described in this article. Feel free to check out <a href="https://github.com/nkoehring/FreddyvsJSON">its source code</a> and create a ton of games like it. Or completely different ones. Be creative and enjoy to use what you've just learned.</p>
</main>
<div id="spacer"></div>
<header id="header" class="small">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 832.4 143.1">
<path id="header-underscore"
d="M832.4 131.1q0 5.5-3.1 8.6-3 3.4-8.2 3.3h-75.5q-5.2 0-8.2-3.3-1.7-1.6-2.4-3.8-.7-2.3-.7-4.8 0-5.5 3.1-8.7 1.6-1.7 3.7-2.4 2.2-.8 4.5-.8h75.5q5.2 0 8.2 3.2 3 3.1 3 8.7z" />
<path id="header-bracket"
d="M731.9 81.4q0 6.7-6.5 10.7l-1 .6-74.3 39.2q-2.5 1.3-5.2 1.2-4.8 0-8.1-3.8-3.2-3.6-3.2-8.4 0-3.3 1.7-6 1.8-2.9 4.6-4.4l55.3-29.1-55.3-29q-2.8-1.6-4.6-4.3-1.7-2.7-1.7-6.2 0-4.7 3.2-8.4 3.3-4 8-3.7 2.7 0 5.3 1.2l74.4 39.2q3.3 1.7 5.3 4.7 2 2.8 2 6.5z" />
<path id="header-r"
d="M588.7 66.5q0 5-3.5 8.5-3.5 3.4-8.1 3.5-4.4 0-8.3-4.3-10-10.7-20.9-10.6-2.2 0-4.3.3-2.1.3-4 1-1.8.6-3.7 1.6-1.7 1-3.4 2.3-1.7 1.3-3.3 2.9-7.8 8.2-7.6 19.7V131q0 5.5-3.1 8.6-3 3.4-8.3 3.3l-2.2-.2q-1-.1-2.2-.5-1-.3-2-1-1-.6-1.8-1.6-1.7-1.6-2.4-3.8-.7-2.3-.7-4.8V51.6q0-5.4 3-8.6 3-3.4 8.3-3.3 2 0 3.7.6 1.8.6 3.3 1.8 1.4 1 2.2 2.7 1 1.5 1.6 3.3 11.8-8.4 27-8.4 10.6 0 21 5 11.3 5.4 17.2 14.5 2.5 3.7 2.5 7.3z" />
<path id="header-h"
d="M483.9 131.1q0 5.5-3.1 8.6-3 3.4-8.3 3.3-5.2 0-8.2-3.3-3.2-3.1-3.1-8.6V84.8q0-4.6-1.5-8.2-1.4-3.5-4.4-6.9-2.1-2-4.3-3.4-2.2-1.4-4.7-2-2.4-.7-5.3-.7-4.3 0-7.8 1.5-3.3 1.5-6.4 4.6-5.9 6.3-5.8 15v46.4q0 5.5-3 8.6-3.1 3.4-8.4 3.3l-2.2-.2q-1-.1-2.2-.5-1-.3-2-1-1-.6-1.8-1.6-1.7-1.6-2.4-3.8-.7-2.3-.7-4.8V11.9q0-5.5 3-8.6 3-3.4 8.3-3.3 5.2 0 8.2 3.3 3.2 3.1 3.2 8.6v33q1.5-1 3-1.6l3.2-1.2 3.4-1q1.6-.5 3.3-.8l3.5-.4 3.6-.2q4.4 0 8.5 1 4.1.7 7.9 2.4 3.8 1.6 7.3 4.1 3.5 2.5 6.6 5.8Q484 66 484 84.8z" />
<path id="header-e"
d="M387.5 111.1q0 1.2-.3 2.3-.1 1-.5 2l-.9 2q-6.6 12-19.4 19-12 6.6-25.4 6.6-20.8 0-35.8-14.6-15.9-15-15.9-37 0-22.1 15.9-37.1 15-14.6 35.8-14.6 3.9 0 7.8.7 4 .7 8 2.2 9.2 3.1 18.2 10 6 4.6 9.1 9.3 3.3 4.7 3.3 10 0 1.3-.3 2.5-.2 1.3-.7 2.4-1.5 3.4-5 5.3l-56.9 32.2q7.2 4.9 16.5 4.9 7.2 0 12.6-2.5 5.5-2.5 9.7-7.4l.7-1 .8-1 .9-1.3 1-1.5q3.3-4.2 7.4-5.1l1.8-.2q4.4 0 8 3.4 3.6 3.5 3.6 8.5zm-29.9-42.7q-7.2-4.8-16.6-4.8-6 0-11 2-4.9 1.8-9.3 6-4.5 4-6.7 9-2 4.8-2 10.8l.1 2.9z" />
<path id="header-o"
d="M286.8 91.4q0 4.2-.6 8.3-.6 4-1.8 7.7-1.1 3.8-2.9 7.4-1.7 3.5-4 6.9-2.4 3.3-5.2 6.1Q258 143 237.7 143T203 128q-14.3-15.2-14.3-36.6 0-21.5 14.3-36.6 14.4-15 34.7-15 4 0 7.8.5 3.9.7 7.5 1.9t7 3q3.3 1.9 6.4 4.3 3.2 2.4 5.9 5.4 14.4 15 14.5 36.5zm-22.6 0q0-2.4-.4-4.5-.2-2.2-.9-4.2-.6-2-1.5-3.9-1-2-2.2-3.7-1.2-1.7-2.8-3.4-4-4.2-8.6-6.1-4.5-2-10-2-11 0-18.7 8.2-7.8 8-7.8 19.6 0 11.4 7.8 19.7 7.8 8 18.6 8 5.6 0 10.1-1.9 4.6-2 8.6-6.1 4-4.3 5.8-9 2-4.9 2-10.7z" />
<path id="header-k"
d="M186.3 131q0 4.7-3.3 8.3-1.5 1.8-3.7 2.7-2 1.1-4.3 1.1-3.5 0-6.6-2L119.2 105v26q0 5.5-3 8.6-3.1 3.4-8.4 3.3l-2.2-.2q-1-.1-2.2-.5-1-.3-2-1-1-.6-1.8-1.6-1.7-1.6-2.4-3.8-.7-2.3-.7-4.8V11.9q0-5.5 3-8.6 3-3.4 8.3-3.3 5.2 0 8.2 3.3 3.2 3.1 3.2 8.6v65.9l49.2-36.1q3.2-2 6.6-2 4.7 0 8 3.7t3.3 8.4q-.2 6-5 9.6l-41 30 41 29.9q2.3 1.7 3.6 4.2 1.4 2.5 1.4 5.4z" />
<path id="header-tilde"
d="M73.1 91q0 2-.6 3.9T71 98.6q-3.2 5.7-8.9 8.5-5.6 2.8-12.9 2.8-8.8 0-18-7.8-2.4-2.3-4.5-3.7-2.1-1.5-3-1.7-1.5 0-2.1.3l-.8 1.3q-.3.7-.8 1.2l-1 1-.9.8q-2.7 2-6.4 2-1.7 0-3.2-.3-1.4-.3-3-1.1-1.5-.8-2.6-2.1-2.8-3.1-2.8-8v-1.3q0-.7.2-1.2l.2-1 .4-1 .4-1q.1-.6.5-1.1l.5-1q3.2-5.7 8.8-8.5 5.7-2.9 13-2.9 3.2 0 6.2 1 3 .9 6 2.7 2.9 1.6 5.7 4.2 5.2 4.6 7.6 5.4 1 0 1.6-.2l.7-.4q.3-.1.5-.4 3.6-5.6 9.2-5.6 5.7 0 8.8 3.5 2.8 3 2.8 8z" />
</svg>
Homepage of
<div class=p-name>
<span class=first-name>Norman</span>
<span class=last-name>Köhring</span>
</div>
Code Artist
</header>
4 months ago
<div id="main-menu">
<menu>
<li><a href="/">home</a></li>
<li><a title="What I do these days" href="/now">/now</a></li>
<li><a title="Today I Learned" href="/til">/til</a></li>
<li><a title="My projects" href="/projects">/projects</a></li>
<li class="active"><a title="Weblog" href="/blog">/blog</a></li>
<li><a title="CV / Resume" href="/cv">/cv</a></li>
<li><a title="Tools I use" href="/stack">/stack</a></li>
<li><a title="Hardware I use" href="/setup">/setup</a></li>
</menu>
</div>
4 months ago
<link href=/extended.css rel=stylesheet>
<link href=/posts.css rel=stylesheet>
<script async data-goatcounter=https://koehr.goatcounter.com/count src=//gc.zgo.at/count.js></script>
</body>