Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Resources - the Power of Global State

Resources are a bit like components, in that they're also a Struct or enum that you define. Unlike components, only one of them exists at any given time, and you can access it in a system mutably with Mut<T> or as a reference with Ref<T>. When declaring your own, you also must #[derive(Default)] so that it can be initialized when the game starts. Effectively, resources are like components that apply to your entire game instance, instead of to a specific entity.

If, for some reason, you wanted your own global Time resource you can pass to systems, you could define it like so:

#[derive(Default)]
#[resource]
struct Time {
    time: f32,
}

I don't know why you would, but you could!

For our purposes, though, we want to use some of the powerful builtin resources. Well, one in particular, InputState. We'll need to get you the actual documentation for it but the short form is this is how you access what kind of inputs are being pressed/sent to the game via your player.

If we want to move our player ourselves, we just need to adjust our move_player function to actually care about the InputState. So let's make that change to lib.rs

srclib.rs
#[system]
fn move_player(mut player: Query<(Mut<Transform>, Ref<Player>)>, input: Ref<InputState>) {
    player.for_each(|(mut transform, _)| {
        if input.keys[KeyCode::KeyW].pressed() {
            transform.position.y += 5.;
        }

        if input.keys[KeyCode::KeyS].pressed() {
            transform.position.y -= 5.;
        }

        if input.keys[KeyCode::KeyD].pressed() {
            transform.position.x += 5.;
        }

        if input.keys[KeyCode::KeyA].pressed() {
            transform.position.x -= 5.;
        }
    });
}

💡   If you read the Minimal Sample then this probably looks familiar to you...

If we now run our game with this system, we can actually move our orange circle around! Hurray!

Next we'll get to Part 2 and actually start making a game, not just covering the basics.