2023-01-25 20:28:05 -06:00
|
|
|
use glam::{Vec3, Mat4, Quat, EulerRot, Vec2};
|
|
|
|
use shipyard::{Component, View, ViewMut, IntoIter, UniqueView, Workload, IntoWorkload};
|
|
|
|
use std::f32::consts::PI;
|
2023-01-24 20:52:54 -06:00
|
|
|
use crate::{transform::Transform, input::Inputs, settings::GameSettings};
|
2023-01-24 20:36:24 -06:00
|
|
|
|
|
|
|
#[derive(Component)]
|
|
|
|
pub struct FlyController;
|
|
|
|
|
2023-01-25 20:28:05 -06:00
|
|
|
pub fn update_controllers() -> Workload {
|
|
|
|
(
|
|
|
|
update_look,
|
|
|
|
update_movement
|
|
|
|
).into_workload()
|
|
|
|
}
|
|
|
|
|
|
|
|
const MAX_PITCH: f32 = PI/2. - 0.001;
|
|
|
|
|
|
|
|
fn update_look(
|
2023-01-24 20:36:24 -06:00
|
|
|
controllers: View<FlyController>,
|
|
|
|
mut transforms: ViewMut<Transform>,
|
2023-01-24 20:52:54 -06:00
|
|
|
inputs: UniqueView<Inputs>,
|
|
|
|
settings: UniqueView<GameSettings>,
|
2023-01-24 20:36:24 -06:00
|
|
|
) {
|
2023-01-25 20:28:05 -06:00
|
|
|
let look = inputs.look * settings.mouse_sensitivity;
|
|
|
|
if look == Vec2::ZERO { return }
|
2023-01-24 20:36:24 -06:00
|
|
|
for (_, mut transform) in (&controllers, &mut transforms).iter() {
|
2023-01-25 20:28:05 -06:00
|
|
|
let (scale, mut rotation, translation) = transform.0.to_scale_rotation_translation();
|
|
|
|
let (mut yaw, mut pitch, _roll) = rotation.to_euler(EulerRot::YXZ);
|
|
|
|
yaw -= look.x;
|
|
|
|
pitch -= look.y;
|
|
|
|
pitch = pitch.clamp(-MAX_PITCH, MAX_PITCH);
|
|
|
|
rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, 0.);
|
|
|
|
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation, translation);
|
|
|
|
}
|
|
|
|
}
|
2023-01-25 20:05:29 -06:00
|
|
|
|
2023-01-25 20:28:05 -06:00
|
|
|
fn update_movement(
|
|
|
|
controllers: View<FlyController>,
|
|
|
|
mut transforms: ViewMut<Transform>,
|
2023-01-25 20:28:17 -06:00
|
|
|
inputs: UniqueView<Inputs>
|
2023-01-25 20:28:05 -06:00
|
|
|
) {
|
|
|
|
let movement = inputs.movement;
|
|
|
|
if movement == Vec2::ZERO { return }
|
|
|
|
for (_, mut transform) in (&controllers, &mut transforms).iter() {
|
|
|
|
let (scale, rotation, mut translation) = transform.0.to_scale_rotation_translation();
|
|
|
|
translation += (rotation * Vec3::NEG_Z) * movement.y;
|
|
|
|
translation += (rotation * Vec3::X) * movement.x;
|
2023-01-24 20:36:24 -06:00
|
|
|
transform.0 = Mat4::from_scale_rotation_translation(scale, rotation, translation);
|
|
|
|
}
|
|
|
|
}
|