src/camera_controller.rs
+72
-0
diff --git a/src/camera_controller.rs b/src/camera_controller.rs
new file mode 100644
index 0000000..329c281
@@ -0,0 +1,72 @@
use bevy::{
app::{App, Plugin, Update},
camera::Camera,
ecs::{
query::With,
resource::Resource,
system::{Res, Single},
},
input::{ButtonInput, keyboard::KeyCode},
math::Vec3,
transform::components::Transform,
};
pub struct CameraControllerPlugin {
origin: Vec3,
target: Vec3,
}
impl CameraControllerPlugin {
pub fn new(origin: Vec3, target: Vec3) -> Self {
Self { origin, target }
}
}
impl Plugin for CameraControllerPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(CameraSettings {
origin: self.origin,
target: self.target,
})
.add_systems(Update, move_camera_with_keyboard);
}
}
#[derive(Resource)]
struct CameraSettings {
origin: Vec3,
target: Vec3,
}
fn move_camera_with_keyboard(
settings: Res<CameraSettings>,
mut camera: Single<&mut Transform, With<Camera>>,
input: Res<ButtonInput<KeyCode>>,
) {
let mut origin = settings.origin;
camera.translation = origin;
camera.look_at(settings.target, Vec3::Y);
if input.pressed(KeyCode::KeyS) {
origin += camera.local_z().as_vec3();
}
if input.pressed(KeyCode::KeyW) {
origin -= camera.local_z().as_vec3();
}
if input.pressed(KeyCode::KeyD) {
origin += camera.local_x().as_vec3();
}
if input.pressed(KeyCode::KeyA) {
origin -= camera.local_x().as_vec3();
}
if input.pressed(KeyCode::KeyE) {
origin += camera.local_y().as_vec3();
}
if input.pressed(KeyCode::KeyQ) {
origin -= camera.local_y().as_vec3();
}
camera.translation = origin;
camera.look_at(settings.target, Vec3::Y);
}
src/main.rs
+9
-2
diff --git a/src/main.rs b/src/main.rs
index 5185e10..81fea26 100644
@@ -1,3 +1,5 @@
mod camera_controller;
use std::f32::consts::FRAC_PI_4;
use bevy::{
@@ -19,9 +21,14 @@ use bevy::{
world_serialization::WorldAssetRoot,
};
use crate::camera_controller::CameraControllerPlugin;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins((
DefaultPlugins,
CameraControllerPlugin::new(Vec3::new(-7.0, 3.3, 14.0), Vec3::new(-6.5, 3.1, 13.1)),
))
.add_systems(Startup, setup)
.add_systems(Update, load_skybox)
.run();
@@ -36,7 +43,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
fov: FRAC_PI_4,
..Default::default()
}),
Transform::from_xyz(-7.0, 3.3, 14.0).looking_to(Vec3::new(0.6, 0.0, -0.8), Vec3::Y),
Transform::IDENTITY,
Skybox {
image: Some(handle),
brightness: 1000.0,