WIP movement component stuff

This commit is contained in:
Daniel Flanagan 2023-12-20 19:35:59 -06:00
parent 4371f02949
commit 58a7b56f43
Signed by: lytedev
GPG key ID: 5B2020A0F9921EF4
2 changed files with 29 additions and 21 deletions

View file

@ -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 {

View file

@ -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<SpriteAssets>) {
fn spawn_player(mut commands: Commands, assets: Res<Assets>) {
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<Player>>, input: Res<Input<KeyCode>>) {
let mut direction = Vec3::ZERO;
fn player_movement(
mut query: Query<(&mut Velocity, &Speed, &mut Heading), With<Player>>,
input: Res<Input<KeyCode>>,
) {
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);
}