Hello, I want to learn how the ECS data driven works, and I have done this simple code:
use bevy::prelude::*;
#[derive(Component)]
pub struct Position {
pub x: f32,
pub y: f32,
}
#[derive(Component)]
pub struct Velocity {
pub x: f32,
pub y: f32,
}
#[derive(Component)]
pub struct Health {
pub health: i32,
pub can_loose_health: bool,
}
#[derive(Component)]
pub struct Damage {
pub damage: i32,
pub can_be_damage: bool,
}
#[derive(Bundle)]
pub struct EntityBundle {
pub position: Position,
pub velocity: Velocity,
pub health: Health,
pub damage: Damage,
pub sprite: Sprite,
}
pub struct EntityPlugin;
impl Plugin for EntityPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, create_entities)
.add_systems(Update, update_movement_by_keyboard);
}
}
pub fn create_entities(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(EntityBundle {
position: Position { x: 0.0, y: 0.0 },
velocity: Velocity { x: 5.0, y: 5.0 },
health: Health {
health: 100,
can_loose_health: true,
},
damage: Damage {
damage: 10,
can_be_damage: true,
},
sprite: Sprite::from_image(
asset_server.load("Main Characters\\Pink Man\\Idle (32x32).png"),
),
});
}
pub fn update_movement_by_keyboard(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut query: Query<(&mut Position, &Velocity)>,
) {
for (mut position, velocity) in query.iter_mut() {
if keyboard_input.pressed(KeyCode::KeyW) {
position.y += velocity.y;
}
if keyboard_input.pressed(KeyCode::KeyS) {
position.y -= velocity.y;
}
if keyboard_input.pressed(KeyCode::KeyA) {
position.x -= velocity.x;
}
if keyboard_input.pressed(KeyCode::KeyD) {
position.x += velocity.x;
}
}
}```