From 58a7b56f438d100446e4044b156dde2af1695b58 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Wed, 20 Dec 2023 19:35:59 -0600 Subject: [PATCH] WIP movement component stuff --- src/movement.rs | 18 +++++++++++------- src/player.rs | 32 ++++++++++++++++++-------------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/movement.rs b/src/movement.rs index 4684d78..d118869 100644 --- a/src/movement.rs +++ b/src/movement.rs @@ -3,19 +3,21 @@ 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); +pub struct Velocity(pub Vec2); impl Velocity { pub fn from_speed_heading(heading: Vec2, speed: f32) -> Self { Self(heading.normalize_or_zero() * speed) } +} +#[derive(Component, Debug, Default)] +pub struct Heading(pub Vec2); + +#[derive(Component, Debug, Default)] +pub struct Speed(pub f32); + +impl Heading { pub fn new(x: f32, y: f32) -> Self { Self(Vec2::new(x, y)) } @@ -24,6 +26,8 @@ impl Velocity { #[derive(Bundle, Debug, Default)] pub struct MovementBundle { pub velocity: Velocity, + pub heading: Heading, + pub speed: Speed, } impl Plugin for MovementPlugin { diff --git a/src/player.rs b/src/player.rs index fc4058c..7eb1e0b 100644 --- a/src/player.rs +++ b/src/player.rs @@ -2,7 +2,7 @@ use bevy::prelude::*; use crate::{ assets::Assets, - movement::{MovementBundle, Velocity}, + movement::{Heading, MovementBundle, Speed, Velocity}, }; const PLAYER_SPEED: f32 = 50.; @@ -19,39 +19,43 @@ impl Plugin for PlayerPlugin { #[derive(Component, Debug)] pub struct Player; -fn spawn_player(mut commands: Commands, sprite_assets: Res) { +fn spawn_player(mut commands: Commands, assets: Res) { commands.spawn(( Player, SpriteBundle { - texture: sprite_assets.knight.clone(), + texture: assets.sprites.square.clone(), transform: Transform::from_xyz(0., 0., 0.), ..Default::default() }, MovementBundle { - velocity: Velocity::new(0., 0.), + velocity: Velocity(Vec2::ZERO), + heading: Heading(Vec2::ZERO), + speed: Speed(PLAYER_SPEED), }, )); } -fn player_movement(mut query: Query<&mut Velocity, With>, input: Res>) { - let mut direction = Vec3::ZERO; +fn player_movement( + mut query: Query<(&mut Velocity, &Speed, &mut Heading), With>, + input: Res>, +) { + let (mut velocity, speed, mut heading) = query.single_mut(); + heading = Vec2::ZERO; for key in input.get_pressed() { match key { KeyCode::W | KeyCode::Up => { - direction += Vec3::Y; - } - KeyCode::A | KeyCode::Left => { - direction += Vec3::NEG_X; + heading += Vec3::Y; } KeyCode::S | KeyCode::Down => { - direction += Vec3::NEG_Y; + heading -= Vec3::Y; + } + KeyCode::A | KeyCode::Left => { + heading -= Vec3::X; } KeyCode::D | KeyCode::Right => { - direction += Vec3::X; + heading += Vec3::X; } _ => {} } } - let mut velocity = query.single_mut(); - velocity.change_direction_speed(direction, PLAYER_SPEED); }