Smith | Game Development with Rust and WebAssembly | E-Book | sack.de
E-Book

E-Book, Englisch, 476 Seiten

Smith Game Development with Rust and WebAssembly

Learn how to run Rust on the web while building a game
1. Auflage 2022
ISBN: 978-1-80107-499-5
Verlag: De Gruyter
Format: EPUB
Kopierschutz: 0 - No protection

Learn how to run Rust on the web while building a game

E-Book, Englisch, 476 Seiten

ISBN: 978-1-80107-499-5
Verlag: De Gruyter
Format: EPUB
Kopierschutz: 0 - No protection



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.

Smith Game Development with Rust and WebAssembly jetzt bestellen!

Autoren/Hrsg.


Weitere Infos & Material


Table of Contents - Hello WebAssembly
- Drawing Sprites
- Creating a Game Loop
- Managing Animations with State Machines

- Collision Detection
- Creating an Endless Runner
- Sound Effects and Music
- Adding a UI

- Testing, Debugging, and Performance

- Continuous Deployment
- Further Resources and What's Next?


: Drawing Sprites


Now that we've got a working app and we're drawing to the screen, we can start making something that actually looks like a game. That means rendering sprites, which is just a fancy way of saying drawing pictures. So, in this chapter, we'll start by defining what those pictures are by doing a little bit of game design, and then we'll render a static sprite to the screen. Since a static picture is a pretty boring game, we'll even get the sprite animating too.

In this chapter, we'll do the following:

  • Design our game, Walk the Dog.
  • Render a sprite to the Canvas.
  • Use a sprite sheet to load many sprites at once.
  • Animate a character via the sprite sheet.

By the end of this chapter, you'll be drawing characters instead of static triangles, and you'll even have them running on the screen.

Technical requirements


In addition to the technical requirements of , , you'll need to download the assets found at https://github.com/PacktPublishing/Game-Development-with-Rust-and-WebAssembly/wiki/Assets. We'll build on top of the results of that chapter as well, so don't throw away the code. If you're reading this book out of order because you can't be tamed by society's rules, then you can get the previous chapter's source code at https://github.com/PacktPublishing/Game-Development-with-Rust-and-WebAssembly/tree/chapter_1 and start there. If you get stumped, you can find the complete source code for this chapter at https://github.com/PacktPublishing/Game-Development-with-Rust-and-WebAssembly/tree/chapter_2.

Check out the following video to see the Code in Action: https://bit.ly/3wOpCqy

A quick game design session


In the previous chapter, I had you create a project called "Walk the Dog", and you were so engrossed by the process of creating a Rust project and my thrilling prose that you didn't even ask why that was the name of the project. Now we'll dig into the game we're making for this book – Walk the Dog.

is an endless runner with a simple concept. You play as a boy walking his dog through the forest when your dog is surprised by a cat that runs by and starts chasing it. You, in turn, begin chasing your dog through the forest, dodging obstacles along the way, until you crash into one and fall down. At which point, of course, the dog turns around and checks on you.

