Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add orbit_smoothness option, fix bug, and add animation example #10

Merged
merged 6 commits into from
Apr 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Default controls:
- Works with orthographic camera projection in addition to perspective
- Customisable controls, sensitivity, and more
- Works with multiple viewports and/or windows
- Easy to animate, e.g. to slowly rotate around an object

## Quick Start

Expand Down
65 changes: 65 additions & 0 deletions examples/animate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//! Demonstrates how you can animate the movement of the camera

use bevy::prelude::*;
use bevy_panorbit_camera::{PanOrbitCamera, PanOrbitCameraPlugin};
use std::f32::consts::TAU;

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugin(PanOrbitCameraPlugin)
.add_startup_system(setup)
.add_system(animate)
.run();
}

fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// Ground
commands.spawn(PbrBundle {
mesh: meshes.add(shape::Plane::from_size(5.0).into()),
material: materials.add(Color::rgb(0.3, 0.5, 0.3).into()),
..default()
});
// Cube
commands.spawn(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: materials.add(Color::rgb(0.8, 0.7, 0.6).into()),
transform: Transform::from_xyz(0.0, 0.5, 0.0),
..default()
});
// Light
commands.spawn(PointLightBundle {
point_light: PointLight {
intensity: 1500.0,
shadows_enabled: true,
..default()
},
transform: Transform::from_xyz(4.0, 8.0, 4.0),
..default()
});
// Camera
commands.spawn((
Camera3dBundle::default(),
PanOrbitCamera {
// Optionally disable smoothing to have full control over the camera's position
// orbit_smoothness: 0.0,
// Might want to disable the controls
enabled: false,
..default()
},
));
}

// Animate the camera's position
fn animate(time: Res<Time>, mut pan_orbit_query: Query<&mut PanOrbitCamera>) {
for mut pan_orbit in pan_orbit_query.iter_mut() {
// Must set target values, not alpha/beta directly
pan_orbit.target_alpha += 15f32.to_radians() * time.delta_seconds();
pan_orbit.target_beta = time.elapsed_seconds_wrapped().sin() * TAU * 0.1;
pan_orbit.radius = (((time.elapsed_seconds_wrapped() * 2.0).cos() + 1.0) * 0.5) * 2.0 + 4.0;
}
}
38 changes: 19 additions & 19 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct PanOrbitCameraPlugin;

