Logo for Sneaky Crow, LLC (vector art of a crow with a green baseball cap on)

Brain Juice

Running a Bevy game in SvelteKit

Recently, I started working on a new project using Bevy, a game engine written in Rust. I've been really enjoying it so far, and I'm excited to see where it goes.

I'd like to document the process of developing games, but I also wanted people to be able to play wasm builds of the games I make. I recently converted my entire website to SvelteKit, and I wanted to be able to import my games into it. I couldn't find any examples of using Bevy with SvelteKit specifically, so I thought I'd write one.

For this tutorial we will create a basic SvelteKit project, create a Rust workspace with a Bevy game, and configure SvelteKit to run the game.

Creating a basic SvelteKit project

We'll start with creating a basic SvelteKit project. If you already have a project you'd like to use, you can skip this

1
npm create svelte@latest my-sveltekit-project && cd sveltekit-project

Next, we'll need to update the Vite configuration to be able to import wasm later. We're going to utilize the vite-plugin-wasm and vite-plugin-top-level-await plugins to do this.

1
npm install -D vite-plugin-wasm vite-plugin-top-level-await

Next, open vite.config.js and update the plugins section to look like this:

1
import { sveltekit } from "@sveltejs/kit/vite";
2
import { defineConfig } from "vite";
3
import topLevelAwait from "vite-plugin-top-level-await";
4
import wasm from "vite-plugin-wasm";
5

6
export default defineConfig({
7
  plugins: [sveltekit(), wasm(), topLevelAwait()]
8
});

Before we can import wasm, we need...the wasm. So next, we'll initialize our Bevy game.

Adding a Bevy game

We'll start by creating a new Rust workspace. If you already have a workspace you'd like to use, you can skip this step.

Add a new file called Cargo.toml to the root of your project with the following contents:

1
[workspace]
2
members = ["game"]

Next, we'll initialize our bevy game in the game directory.

1
cargo new game

You'll need to also make sure you have the wasm target installed. You can do this by running:

1
rustup target add wasm32-unknown-unknown

Next, add bevy as a dependency in our game/Cargo.toml file.

1
[dependencies]
2
bevy = "0.11"

For this next part, any game that can compile to wasm should be fine.

One important change you'll want to make though is to update the WindowPlugin canvas property to use a custom id. This is how we're going to control the canvas element from SvelteKit.

Here's an example of customizing the WindowPlugin:

1
use bevy::prelude::*;
2

3
fn main() {
4
    let mut window_plugin = WindowPlugin::default();
5
    window_plugin.primary_window = Some(Window {
6
        title: "Game".to_string(),
7
        canvas: Some("#game_canvas".to_string()), // This is the important part
8
        ..Default::default()
9
    });
10
    let plugins = DefaultPlugins.set(window_plugin);
11
    App::new()
12
        .add_plugins(plugins)
13
        .run();
14
}
15

If you'd like a basic game to test with, you can use the following example from bevy:

1
//! Shows how to render simple primitive shapes with a single color.
2

3
use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
4

5
fn main() {
6
    let mut window_plugin = WindowPlugin::default();
7
    window_plugin.primary_window = Some(Window {
8
        title: "Game".to_string(),
9
        canvas: Some("#game_canvas".to_string()),
10
        ..Default::default()
11
    });
12
    let plugins = DefaultPlugins.set(window_plugin);
13
    App::new()
14
        .add_plugins(plugins)
15
        .add_systems(Startup, setup)
16
        .run();
17
}
18

19
fn setup(
20
    mut commands: Commands,
21
    mut meshes: ResMut<Assets<Mesh>>,
22
    mut materials: ResMut<Assets<ColorMaterial>>,
23
) {
24
    commands.spawn(Camera2dBundle::default());
25

26
    // Circle
27
    commands.spawn(MaterialMesh2dBundle {
28
        mesh: meshes.add(shape::Circle::new(50.).into()).into(),
29
        material: materials.add(ColorMaterial::from(Color::PURPLE)),
30
        transform: Transform::from_translation(Vec3::new(-150., 0., 0.)),
31
        ..default()
32
    });
33

34
    // Rectangle
35
    commands.spawn(SpriteBundle {
36
        sprite: Sprite {
37
            color: Color::rgb(0.25, 0.25, 0.75),
38
            custom_size: Some(Vec2::new(50.0, 100.0)),
39
            ..default()
40
        },
41
        transform: Transform::from_translation(Vec3::new(-50., 0., 0.)),
42
        ..default()
43
    });
44

45
    // Quad
46
    commands.spawn(MaterialMesh2dBundle {
47
        mesh: meshes
48
            .add(shape::Quad::new(Vec2::new(50., 100.)).into())
49
            .into(),
50
        material: materials.add(ColorMaterial::from(Color::LIME_GREEN)),
51
        transform: Transform::from_translation(Vec3::new(50., 0., 0.)),
52
        ..default()
53
    });
54

55
    // Hexagon
56
    commands.spawn(MaterialMesh2dBundle {
57
        mesh: meshes.add(shape::RegularPolygon::new(50., 6).into()).into(),
58
        material: materials.add(ColorMaterial::from(Color::TURQUOISE)),
59
        transform: Transform::from_translation(Vec3::new(150., 0., 0.)),
60
        ..default()
61
    });
62
}

Next, we just need to build our game for the wasm target.

1
cargo build --release --bin game --target wasm32-unknown-unknown

Now we should have a wasm file at target/wasm32-unknown-unknown/release/game.wasm.

We're almost done! Next we're going to utilize wasm-bindgen to package our wasm file into a js/ts file that we can import into our SvelteKit project.

Generating lib files with wasm-bindgen

We're going to run wasm-bindgen and have it output our files to an assets directory for Svelte to be able to import.

1
wasm-bindgen --out-dir src/assets/game --target web ./target/wasm32-unknown-unknown/release/game.wasm

This will generate a game.js and game_bg.wasm file in the src/assets/game directory.

Configuring SvelteKit to run the game

Now that we have importable js files, we can create our Svelte component to run the game. We'll create a component that renders a canvas element with a matching id to the one we specified in our game. And then we can customize this canvas component

Create a new file src/lib/components/Game.svelte with the following contents:

1
<script>
2
  import { onMount } from "svelte";
3
  import __wbg_init from "../../assets/game";
4

5
  onMount(async () => {
6
    await __wbg_init();
7
  });
8
</script>
9

10
<canvas id="game_canvas" />

Now we can import this component into our src/routes/index.svelte file and render it.

1
<script>
2
  import Game from "$lib/components/Game.svelte";
3
</script>
4

5
<Game />

Now we should be able to run our SvelteKit project and see our game running!

1
npm run dev