Skip to content

Commit 1114ae8

Browse files
committed
Add is_angle_equal_approx
1 parent bf76894 commit 1114ae8

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

godot-core/src/builtin/math.rs

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
use std::f32::consts::TAU;
88

9+
use super::Vector2;
10+
911
pub const CMP_EPSILON: f32 = 0.00001;
1012

1113
pub fn lerp(a: f32, b: f32, t: f32) -> f32 {
@@ -23,6 +25,18 @@ pub fn is_equal_approx(a: f32, b: f32) -> bool {
2325
(a - b).abs() < tolerance
2426
}
2527

28+
/// Check if two angles are approximately equal, by comparing the distance
29+
/// between the points on the unit circle with 0 using [`is_equal_approx`].
30+
pub fn is_angle_equal_approx(a: f32, b: f32) -> bool {
31+
let (x1, y1) = a.sin_cos();
32+
let (x2, y2) = b.sin_cos();
33+
34+
is_equal_approx(
35+
Vector2::distance_to(Vector2::new(x1, y1), Vector2::new(x2, y2)),
36+
0.0,
37+
)
38+
}
39+
2640
pub fn is_zero_approx(s: f32) -> bool {
2741
s.abs() < CMP_EPSILON
2842
}
@@ -190,6 +204,15 @@ mod test {
190204
assert_ne_approx!(1.0, 2.0, is_equal_approx, "Message {}", "formatted");
191205
}
192206

207+
#[test]
208+
fn angle_equal_approx() {
209+
assert_eq_approx!(1.0, 1.000001, is_angle_equal_approx);
210+
assert_eq_approx!(0.0, TAU, is_angle_equal_approx);
211+
assert_eq_approx!(PI, -PI, is_angle_equal_approx);
212+
assert_eq_approx!(4.45783, -(TAU - 4.45783), is_angle_equal_approx);
213+
assert_eq_approx!(31.0 * PI, -13.0 * PI, is_angle_equal_approx);
214+
}
215+
193216
#[test]
194217
#[should_panic(expected = "I am inside format")]
195218
fn eq_approx_fail_with_message() {
@@ -198,16 +221,17 @@ mod test {
198221

199222
#[test]
200223
fn lerp_angle_test() {
201-
assert_eq_approx!(lerp_angle(0.0, PI, 0.5), -FRAC_PI_2, is_equal_approx);
224+
assert_eq_approx!(lerp_angle(0.0, PI, 0.5), -FRAC_PI_2, is_angle_equal_approx);
202225
assert_eq_approx!(
203226
lerp_angle(0.0, PI + 3.0 * TAU, 0.5),
204227
FRAC_PI_2,
205-
is_equal_approx
228+
is_angle_equal_approx
206229
);
207230
let angle = PI * 2.0 / 3.0;
208-
let (s1, c1) = lerp_angle(-5.0 * TAU, angle + 3.0 * TAU, 0.5).sin_cos();
209-
let (s2, c2) = (angle / 2.0).sin_cos();
210-
assert_eq_approx!(s1, s2, is_equal_approx);
211-
assert_eq_approx!(c1, c2, is_equal_approx);
231+
assert_eq_approx!(
232+
lerp_angle(-5.0 * TAU, angle + 3.0 * TAU, 0.5),
233+
(angle / 2.0),
234+
is_angle_equal_approx
235+
);
212236
}
213237
}

0 commit comments

Comments
 (0)