Player movement

This commit is contained in:
2026-09-15 23:24:16 +02:00
parent 8ba07bb02b
commit fe35a17901
2 changed files with 49 additions and 4 deletions
+3
View File
@@ -1,5 +1,7 @@
use bevy::{prelude::*, window::PresentMode};
use crate::player::PlayerPlugin;
mod player;
fn main() {
@@ -15,6 +17,7 @@ fn main() {
}))
.insert_resource(ClearColor(Color::srgb(0.0, 0.0, 0.0)))
.add_systems(Startup, setup)
.add_plugins(PlayerPlugin)
.run();
}
+46 -4
View File
@@ -12,11 +12,53 @@ struct Player;
#[derive(Component)]
struct Velocity(Vec2);
// Spawn player
fn spawn_player(mut command: Commands) {
command.spawn((
// Spawn entity player
fn spawn_player(mut commands: Commands) {
commands.spawn((
Player,
Velocity(Vec2::ZERO),
Sprite::from_color(Color::srgb(128.0, 0.0, 128.0), Vec2::new(20.0, 40.0)),
Sprite::from_color(Color::srgb(0.5, 0.5, 0.5), Vec2::new(20.0, 40.0)),
Transform::from_xyz(0.0, 350.0, 0.0), // Top of the screen
));
}
// Input + movement system for the player
fn move_player(
input: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
mut player: Query<(&mut Velocity, &mut Transform), With<Player>>,
) {
// If matching entity
let Ok((mut velocity, mut transform)) = player.single_mut() else {
return;
};
// Change then horizontal direction regardless the input
let direction = if input.pressed(KeyCode::KeyA) {
-1.0
} else if input.pressed(KeyCode::KeyD) {
1.0
} else {
0.0
};
velocity.0 = Vec2::new(
direction * HORIZONTAL_SPEED,
-if input.pressed(KeyCode::KeyS) {
DIVE_SPEED
} else {
FALL_SPEED
},
);
transform.translation += velocity.0.extend(0.0) * time.delta_secs();
}
pub struct PlayerPlugin;
impl Plugin for PlayerPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, spawn_player)
.add_systems(Update, move_player);
}
}