cyber_rider/src/camera.rs

64 lines
2 KiB
Rust
Raw Normal View History

use bevy::prelude::*;
use crate::{geometry::CyberBike, input::InputState, physics::MovementSettings};
pub(crate) const CAM_DIST: f32 = 50.0;
#[derive(Component, Debug)]
pub struct CyberCam;
fn setup_cybercam(mut commands: Commands) {
use crate::geometry::PLAYER_DIST;
commands
.spawn_bundle(PerspectiveCameraBundle {
transform: Transform::from_xyz(PLAYER_DIST + CAM_DIST, 0.0, 0.0)
.looking_at(Vec3::ZERO, Vec3::Y),
..Default::default()
})
.insert(CyberCam);
}
fn follow_player(
bike_query: Query<(&Transform, &CyberBike), Without<CyberCam>>,
mut cam_query: Query<(&mut Transform, &CyberCam), Without<CyberBike>>,
) {
let (bike_xform, _) = bike_query.single();
let up = bike_xform.translation.normalize();
let look_at = bike_xform.translation;
let cam_pos = bike_xform.translation + (bike_xform.back() * CAM_DIST * 1.3) + (up * CAM_DIST);
let (mut cam_xform, _) = cam_query.single_mut();
cam_xform.translation = cam_pos;
cam_xform.look_at(look_at, up);
}
fn player_look(
settings: Res<MovementSettings>,
windows: Res<Windows>,
time: Res<Time>,
istate: Res<InputState>,
mut query: Query<(&mut Transform, &CyberBike)>,
) {
let window = windows.get_primary().unwrap();
let window_scale = window.height().min(window.width());
let dt = time.delta_seconds();
let (mut transform, _) = query.single_mut();
let d_alt = (settings.sensitivity * dt * window_scale * istate.pitch).to_radians();
let d_az = (settings.sensitivity * dt * window_scale * istate.yaw).to_radians();
let rotation = Quat::from_axis_angle(transform.local_y(), d_az)
* Quat::from_axis_angle(transform.local_x(), d_alt);
transform.rotate(rotation);
}
pub struct CyberCamPlugin;
impl Plugin for CyberCamPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.add_startup_system(setup_cybercam)
.add_system(follow_player)
.add_system(player_look);
}
}