diff options
author | HampusM <hampus@hampusmat.com> | 2023-10-25 21:15:41 +0200 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2023-10-25 21:16:10 +0200 |
commit | fd535654369b31e1283a609ba8e8fcf0df42100b (patch) | |
tree | 2509bd71d835a4389ff7578dc6314d6019e31d01 /engine/src/matrix.rs | |
parent | 0c0dc186b542bf6bdd7645ba091dc2a47a03fa97 (diff) |
feat(engine): make camera look at a target position
Diffstat (limited to 'engine/src/matrix.rs')
-rw-r--r-- | engine/src/matrix.rs | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/engine/src/matrix.rs b/engine/src/matrix.rs index c060b59..85a3721 100644 --- a/engine/src/matrix.rs +++ b/engine/src/matrix.rs @@ -71,4 +71,39 @@ impl Matrix<f32, 4, 4> self.set_cell(2, 2, scaling.z); self.set_cell(3, 3, 1.0); } + + pub fn look_at(&mut self, eye: &Vec3<f32>, target: &Vec3<f32>, up: &Vec3<f32>) + { + let rev_target_direction = (eye - target).normalize(); + + let camera_right = up.cross(&rev_target_direction).normalize(); + + let camera_up = rev_target_direction.cross(&camera_right); + + self.set_cell(0, 0, camera_right.x); + self.set_cell(0, 1, camera_right.y); + self.set_cell(0, 2, camera_right.z); + + self.set_cell(1, 0, camera_up.x); + self.set_cell(1, 1, camera_up.y); + self.set_cell(1, 2, camera_up.z); + + self.set_cell(2, 0, rev_target_direction.x); + self.set_cell(2, 1, rev_target_direction.y); + self.set_cell(2, 2, rev_target_direction.z); + + // The vector is negated since we want the world to be translated in the opposite + // direction of where we want the camera to move. + let camera_pos = -Vec3 { + x: camera_right.dot(eye), + y: camera_up.dot(eye), + z: rev_target_direction.dot(eye), + }; + + self.set_cell(0, 3, camera_pos.x); + self.set_cell(1, 3, camera_pos.y); + self.set_cell(2, 3, camera_pos.z); + + self.set_cell(3, 3, 1.0); + } } |