From 6892b2dc2b223dc8ed8a4953137cf826e27a6532 Mon Sep 17 00:00:00 2001 From: ira Date: Mon, 21 Nov 2022 13:19:43 +0000 Subject: [PATCH] Add `Transform::look_to` (#6692) Add a method to rotate a transform to point towards a direction. Also updated the docs to link to `forward` and `up` instead of mentioning local negative `Z` and local `Y`. Unfortunately, links to methods don't work in rust-analyzer :( Co-authored-by: Devil Ira --- .../src/components/transform.rs | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/bevy_transform/src/components/transform.rs b/crates/bevy_transform/src/components/transform.rs index 439f3c53a1e05..a94ff06bda17a 100644 --- a/crates/bevy_transform/src/components/transform.rs +++ b/crates/bevy_transform/src/components/transform.rs @@ -117,9 +117,8 @@ impl Transform { } } - /// Updates and returns this [`Transform`] by rotating it so that its unit - /// vector in the local negative `Z` direction is toward `target` and its - /// unit vector in the local `Y` direction is toward `up`. + /// Returns this [`Transform`] with a new rotation so that [`Transform::forward`] + /// points towards the `target` position and [`Transform::up`] points towards `up`. #[inline] #[must_use] pub fn looking_at(mut self, target: Vec3, up: Vec3) -> Self { @@ -127,6 +126,15 @@ impl Transform { self } + /// Returns this [`Transform`] with a new rotation so that [`Transform::forward`] + /// points in the given `direction` and [`Transform::up`] points towards `up`. + #[inline] + #[must_use] + pub fn looking_to(mut self, direction: Vec3, up: Vec3) -> Self { + self.look_to(direction, up); + self + } + /// Returns this [`Transform`] with a new translation. #[inline] #[must_use] @@ -314,11 +322,18 @@ impl Transform { self.rotate(rotation); } - /// Rotates this [`Transform`] so that its local negative `Z` direction is toward - /// `target` and its local `Y` direction is toward `up`. + /// Rotates this [`Transform`] so that [`Transform::forward`] points towards the `target` position, + /// and [`Transform::up`] points towards `up`. #[inline] pub fn look_at(&mut self, target: Vec3, up: Vec3) { - let forward = Vec3::normalize(self.translation - target); + self.look_to(target - self.translation, up); + } + + /// Rotates this [`Transform`] so that [`Transform::forward`] points in the given `direction` + /// and [`Transform::up`] points towards `up`. + #[inline] + pub fn look_to(&mut self, direction: Vec3, up: Vec3) { + let forward = -direction.normalize(); let right = up.cross(forward).normalize(); let up = forward.cross(right); self.rotation = Quat::from_mat3(&Mat3::from_cols(right, up, forward));