Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

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?

[Bevy] 丸をキーボード入力で動かし、無限ループさせる

Posted at

丸いオブジェクトをキーボード入力(矢印キー)で動かし、フィールドを無限ループさせる動作をさせてみます。

前回に加筆する形で作成します。

オブジェクトの設置

丸い形を作成し、設置します。
座標軸はどうやらウィンドウ中央が(0, 0)で、右方向がx軸プラス、上方向がy軸プラスのように見えたけれど、気のせいかも知れません。

fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {

    let shape = meshes.add(Circle::new(100.0));
    commands.spawn((
        Mesh2d(shape),
        MeshMaterial2d(materials.add(Color::WHITE)),
        Transform::from_xyz(0.0, 0.0, 0.0),
    ));

キーボード入力処理

キーボード入力イベントとオブジェクトのquery?を引数とするkeyboard_input関数を作成し、Updateへ登録します。

Mesh2dのエンティティ?を取りだし、キーボードの矢印キーの入力イベントがあればエンティティの座標を加算または減算し、変更します。

これによって、丸が動きます。

もし、変更後の座標が画面外へはみ出した場合は、画面の反対側に配置するように座標を書き換えます。

これにより、無限ループ移動が可能となります。

fn keyboard_input(
    window_size: ResMut<WindowSize>,
    keys: Res<ButtonInput<KeyCode>>,
    mut query: Query<&mut Transform, With<Mesh2d>>,
) {
    for mut transform in &mut query {
        if keys.pressed(KeyCode::ArrowLeft) {
            transform.translation.x -= 10.0;
        }
        if keys.pressed(KeyCode::ArrowUp) {
            transform.translation.y += 10.0;
        }
        if keys.pressed(KeyCode::ArrowDown) {
            transform.translation.y -= 10.0;
        }
        if keys.pressed(KeyCode::ArrowRight) {
            transform.translation.x += 10.0;
        }

        if transform.translation.x < -window_size.width / 2.0 {
            transform.translation.x = window_size.width / 2.0;
        }
        if transform.translation.x > window_size.width / 2.0 {
            transform.translation.x = -window_size.width / 2.0;
        }
        if transform.translation.y < -window_size.height / 2.0 {
            transform.translation.y = window_size.height / 2.0;
        }
        if transform.translation.y > window_size.height / 2.0 {
            transform.translation.y = -window_size.height / 2.0;
        }
    }
}

動作確認

これで、丸を動かせるようになりました。

やっぱり、実際に動くと感動しますね。

終わりに

ここは簡単に実現できました。

これができれば、簡単なゲームやアートのような描画もできそうな気がしてきます。

引き続きやっていきましょう。

ここまで読んでいただき、ありがとうございました。

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?