0
0

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ゲーム開発レシピ: テキストを描画しよう

Last updated at Posted at 2025-08-27

Bevyを使った個人でゲーム開発を行なっている登尾(のぼりお)です。

今回はシンプルにBevy上にテキストを描いてみましょう。

スクリーンショット 2025-08-27 15.43.15.png

フォントを準備しよう

適当なフォントファイルをassetsフォルダにおいて、それを読み込みます。今回の例では、 assets/LinestriderRegular-PjJd 2.ttf があるものとして進めています。

このフォント自体は以下で見つけた、パブリックドメインなフォントです。

Bevyらしく以下のようにFontHandleリソースを用意し、読み込んだフォントを後で利用するために使います。

#[derive(Resource)]
struct FontHandle(Handle<Font>);

fn setup_font(mut commands: Commands, assets: Res<AssetServer>) {
    commands.insert_resource(FontHandle(assets.load("LinestriderRegular-PjJd 2.ttf")));
}

テキストを描画しよう

Nodeを作りその中で、位置と色をランダムに決めて、描画しています。

fn setup_texts(mut commands: Commands, font: Res<FontHandle>) {
    let mut rng = rand::rng();

    for _n in 0..20 {
        let x = rng.random_range((-(WIDTH as i32) / 2)..((WIDTH as i32) / 2)) as f32;
        let y = rng.random_range((-(HEIGHT as i32) / 2)..((HEIGHT as i32) / 2)) as f32;
        let color = Color::linear_rgba(
            rng.random_range(0.0..1.0),
            rng.random_range(0.0..1.0),
            rng.random_range(0.0..1.0),
            0.5,
        );

        commands
            .spawn(Node {
                position_type: PositionType::Absolute,
                ..default()
            })
            .with_children(|p| {
                p.spawn((
                    Text2d::new("text"),
                    TextFont {
                        font: font.0.clone(),
                        font_size: 80.0,
                        ..default()
                    },
                    TextColor(color),
                    Transform::from_translation(Vec3::new(x, y, 0.0)),
                ));
            });
    }
}

Nodeの中で、

  • Text2d: テキストの中身
  • TextFont: フォントとフォントサイズ
  • TextColor: テキストの色
  • Transform: 描画位置

という形のセットをspawnすることで実現しています。

おしまい

今回もこれまで同様以下の個人リポジトリで公開しています。

cloneした後に、

% cargo run --example texts

で挙動を確認できます。

Bevyが最新版の0.16になり、ネットの情報では新しいAPIでのやり方が見つかりにくいのかなと思っていますので何かの参考になれば幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?