ttt-ce/src/player_utils/player_look.rs
2024-04-05 21:43:43 +02:00

97 lines
2.8 KiB
Rust

/*
Trouble in Terror Town: Community Edition
Copyright (C) 2024 Mikolaj Wojciech Gorski
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License 3.0 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License 3.0 for more details.
You should have received a copy of the GNU General Public License 3.0
along with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
*/
use bevy::math::Quat;
use crate::player_utils::input_processor::*;
use bevy::{
input::mouse::MouseMotion,
prelude::*,
math::*,
};
pub struct PlayerLookPlugin;
impl Plugin for PlayerLookPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, rotate_camera);
app.add_event::<LookAction>();
}
}
// marker for rotating player horizontally
#[derive(Component)]
pub struct PlayerLookRotatable;
#[derive(Component)]
pub struct PlayerCamera {
mouse_gain: f32,
rotation: Vec3,
rotation_limit_top: f32,
rotation_limit_bottom: f32,
}
impl Default for PlayerCamera {
fn default() -> Self {
Self {
mouse_gain: 0.005,
rotation: Vec3 {
x: 0.0,
y: 0.0,
z: 0.0,
},
rotation_limit_top: 1.0,
rotation_limit_bottom: -1.0,
}
}
}
fn rotate_camera(
time: Res<Time>,
mut mouse_motion_events: EventReader<MouseMotion>,
mut camera_query: Query<(&mut Transform, &mut PlayerCamera), With<Camera3d>>,
mut rotatable_query: Query<
&mut Transform,
(With<PlayerLookRotatable>, Without<PlayerCamera>),
>,
mut gizmos: Gizmos,
) {
let delta_time = time.delta_seconds_f64();
for (mut transform, mut camera) in &mut camera_query {
for event in mouse_motion_events.read() {
for mut rotatable in &mut rotatable_query {
camera.rotation.x -= event.delta.y * camera.mouse_gain;
camera.rotation.x = f32::clamp(
camera.rotation.x,
camera.rotation_limit_bottom,
camera.rotation_limit_top,
);
let x_rotation = Quat::from_axis_angle(Vec3::X, camera.rotation.x);
info!("{}", x_rotation);
transform.rotation = x_rotation;
camera.rotation.y -= event.delta.x * camera.mouse_gain;
let y_rotation = Quat::from_axis_angle(Vec3::Y, camera.rotation.y);
info!("{}", y_rotation);
rotatable.rotation = y_rotation;
}
}
}
}