cyber_rider/src/camera.rs

111 lines
3.2 KiB
Rust
Raw Normal View History

2023-01-20 22:40:51 +00:00
use bevy::prelude::*;
use crate::{bike::CyberBikeModel, input::InputState};
// 85 degrees in radians
const MAX_PITCH: f32 = 1.48353;
#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Component)]
enum CyberCameras {
Hero,
Debug,
}
impl CyberCameras {
fn next(self) -> Self {
match self {
CyberCameras::Debug => CyberCameras::Hero,
CyberCameras::Hero => CyberCameras::Debug,
}
}
}
fn setup_cybercams(mut commands: Commands) {
let hero_projection = PerspectiveProjection {
fov: std::f32::consts::FRAC_PI_3,
..Default::default()
};
commands
2023-01-20 22:40:51 +00:00
.spawn(Camera3dBundle {
projection: bevy::render::camera::Projection::Perspective(hero_projection),
..Default::default()
})
.insert(CyberCameras::Hero);
commands
2023-01-20 22:40:51 +00:00
.spawn(Camera3dBundle::default())
.insert(CyberCameras::Debug);
}
fn follow_cyberbike(
mut query: ParamSet<(
// 0: the bike
Query<&Transform, With<CyberBikeModel>>,
// 1: the cameras
Query<(&mut Transform, &CyberCameras)>,
)>,
input: Res<InputState>,
) {
let bike_xform = *query.p0().single();
let up = bike_xform.translation.normalize();
for (mut cam_xform, cam_type) in query.p1().iter_mut() {
match *cam_type {
CyberCameras::Hero => {
let look_at = bike_xform.translation + (bike_xform.forward() * 200.0);
2023-01-21 07:05:43 +00:00
let cam_pos = bike_xform.translation + (bike_xform.back() * 1.05) + (up * 1.08);
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));
}
CyberCameras::Debug => {
let pos = bike_xform.translation
2023-01-21 07:33:21 +00:00
+ (bike_xform.forward() * 9.0)
2023-01-21 07:05:43 +00:00
+ (bike_xform.left() * 10.0)
+ (bike_xform.up() * 5.0);
cam_xform.translation = pos;
cam_xform.look_at(bike_xform.translation, up);
}
}
}
}
fn update_active_camera(
state: Res<State<CyberCameras>>,
mut query: Query<(&mut Camera, &CyberCameras)>,
) {
// find the camera with the current state, set it as the ActiveCamera
query.iter_mut().for_each(|(mut cam, cyber)| {
if cyber.eq(state.current()) {
cam.is_active = true;
} else {
cam.is_active = false;
}
});
}
fn cycle_cam_state(mut state: ResMut<State<CyberCameras>>, mut keys: ResMut<Input<KeyCode>>) {
if keys.just_pressed(KeyCode::D) {
let new_state = state.current().next();
info!("{:?}", new_state);
state.set(new_state).unwrap();
keys.reset(KeyCode::D);
}
}
pub struct CyberCamPlugin;
impl Plugin for CyberCamPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.add_startup_system(setup_cybercams)
2022-03-14 06:37:11 +00:00
.add_state(CyberCameras::Hero)
.add_system(cycle_cam_state)
.add_system(update_active_camera)
.add_system(follow_cyberbike);
}
}