impl Plugin for PanOrbitCameraPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(ActiveViewportData::default())
app.insert_resource(ActiveCameraData::default())
.add_systems(
(active_viewport_data, pan_orbit_camera)
.chain()
Expand Down Expand Up @@ -117,6 +117,10 @@ pub struct PanOrbitCamera {
pub beta_lower_limit: Option<f32>,
/// The sensitivity of the orbiting motion. Defaults to `1.0`.
pub orbit_sensitivity: f32,
/// How much smoothing is applied to the orbit motion. A value of `0.0` disables smoothing,
/// so there's a 1:1 mapping of input to camera position. A value of `1.0` is infinite
/// smoothing. Defaults to `0.8`.
pub orbit_smoothness: f32,
/// The sensitivity of the panning motion. Defaults to `1.0`.
pub pan_sensitivity: f32,
/// The sensitivity of moving the camera closer or further way using the scroll wheel. Defaults to `1.0`.
Expand Down Expand Up @@ -151,6 +155,7 @@ impl Default for PanOrbitCamera {
is_upside_down: false,
allow_upside_down: false,
orbit_sensitivity: 1.0,
orbit_smoothness: 0.8,
pan_sensitivity: 1.0,
zoom_sensitivity: 1.0,
button_orbit: MouseButton::Left,
Expand Down Expand Up @@ -221,7 +226,7 @@ impl PanOrbitCamera {
// Tracks the camera entity that should be handling input events.
// This enables having multiple cameras with different viewports or windows.
#[derive(Resource, Default, Debug, PartialEq)]
struct ActiveViewportData {
struct ActiveCameraData {
entity: Option<Entity>,
viewport_size: Option<Vec2>,
window_size: Option<Vec2>,
Expand All @@ -230,15 +235,15 @@ struct ActiveViewportData {
// Gathers data about the active viewport, i.e. the viewport the user is interacting with. This
// enables multiple viewports/windows.
fn active_viewport_data(
mut active_entity: ResMut<ActiveViewportData>,
mut active_cam: ResMut<ActiveCameraData>,
mouse_input: Res<Input<MouseButton>>,
key_input: Res<Input<KeyCode>>,
scroll_events: EventReader<MouseWheel>,
primary_windows: Query<&Window, With<PrimaryWindow>>,
other_windows: Query<&Window, Without<PrimaryWindow>>,
orbit_cameras: Query<(Entity, &Camera, &PanOrbitCamera)>,
) {
let mut new_resource: Option<ActiveViewportData> = None;
let mut new_resource: Option<ActiveCameraData> = None;
let mut max_cam_order = 0;

for (entity, camera, pan_orbit) in orbit_cameras.iter() {
Expand Down Expand Up @@ -271,7 +276,7 @@ fn active_viewport_data(
// Only set if camera order is higher. This may overwrite a previous value
// in the case the viewport overlapping another viewport.
if cursor_in_vp && camera.order >= max_cam_order {
new_resource = Some(ActiveViewportData {
new_resource = Some(ActiveCameraData {
entity: Some(entity),
viewport_size: camera.logical_viewport_size(),
window_size: Some(Vec2::new(window.width(), window.height())),
Expand All @@ -285,13 +290,13 @@ fn active_viewport_data(
}

if let Some(new_resource) = new_resource {
active_entity.set_if_neq(new_resource);
active_cam.set_if_neq(new_resource);
}
}

/// Main system for processing input and converting to transformations
fn pan_orbit_camera(
active_viewport_data: Res<ActiveViewportData>,
active_cam: Res<ActiveCameraData>,
mouse_input: Res<Input<MouseButton>>,
key_input: Res<Input<KeyCode>>,
mut mouse_motion: EventReader<MouseMotion>,
Expand Down Expand Up @@ -330,20 +335,14 @@ fn pan_orbit_camera(
continue;
}

// Abort early if this camera not active. Do this after initializing so cameras are always
// initialized.
if active_viewport_data.entity != Some(entity) {
continue;
}

// 1 - Get Input

let mut pan = Vec2::ZERO;
let mut rotation_move = Vec2::ZERO;
let mut scroll = 0.0;
let mut orbit_button_changed = false;

if pan_orbit.enabled {
if pan_orbit.enabled && active_cam.entity == Some(entity) {
if orbit_pressed(&pan_orbit, &mouse_input, &key_input) {
rotation_move += mouse_delta * pan_orbit.orbit_sensitivity;
} else if pan_pressed(&pan_orbit, &mouse_input, &key_input) {
Expand Down Expand Up @@ -383,7 +382,7 @@ fn pan_orbit_camera(
if rotation_move.length_squared() > 0.0 {
// Use window size for rotation otherwise the sensitivity
// is far too high for small viewports
if let Some(win_size) = active_viewport_data.window_size {
if let Some(win_size) = active_cam.window_size {
let delta_x = {
let delta = rotation_move.x / win_size.x * PI * 2.0;
if pan_orbit.is_upside_down {
Expand Down Expand Up @@ -429,7 +428,7 @@ fn pan_orbit_camera(
}
} else if pan.length_squared() > 0.0 {
// Make panning distance independent of resolution and FOV,
if let Some(vp_size) = active_viewport_data.viewport_size {
if let Some(vp_size) = active_cam.viewport_size {
let mut multiplier = 1.0;
match *projection {
Projection::Perspective(ref p) => {
Expand Down Expand Up @@ -470,9 +469,10 @@ fn pan_orbit_camera(
|| pan_orbit.target_alpha != pan_orbit.alpha
|| pan_orbit.target_beta != pan_orbit.beta
{
// Otherwise, interpolate our way there
let mut target_alpha = pan_orbit.alpha.lerp(&pan_orbit.target_alpha, &0.2);
let mut target_beta = pan_orbit.beta.lerp(&pan_orbit.target_beta, &0.2);
// Interpolate towards the target value
let t = 1.0 - pan_orbit.orbit_smoothness;
let mut target_alpha = pan_orbit.alpha.lerp(&pan_orbit.target_alpha, &t);
let mut target_beta = pan_orbit.beta.lerp(&pan_orbit.target_beta, &t);

// If we're super close, then just snap to target rotation to save cycles
if (target_alpha - pan_orbit.target_alpha).abs() < 0.001 {
Expand Down