96 lines
2.0 KiB
Rust
96 lines
2.0 KiB
Rust
|
|
use bevy::prelude::*;
|
||
|
|
|
||
|
|
#[derive(Component)]
|
||
|
|
struct EntityPhysics {
|
||
|
|
x: f32,
|
||
|
|
y: f32,
|
||
|
|
speed: f32,
|
||
|
|
heading: f32,
|
||
|
|
}
|
||
|
|
|
||
|
|
fn main() {
|
||
|
|
let mut app = App::new();
|
||
|
|
|
||
|
|
app.add_plugins(DefaultPlugins)
|
||
|
|
.add_systems(Startup, (hello_world, camera_setup, sprite_setup).chain())
|
||
|
|
.add_systems(Update, (handle_keys, player_physics).chain());
|
||
|
|
|
||
|
|
app.run();
|
||
|
|
}
|
||
|
|
|
||
|
|
fn hello_world() {
|
||
|
|
println!("Hello, world!");
|
||
|
|
}
|
||
|
|
|
||
|
|
fn camera_setup(mut clear_color: ResMut<ClearColor>, mut commands: Commands) {
|
||
|
|
*clear_color = ClearColor(Color::WHITE);
|
||
|
|
|
||
|
|
commands.spawn(Camera2d);
|
||
|
|
}
|
||
|
|
|
||
|
|
fn sprite_setup(assets: Res<AssetServer>, mut commands: Commands) {
|
||
|
|
let sprite_handle = assets.load("sprite-0001.png");
|
||
|
|
|
||
|
|
commands.spawn((
|
||
|
|
Sprite {
|
||
|
|
image: sprite_handle,
|
||
|
|
..default()
|
||
|
|
},
|
||
|
|
EntityPhysics {
|
||
|
|
x: 0.,
|
||
|
|
y: 0.,
|
||
|
|
speed: 0.,
|
||
|
|
heading: 0.,
|
||
|
|
},
|
||
|
|
));
|
||
|
|
}
|
||
|
|
|
||
|
|
fn handle_keys(mut q_player: Query<&mut EntityPhysics>, keys: Res<ButtonInput<KeyCode>>) {
|
||
|
|
if keys.just_pressed(KeyCode::KeyQ) {
|
||
|
|
info!("Quit.");
|
||
|
|
}
|
||
|
|
|
||
|
|
let Ok(mut player) = q_player.single_mut() else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
|
||
|
|
if keys.just_pressed(KeyCode::ArrowUp) {
|
||
|
|
player.speed += 0.1;
|
||
|
|
}
|
||
|
|
|
||
|
|
if keys.just_pressed(KeyCode::ArrowRight) {
|
||
|
|
player.heading += 0.1;
|
||
|
|
}
|
||
|
|
|
||
|
|
if keys.just_pressed(KeyCode::ArrowLeft) {
|
||
|
|
player.heading -= 0.1;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
fn player_physics(mut q_player: Query<(&mut EntityPhysics, &mut Transform)>) {
|
||
|
|
let Ok((mut physics, mut transform)) = q_player.single_mut() else {
|
||
|
|
return;
|
||
|
|
};
|
||
|
|
|
||
|
|
let x_speed = physics.heading.sin() * physics.speed;
|
||
|
|
let y_speed = physics.heading.cos() * physics.speed;
|
||
|
|
|
||
|
|
physics.x += x_speed;
|
||
|
|
physics.y += y_speed;
|
||
|
|
|
||
|
|
transform.translation = Vec3 {
|
||
|
|
x: physics.x as f32,
|
||
|
|
y: physics.y as f32,
|
||
|
|
z: 0.,
|
||
|
|
};
|
||
|
|
|
||
|
|
transform.rotation = Quat::from_axis_angle(
|
||
|
|
Vec3 {
|
||
|
|
x: 0.,
|
||
|
|
y: 0.,
|
||
|
|
z: -1.,
|
||
|
|
},
|
||
|
|
physics.heading,
|
||
|
|
);
|
||
|
|
}
|