Write a bevy program to move a 2d square using the WASD keys
- User
Write a bevy program to move a 2d square using the WASD keys
- Assistant
Here's a simple Bevy program that creates a 2D square and allows you to move it using the W, A, S, and D keys:
rustuse bevy::prelude::*; fn main() { App::new() .insert_resource(WindowDescriptor { title: "Move a Square with WASD".to_string(), width: 500.0, height: 500.0, ..Default::default() }) .add_plugins(DefaultPlugins) .add_startup_system(setup) .add_system(player_movement) .run(); } // Component to identify the player entity struct Player; // Setup system to spawn the square and camera fn setup(mut commands: Commands) { // Spawn the camera commands.spawn_bundle(OrthographicCameraBundle::new_2d()); // Spawn the square with a SpriteBundle commands .spawn_bundle(SpriteBundle { sprite: Sprite { color: Color::rgb(0.5, 0.5, 1.0), // Set the square's color ..Default::default() }, transform: Transform { scale: Vec3::new(50.0, 50.0, 1.0), // Set the size of the square ..Default::default() }, ..Default::default() }) .insert(Player); // Tag the entity with the Player component } // System to handle player movement fn player_movement( keyboard_input: Res<Input<KeyCode>>, time: Res<Time>, mut query: Query<&mut Transform, With<Player>>, ) { // Iterate over all entities with the Player component for mut transform in query.iter_mut() { let mut direction = Vec3::ZERO; // Determine the movement direction based on key presses if keyboard_input.pressed(KeyCode::W) { direction.y += 1.0; } if keyboard_input.pressed(KeyCode::S) { direction.y -= 1.0; } if keyboard_input.pressed(KeyCode::A) { direction.x -= 1.0; } if keyboard_input.pressed(KeyCode::D) { direction.x += 1.0; } // Normalize direction to ensure consistent speed when moving diagonally if direction != Vec3::ZERO { direction = direction.normalize(); } let speed = 200.0; // Movement speed (units per second) // Update the square's position transform.translation += direction * speed * time.delta_seconds(); } }