In case you hadn't guessed, the idea for this game came to me while walking the dog on ice. I've used (https://miro.com) to make a prototype, just to get a feel for what the game will look like:

Figure 2.1 – A Walk the Dog screen, hypothetically

Before you get the idea that I'm a great artist, all of the assets I'm using are freely available online via creative commons licenses. You might notice that the background is a little fuzzy relative to the characters, and that's because I made almost no effort to scale the characters to fit beyond copying and pasting them into Miro and dragging the corners around. When we place the actual objects in our game, we'll need to make a better effort than that.

The temptation at this point is to say, "we're done" and start coding. Given the small size of our game, I don't think we need a full treatment to start coding, but I do want to make sure that we clarify a few things about the game.

Scoring is done by measuring how far our little Red Hat Boy (RHB for short) runs – the same as most endless runners such as (http://canabalt.com/) or the game that shows up when you start Google Chrome without an internet connection. The dog and cat navigate all obstacles effortlessly and are just there to give the player ideas on how to catch the dog, and perhaps mislead the player by taking a path they cannot follow. Obstacles will include rocks and boxes that you can crash into and water that you can fall into. RHB has a slide animation, so sometimes he'll need to slide under little cliffs too, which the dog runs under effortlessly. It's not enough for a fully fledged game, but it's enough to give us a checklist of features for future chapters. Let's say goodbye to our lovely triangles and begin rendering our adorable Red Hat Boy.

Rendering a sprite


Sprite is a term so commonplace that it's possible to use it in conversation without actually knowing its meaning, yet properly defining it means properly defining bitmap, which in turn means properly defining pixmap. Did you know the term sprite was coined in the 1970s by Danny Hillis (http://bit.ly/3aZlJ72)? It's exhausting.

While I find all of this fascinating, you didn't get this book for that, so for our purposes, a sprite is a 2D image loaded from a file. Red Hat Boy, his dog and cat, and the background will all be sprites. Let's not waste any more time on definitions and start drawing one.

Loading images


We'll start by unzipping the assets and copying the Idle (1).png file from resized/rhb into the static directory in your project. This will make it reachable from your program. As we build the program out, we'll need further organization, but for one file, this is fine. Next, we'll need to modify our code. You can leave the Sierpinski triangle in there for now as it looks cute next to the sprite, but the first thing to do is use the HTMLImage element to load an image. For now, it's important that you load and draw the image before calling into the Sierpinski triangle. It looks like this:

#[wasm_bindgen(start)]

pub fn main_js() -> Result<(), JsValue> {

    ....

    let image = web_sys::HtmlImageElement::new().unwrap();

    image.set_src("Idle (1).png");

    sierpinski(

        &context,

        [(300.0, 0.0), (0.0, 600.0), (600.0, 600.0)],

        (0, 255, 0),

        5,

    );

    Ok(())

}

You will once again get the ^^^^^^^^^^^^^^^^ could not find `HtmlImageElement` in `web_sys` error. Remember that the web-sys crate makes heavy use of feature flags, so you'll need to add HtmlImageElement to the feature flag list in Cargo.toml. After you add that, rebuilding will take a little longer, but the application will build again. Now you have loaded the image, and we can draw it.

Canvas coordinates


Before we draw it, we need to cover one thing about the Canvas that you might have noticed from the first chapter, and that is the coordinate system. In the first chapter, we covered how the Canvas has a context; in fact, it has multiple contexts, but you can only use one per canvas, and that we are using the 2D context, which gives us an API for drawing directly to the screen. Then, we made a bunch of line_to and move_to commands that may not have made sense at the time, which is why we need to discuss the coordinate system:

Figure 2.2 – Source: Mozilla (http://mzl.la/30NLhxX)

Our canvas is divided into a 2D grid with dimensions of 600 by 600. Why 600 x 600? Because that's the height and width of our canvas element on the HTML page that we created in , . The size itself was completely arbitrary, and we'll probably change it as our game grows. The units of the grid are pixels, so when we moved the top of our original triangle to (300.0, 0.0), we moved it 300 pixels to the right (because x is first) and 0 pixels down (because y is second). Note that 0 is at the top of the screen because (0.0, 0.0) is in the top-left corner of the canvas.

Drawing images


Drawing one image at this point seems uncomplicated – we'll use the drawImage command from JavaScript; only we'll use the web-sys version for HtmlElement.

Tip

Remember that JavaScript functions frequently use function overloading, which Rust doesn't support, so one JavaScript function may have many corresponding variations in Rust.

So, let's add the draw command right after the code to load the image, and we'll be done:

image.set_src("Idle (1).png");

context.draw_image_with_html_image_element(&image, 0.0, 0.0);

...

We've ignored Result from the draw_image_with_html_image_element command, but that should draw the image, except, it…doesn't....


Smith Eric:

Eric Smith is a software crafter with over 20 years of software development experience. Since 2005, he's worked at 8th Light, where he consults for companies big and small by delivering software, mentoring developers, and coaching teams. He's a frequent speaker at conferences speaking on topics such as educating developers and test-driven development, and holds a master's degree in video game development from DePaul University. Eric wrote much of the code for this book live on his Twitch stream. When he's not at the computer, you can find Eric running obstacle races and traveling with his family.



Ihre Fragen, Wünsche oder Anmerkungen
Vorname*
Nachname*
Ihre E-Mail-Adresse*
Kundennr.
Ihre Nachricht*
Lediglich mit * gekennzeichnete Felder sind Pflichtfelder.
Wenn Sie die im Kontaktformular eingegebenen Daten durch Klick auf den nachfolgenden Button übersenden, erklären Sie sich damit einverstanden, dass wir Ihr Angaben für die Beantwortung Ihrer Anfrage verwenden. Selbstverständlich werden Ihre Daten vertraulich behandelt und nicht an Dritte weitergegeben. Sie können der Verwendung Ihrer Daten jederzeit widersprechen. Das Datenhandling bei Sack Fachmedien erklären wir Ihnen in unserer Datenschutzerklärung.