moria/src/camera.rs

59 lines
1.7 KiB
Rust

use bevy::prelude::*;
use bevy_mod_raycast::{RayCastMethod, RayCastSource};
use crate::player::*;
pub struct MyRaycastSet;
pub struct Camera;
pub fn spawn_camera(commands: &mut Commands) {
commands
.spawn_bundle(PerspectiveCameraBundle::default())
.insert(Camera)
.insert(RayCastSource::<MyRaycastSet>::new());
}
pub fn camera_follow_player(
player: Query<(&Transform, &Player), Without<Camera>>,
mut camera: Query<(&mut Transform, &Camera), Without<Player>>,
) {
let player_pos = if let Some(player) = player.iter().next() {
player.0.translation
} else {
return;
};
for (mut trans, _) in camera.iter_mut() {
trans.translation = player_pos + Vec3::new(-50.0, 100.0, 50.0);
trans.look_at(player_pos, Vec3::Y);
}
}
// update our `RayCastSource` with the current cursor position every frame.
pub fn update_raycast_with_cursor(
mut cursor: EventReader<CursorMoved>,
mut query: Query<&mut RayCastSource<MyRaycastSet>>,
) {
for mut pick_source in query.iter_mut() {
// Grab the most recent cursor event if it exists:
if let Some(cursor_latest) = cursor.iter().last() {
pick_source.cast_method = RayCastMethod::Screenspace(cursor_latest.position);
}
}
}
#[derive(Default)]
pub struct MouseCoords(pub Vec3);
// Update our `RayCastSource` with the current cursor position every frame.
pub fn update_mouse_coords(
query: Query<&RayCastSource<MyRaycastSet>>,
mut coords: ResMut<MouseCoords>,
) {
for pick_source in query.iter() {
if let Some((_, intersection)) = pick_source.intersect_top() {
coords.0 = intersection.position();
}
}
}