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(
mut camera_query: Query<(&Camera, &mut Transform, &GlobalTransform)>,
mut camera_query: Query<(&Camera, &mut Transform)>,
characters: Query<(&CharacterId, &Transform), Without<Camera>>,
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 Some(selected_character_id) = &selected_character_id.0 {
@ -315,25 +317,14 @@ fn move_camera(
.iter()
.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();
let pos = camera
.world_to_viewport(camera_global_transform, transform.translation)
.unwrap();
let size = camera.logical_viewport_size().unwrap();
if pos.x < 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;
}
let size: Vec2 = camera.logical_viewport_size().unwrap();
let half_height: f32 = size.y * 0.5;
camera_transform.translation = camera_transform.translation.lerp(transform.translation, time.delta_seconds() * FOLLOW_SPEED);
// prevent camera from going too low
camera_transform.translation.y = camera_transform.translation.y.max(half_height-MARGIN);
}
}
}