Player movement
This commit is contained in:
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user