Skip to content

Commit

Permalink
Add Transform::look_to (bevyengine#6692)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
2 people authored and taiyoungjang committed Dec 15, 2022
1 parent 44e6326 commit e35b3d6
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions crates/bevy_transform/src/components/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,16 +117,24 @@ 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 {
self.look_at(target, up);
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]
Expand Down Expand Up @@ -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));
Expand Down

0 comments on commit e35b3d6

Please sign in to comment.