aboutsummaryrefslogtreecommitdiff
path: root/src/math.rs
diff options
context:
space:
mode:
authorArne Dußin2020-10-30 23:28:40 +0100
committerArne Dußin2020-10-30 23:28:40 +0100
commitc5b16dd0511997331b8cc8c3647fff95effbe8ec (patch)
treef9077567ee46d70e4988e66086e47d07192f6aa3 /src/math.rs
parent11faa70718c8304ac4e5b4a75e6aa1d573883955 (diff)
downloadgraf_karto-c5b16dd0511997331b8cc8c3647fff95effbe8ec.tar.gz
graf_karto-c5b16dd0511997331b8cc8c3647fff95effbe8ec.zip
Snap rooms to the grid
Diffstat (limited to 'src/math.rs')
-rw-r--r--src/math.rs18
1 files changed, 18 insertions, 0 deletions
diff --git a/src/math.rs b/src/math.rs
index c4e7ac0..60a53e8 100644
--- a/src/math.rs
+++ b/src/math.rs
@@ -16,3 +16,21 @@ pub fn bounding_rect(pos1: Vector2, pos2: Vector2) -> Rectangle {
height: max_y - min_y,
}
}
+
+/// Round a floating point number to the nearest step given by the step argument. For instance, if
+/// the step is 0.5, then all numbers from 0.0 to 0.24999... will be 0., while all numbers from
+/// 0.25 to 0.74999... will be 0.5 and so on.
+pub fn round(num: f32, step: f32) -> f32 {
+ // Only positive steps will be accepted.
+ assert!(step > 0.);
+
+ let lower_bound = ((num / step) as i32) as f32 * step;
+ let upper_bound = lower_bound + step;
+
+ // Compare the distances and prefer the smaller. If they are the same, prefer the upper bound.
+ if (num - lower_bound) < (upper_bound - num) {
+ lower_bound
+ } else {
+ upper_bound
+ }
+}