Skip to main content

bevy_dev_tools/
easy_camera.rs

1use bevy_app::{App, Plugin, PostUpdate};
2use bevy_camera::Camera;
3use bevy_ecs::prelude::*;
4use bevy_math::{Quat, StableInterpolate, Vec3};
5use bevy_time::Time;
6use bevy_transform::{components::Transform, TransformSystems};
7
8/// Plugin to move the camera smoothly according to the current time
9pub struct EasyCameraMovementPlugin {
10    /// Decay rate for the camera movement
11    pub decay_rate: f32,
12}
13
14impl Default for EasyCameraMovementPlugin {
15    fn default() -> Self {
16        Self { decay_rate: 1.0 }
17    }
18}
19
20/// Move the camera to the given position
21#[derive(impl bevy_ecs::component::Component for CameraMovement where
    Self: ::core::marker::Send + ::core::marker::Sync + 'static {
    const STORAGE_TYPE: bevy_ecs::component::StorageType =
        bevy_ecs::component::StorageType::Table;
    type Mutability = bevy_ecs::component::Mutable;
    fn register_required_components(_requiree:
            bevy_ecs::component::ComponentId,
        required_components:
            &mut bevy_ecs::component::RequiredComponentsRegistrator) {}
    fn clone_behavior() -> bevy_ecs::component::ComponentCloneBehavior {
        use bevy_ecs::component::{
            DefaultCloneBehaviorBase, DefaultCloneBehaviorViaClone,
        };
        (&&&bevy_ecs::component::DefaultCloneBehaviorSpecialization::<Self>::default()).default_clone_behavior()
    }
    fn relationship_accessor()
        ->
            ::core::option::Option<bevy_ecs::relationship::ComponentRelationshipAccessor<Self>> {
        ::core::option::Option::None
    }
}Component)]
22pub struct CameraMovement {
23    /// Target position for the camera movement
24    pub translation: Vec3,
25    /// Target rotation for the camera movement
26    pub rotation: Quat,
27}
28
29impl Plugin for EasyCameraMovementPlugin {
30    fn build(&self, app: &mut App) {
31        let decay_rate = self.decay_rate;
32        app.add_systems(
33            PostUpdate,
34            (move |mut query: Single<(&mut Transform, &CameraMovement), With<Camera>>,
35                   time: Res<Time>| {
36                {
37                    {
38                        let target = query.1;
39                        query.0.translation.smooth_nudge(
40                            &target.translation,
41                            decay_rate,
42                            time.delta_secs(),
43                        );
44                        query.0.rotation.smooth_nudge(
45                            &target.rotation,
46                            decay_rate,
47                            time.delta_secs(),
48                        );
49                    }
50                }
51            })
52            .before(TransformSystems::Propagate),
53        );
54    }
55}