cyber_rider/src/camera.rs

59 lines
1.7 KiB
Rust
Raw Normal View History

use bevy::prelude::*;
use crate::{
geometry::{CyberBike, SPAWN_ALTITUDE},
input::InputState,
};
2022-01-14 00:14:08 +00:00
pub(crate) const CAM_DIST: f32 = 15.0;
// 85 degrees in radians
const MAX_PITCH: f32 = 1.48353;
#[derive(Component, Debug)]
pub struct CyberCam;
fn setup_cybercam(mut commands: Commands) {
let projection = PerspectiveProjection {
fov: std::f32::consts::FRAC_PI_3,
..Default::default()
};
commands
.spawn_bundle(PerspectiveCameraBundle {
2022-01-14 00:14:08 +00:00
transform: Transform::from_xyz(SPAWN_ALTITUDE + CAM_DIST, 0.0, 0.0)
.looking_at(Vec3::ZERO, Vec3::Y),
perspective_projection: projection,
..Default::default()
})
.insert(CyberCam);
}
fn follow_cyberbike(
2022-01-14 00:14:08 +00:00
bike_query: Query<&Transform, (Without<CyberCam>, With<CyberBike>)>,
mut cam_query: Query<&mut Transform, (With<CyberCam>, Without<CyberBike>)>,
input: Res<InputState>,
) {
2022-01-14 00:14:08 +00:00
let bike_xform = bike_query.single();
let up = bike_xform.translation.normalize();
2022-01-14 06:05:51 +00:00
let look_at = bike_xform.translation + (bike_xform.forward() * 200.0);
let cam_pos = bike_xform.translation + (bike_xform.back() * 2.7) + (up * 2.4);
2022-01-14 00:14:08 +00:00
let mut cam_xform = cam_query.single_mut();
cam_xform.translation = cam_pos;
cam_xform.look_at(look_at, up);
// handle input pitch
let angle = input.pitch.powi(3) * MAX_PITCH;
let axis = cam_xform.right();
cam_xform.rotate(Quat::from_axis_angle(axis, angle));
}
pub struct CyberCamPlugin;
impl Plugin for CyberCamPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.add_startup_system(setup_cybercam)
.add_system(follow_cyberbike);
}
}