WIP movement

This commit is contained in:
Daniel Flanagan 2023-12-20 13:36:34 -06:00
parent 72918dd102
commit 1c787d17ff
Signed by: lytedev
GPG key ID: 5B2020A0F9921EF4
3 changed files with 99 additions and 0 deletions

View file

@ -2,6 +2,8 @@ use bevy::prelude::*;
mod assets;
mod camera;
mod movement;
mod player;
fn main() {
let mut app = App::new();

40
src/movement.rs Normal file
View file

@ -0,0 +1,40 @@
use bevy::prelude::*;
pub struct MovementPlugin;
#[derive(Component, Debug, Default)]
pub struct Velocity(Vec2);
#[derive(Component, Debug, Default)]
pub struct Heading(Vec2);
#[derive(Component, Debug, Default)]
pub struct Speed(f32);
impl Velocity {
pub fn from_speed_heading(heading: Vec2, speed: f32) -> Self {
Self(heading.normalize_or_zero() * speed)
}
pub fn new(x: f32, y: f32) -> Self {
Self(Vec2::new(x, y))
}
}
#[derive(Bundle, Debug, Default)]
pub struct MovementBundle {
pub velocity: Velocity,
}
impl Plugin for MovementPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, update_position);
}
}
fn update_position(mut query: Query<(&Velocity, &mut Transform)>, time: Res<Time>) {
for (velocity, mut transform) in query.iter_mut() {
// TODO: convert vec2 to vec3 with a zero Z value?
transform.translation += velocity.0 * time.delta_seconds();
}
}

57
src/player.rs Normal file
View file

@ -0,0 +1,57 @@
use bevy::prelude::*;
use crate::{
assets::Assets,
movement::{MovementBundle, Velocity},
};
const PLAYER_SPEED: f32 = 50.;
pub struct PlayerPlugin;
impl Plugin for PlayerPlugin {
fn build(&self, app: &mut App) {
app.add_systems(PostStartup, spawn_player)
.add_systems(Update, player_movement);
}
}
#[derive(Component, Debug)]
pub struct Player;
fn spawn_player(mut commands: Commands, sprite_assets: Res<SpriteAssets>) {
commands.spawn((
Player,
SpriteBundle {
texture: sprite_assets.knight.clone(),
transform: Transform::from_xyz(0., 0., 0.),
..Default::default()
},
MovementBundle {
velocity: Velocity::new(0., 0.),
},
));
}
fn player_movement(mut query: Query<&mut Velocity, With<Player>>, input: Res<Input<KeyCode>>) {
let mut direction = Vec3::ZERO;
for key in input.get_pressed() {
match key {
KeyCode::W | KeyCode::Up => {
direction += Vec3::Y;
}
KeyCode::A | KeyCode::Left => {
direction += Vec3::NEG_X;
}
KeyCode::S | KeyCode::Down => {
direction += Vec3::NEG_Y;
}
KeyCode::D | KeyCode::Right => {
direction += Vec3::X;
}
_ => {}
}
}
let mut velocity = query.single_mut();
velocity.change_direction_speed(direction, PLAYER_SPEED);
}