smooth camera follow

This commit is contained in:
Nixon 2022-08-24 16:47:09 +08:00
parent 6809a30faa
commit 135fc268aa

View file

@ -303,11 +303,13 @@ fn win_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
} }
fn move_camera( fn move_camera(
mut camera_query: Query<(&Camera, &mut Transform, &GlobalTransform)>, mut camera_query: Query<(&Camera, &mut Transform)>,
characters: Query<(&CharacterId, &Transform), Without<Camera>>, characters: Query<(&CharacterId, &Transform), Without<Camera>>,
level_query: Query<&SelectedCharacterId>, level_query: Query<&SelectedCharacterId>,
time: Res<Time>,
) { ) {
const MARGIN: f32 = 128.0; const MARGIN: f32 = 300.0;
const FOLLOW_SPEED: f32 = std::f32::consts::PI;
if let Ok(selected_character_id) = level_query.get_single() { if let Ok(selected_character_id) = level_query.get_single() {
if let Some(selected_character_id) = &selected_character_id.0 { if let Some(selected_character_id) = &selected_character_id.0 {
@ -315,25 +317,14 @@ fn move_camera(
.iter() .iter()
.find(|(character_id, _transform)| *character_id == selected_character_id) .find(|(character_id, _transform)| *character_id == selected_character_id)
{ {
let (camera, mut camera_transform, camera_global_transform) = let (camera, mut camera_transform) =
camera_query.single_mut(); camera_query.single_mut();
let pos = camera let size: Vec2 = camera.logical_viewport_size().unwrap();
.world_to_viewport(camera_global_transform, transform.translation) let half_height: f32 = size.y * 0.5;
.unwrap(); camera_transform.translation = camera_transform.translation.lerp(transform.translation, time.delta_seconds() * FOLLOW_SPEED);
let size = camera.logical_viewport_size().unwrap(); // prevent camera from going too low
if pos.x < MARGIN { camera_transform.translation.y = camera_transform.translation.y.max(half_height-MARGIN);
camera_transform.translation.x += pos.x - MARGIN;
}
if pos.x > size.x - MARGIN {
camera_transform.translation.x += MARGIN + pos.x - size.x;
}
if pos.y < MARGIN {
camera_transform.translation.y += pos.y - MARGIN;
}
if pos.y > size.y - MARGIN {
camera_transform.translation.y += MARGIN + pos.y - size.y;
}
} }
} }
} }