Skip to content

Commit

Permalink
Add Transform::rotate_around method (#3107)
Browse files Browse the repository at this point in the history
# Objective

- Missing obvious way to rotate a transform around a point. This is popularly used for rotation of an object in world space ("orbiting" a point), or for local rotation of an object around a pivot point on that object.
- Present in other (not to be named) game engines
- Was question from user on Discord today (thread "object rotation")

## Solution

- Added Transform::rotate_around method where point is specified in reference frame of the parent (if any) or in world space.
  • Loading branch information
jamesbeilby committed Feb 4, 2022
1 parent 37a7be5 commit f584e72
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
7 changes: 7 additions & 0 deletions crates/bevy_transform/src/components/global_transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,13 @@ impl GlobalTransform {
self.rotation = rotation * self.rotation;
}

#[doc(hidden)]
#[inline]
pub fn rotate_around(&mut self, point: Vec3, rotation: Quat) {
self.translation = point + rotation * (self.translation - point);
self.rotation *= rotation;
}

/// Multiplies `self` with `transform` component by component, returning the
/// resulting [`GlobalTransform`]
#[inline]
Expand Down
12 changes: 10 additions & 2 deletions crates/bevy_transform/src/components/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ impl Transform {
self.rotation = rotation * self.rotation;
}

/// Rotates this [`Transform`] around a point in space.
/// If the point is a zero vector, this will rotate around the parent (if any) or the origin.
#[inline]
pub fn rotate_around(&mut self, point: Vec3, rotation: Quat) {
self.translation = point + rotation * (self.translation - point);
self.rotation *= rotation;
}

/// Multiplies `self` with `transform` component by component, returning the
/// resulting [`Transform`]
#[inline]
Expand Down Expand Up @@ -235,8 +243,8 @@ impl Transform {
self.scale *= scale_factor;
}

/// Rotates this [`Transform`] so that its unit vector in the local z direction is toward
/// `target` and its unit vector in the local y direction is toward `up`.
/// Rotates this [`Transform`] so that its local z direction is toward
/// `target` and its local y direction is toward `up`.
#[inline]
pub fn look_at(&mut self, target: Vec3, up: Vec3) {
let forward = Vec3::normalize(self.translation - target);
Expand Down

0 comments on commit f584e72

Please sign in to comment.