feat(player): add tile movement

This commit is contained in:
Kristofers Solo 2024-12-10 17:22:04 +02:00
parent 0fb3504b81
commit 4ac52cfb38
3 changed files with 43 additions and 16 deletions

View File

@ -1,7 +1,20 @@
use bevy::prelude::*;
use hexx::Hex;
#[derive(Component, Debug, Clone, Copy, PartialEq, Default, Reflect)]
#[derive(Component, Debug, Clone, Copy, PartialEq, Reflect)]
#[reflect(Component)]
pub struct Player {
pub speed: f32,
pub current_hex: Hex,
pub target_hex: Option<Hex>,
}
impl Default for Player {
fn default() -> Self {
Self {
speed: 50.,
current_hex: Hex::ZERO,
target_hex: None,
}
}
}

View File

@ -1,7 +1,6 @@
use bevy::prelude::*;
use hexx::{EdgeDirection, Hex};
use crate::{maze::MazeConfig, player::components::Player};
use bevy::prelude::*;
use hexx::EdgeDirection;
const fn create_direction(key: &KeyCode) -> Option<EdgeDirection> {
match key {
@ -18,21 +17,36 @@ const fn create_direction(key: &KeyCode) -> Option<EdgeDirection> {
pub fn player_movement(
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&Player, &mut Transform)>,
mut player_query: Query<(&mut Player, &mut Transform)>,
maze_config: Res<MazeConfig>,
) {
for (player, mut transform) in player_query.iter_mut() {
let direction = input.get_pressed().find_map(|key| create_direction(key));
for (mut player, mut transform) in player_query.iter_mut() {
if let Some(direction) = input.get_pressed().find_map(|key| create_direction(key)) {
let next_hex = player.current_hex + direction.into_hex();
player.target_hex = Some(next_hex);
}
if let Some(hex_dir) = direction {
let hex_vec = Hex::from(hex_dir);
let world_pos = maze_config.layout.hex_to_world_pos(hex_vec);
if let Some(target_hex) = player.target_hex {
let current_pos = transform.translation;
let target_pos = {
let world_pos = maze_config.layout.hex_to_world_pos(target_hex);
Vec3::new(world_pos.x, current_pos.y, world_pos.y)
};
let direction = target_pos - current_pos;
let distance = direction.length();
let move_vec = Vec3::new(world_pos.x, 0.0, world_pos.y).normalize()
* player.speed
* time.delta_seconds();
transform.translation += move_vec;
if distance < 0.1 {
transform.translation = target_pos;
player.current_hex = target_hex;
player.target_hex = None;
} else {
let movement = direction.normalize() * player.speed * time.delta_seconds();
if movement.length() > distance {
transform.translation = target_pos;
} else {
transform.translation += movement;
}
}
}
}
}

View File

@ -18,7 +18,7 @@ pub fn spawn_player(
commands.spawn((
Name::new("Player"),
Player { speed: 50. },
Player::default(),
PbrBundle {
mesh: meshes.add(generate_pill_mesh(player_radius, player_height / 2.)),
material: materials.add(blue_material()),