Skip to content

Commit 67c7825

Browse files
authored
Fix rotation matrix construction from Rot2 (#20522)
# Objective Our `From<Rot2>` implementation for `Mat2` looks like this: ```rust impl From<Rot2> for Mat2 { /// Creates a [`Mat2`] rotation matrix from a [`Rot2`]. fn from(rot: Rot2) -> Self { Mat2::from_cols_array(&[rot.cos, -rot.sin, rot.sin, rot.cos]) } } ``` The resulting matrix looks like this: ```text [ cos, sin ] [ -sin, cos ] ``` Cool! Oh wait -- *checks [notes](https://en.wikipedia.org/wiki/Rotation_matrix)* -- the correct matrix is this? ```text [ cos, -sin ] [ sin, cos ] ``` Oops! ## Solution Fix the matrix signs. Now my joint's axes are oriented correctly :) ## Testing Added a simple regression test. Fails before the change, passes after.
1 parent cb34db6 commit 67c7825

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

crates/bevy_math/src/rotation2d.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ impl From<f32> for Rot2 {
446446
impl From<Rot2> for Mat2 {
447447
/// Creates a [`Mat2`] rotation matrix from a [`Rot2`].
448448
fn from(rot: Rot2) -> Self {
449-
Mat2::from_cols_array(&[rot.cos, -rot.sin, rot.sin, rot.cos])
449+
Mat2::from_cols_array(&[rot.cos, rot.sin, -rot.sin, rot.cos])
450450
}
451451
}
452452

@@ -518,7 +518,7 @@ mod tests {
518518

519519
use approx::assert_relative_eq;
520520

521-
use crate::{ops, Dir2, Rot2, Vec2};
521+
use crate::{ops, Dir2, Mat2, Rot2, Vec2};
522522

523523
#[test]
524524
fn creation() {
@@ -721,4 +721,20 @@ mod tests {
721721
assert_eq!(rot1.slerp(rot2, 0.5).as_degrees(), 90.0);
722722
assert_eq!(ops::abs(rot1.slerp(rot2, 1.0).as_degrees()), 180.0);
723723
}
724+
725+
#[test]
726+
fn rotation_matrix() {
727+
let rotation = Rot2::degrees(90.0);
728+
let matrix: Mat2 = rotation.into();
729+
730+
// Check that the matrix is correct.
731+
assert_relative_eq!(matrix.x_axis, Vec2::Y);
732+
assert_relative_eq!(matrix.y_axis, Vec2::NEG_X);
733+
734+
// Check that the matrix rotates vectors correctly.
735+
assert_relative_eq!(matrix * Vec2::X, Vec2::Y);
736+
assert_relative_eq!(matrix * Vec2::Y, Vec2::NEG_X);
737+
assert_relative_eq!(matrix * Vec2::NEG_X, Vec2::NEG_Y);
738+
assert_relative_eq!(matrix * Vec2::NEG_Y, Vec2::X);
739+
}
724740
}

0 commit comments

Comments
 (0)