65 lines
1.6 KiB
Rust
65 lines
1.6 KiB
Rust
use bevy::prelude::*;
|
|
|
|
const FALL_SPEED: f32 = 300.0; // Falling speed
|
|
const DIVE_SPEED: f32 = 700.0; // Falling speed sped up
|
|
const HORIZONTAL_SPEED: f32 = 300.0; // Lateral movement speed
|
|
|
|
// The player
|
|
#[derive(Component)]
|
|
pub struct Player;
|
|
|
|
// Speed of the player
|
|
#[derive(Component)]
|
|
pub struct Velocity(Vec2);
|
|
|
|
// Spawn entity player
|
|
fn spawn_player(mut commands: Commands) {
|
|
commands.spawn((
|
|
Player,
|
|
Velocity(Vec2::ZERO),
|
|
Sprite::from_color(Color::srgb(1.0, 1.0, 1.0), Vec2::new(20.0, 40.0)),
|
|
Transform::from_xyz(0.0, 0.0, 1.0),
|
|
));
|
|
}
|
|
|
|
// Input + movement system for the player
|
|
pub(crate) 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);
|
|
}
|
|
}
|