1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust×Bevyゲーム開発レシピ: Bevy導入と背景を切り替えよう

Posted at

Bevyを使った個人ゲーム開発を行う登尾(のぼりお)です。今回はBevyの導入とシンプルに背景を切り替える実装を解説します。

最低限のBevy環境を整えよう

まずは、Bevyを入れて、空のウィンドウが立ち上がるシンプルな状態までの解説です。Rustが導入済みであることを前提で進めます。

まずは、プロジェクトを作成してください。

% cargo new bevy_beginning
    Creating binary (application) `bevy_beginning` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

% cd bevy_beginning

作成したフォルダの中でBevyを導入します。

cargo add bevy

以下のようなCargo.tomlファイルができていれば成功です。(執筆時点ではBevyのバージョンは0.16.1でした。)

[package]
name = "bevy_beginning"
version = "0.1.0"
edition = "2024"

[dependencies]
bevy = "0.16.1"

src/main.rsの内容を以下のように書き換えて、実行すれば本当に最低限ですがBevyを経由したウィンドウが立ち上がることを確認できると思います。

use bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .run();
}

以下はVisual Studio Code経由で立ち上げたところです。

スクリーンショット 2025-08-20 12.57.07.png

ターミナル経由であれば、

cargo run

で起動できます。

ウィンドウの背景を変えてみよう

src/main.rsに以下の関数を定義します。

fn setup_clear_color(mut clear_color: ResMut<ClearColor>) {
    clear_color.0 = Color::BLACK;
}

背景色を黒にする関数がsetup_clear_colorです。これをウィンドウが起動したタイミングで一度だけ呼ばれるようmain関数を以下のように修正してください。

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup_clear_color)
        .run();
}

この変更によって先ほどまでのウィンドウが以下のような背景が黒い状態になることが確認できればOKです。

スクリーンショット 2025-08-20 13.09.03.png

キーに反応して背景を変えよう

最後の実例として、押されたキーによってリアルタイムに色をかえるコードを紹介して終わりにします。

以下のような関数をさらに追加してください。スペースキーが押されれば背景が白になり、エンターキーが押されれれば背景が白になるという関数です。

fn change_clear_color(keys: Res<ButtonInput<KeyCode>>, mut clear_color: ResMut<ClearColor>) {
    if keys.just_pressed(KeyCode::Space) {
        clear_color.0 = Color::WHITE;
    } else if keys.just_pressed(KeyCode::Enter) {
        clear_color.0 = Color::BLACK;
    }
}

この関数がリアルタイムに呼ばれるよう以下のようにmain関数を書き換えて起動すればキー入力に応じた背景色の変更が可能になります。

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, setup_clear_color)
        .add_systems(Update, change_clear_color)
        .run();
}

おしまい

今回のコードは以下の個人リポジトリで公開しています。

cloneした後に、

% cargo run --example clear_color 

で起動できますので、そちらも参考にしてみてください。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?