Book Image

Game Development with Rust and WebAssembly

By : Eric Smith
Book Image

Game Development with Rust and WebAssembly

By: Eric Smith

Overview of this book

The Rust programming language has held the most-loved technology ranking on Stack Overflow for 6 years running, while JavaScript has been the most-used programming language for 9 years straight as it runs on every web browser. Now, thanks to WebAssembly (or Wasm), you can use the language you love on the platform that's everywhere. This book is an easy-to-follow reference to help you develop your own games, teaching you all about game development and how to create an endless runner from scratch. You'll begin by drawing simple graphics in the browser window, and then learn how to move the main character across the screen. You'll also create a game loop, a renderer, and more, all written entirely in Rust. After getting simple shapes onto the screen, you'll scale the challenge by adding sprites, sounds, and user input. As you advance, you'll discover how to implement a procedurally generated world. Finally, you'll learn how to keep your Rust code clean and organized so you can continue to implement new features and deploy your app on the web. By the end of this Rust programming book, you'll build a 2D game in Rust, deploy it to the web, and be confident enough to start building your own games.
Table of Contents (16 chapters)
1
Part 1: Getting Started with Rust, WebAssembly, and Game Development
4
Part 2: Writing Your Endless Runner
11
Part 3: Testing and Advanced Tricks

Adding animation

Sprite animation works just like a flip-book or a movie. Show a sequence of images fast enough, where each image is drawn to be only slightly different than the previous one, and it causes the illusion of motion. Animation on the canvas works in much the same way, where each frame in the sprite sheet has the same effect as a drawing in a flip-book:

Figure 2.7 – The run animation for Red Hat Boy

Figure 2.7 – The run animation for Red Hat Boy

To draw Red Hat Boy running, we have to simply draw the images in order, one at a time, and loop after drawing the last one. Simple for a loop, right?

Of course, it's not quite that simple. First, we can't just use an infinite loop, as that would block the browser from any processing, resulting in a frozen browser tab. Second, we have to make sure to clear the canvas between each frame. Otherwise, we'll see all the images merged together as one draws on top of the other. So, each time we draw the canvas, we'll need...