aboutsummaryrefslogtreecommitdiff
path: root/src/math.rs
blob: 60a53e82aac470499e27550c6e2a1893606a5dec (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use raylib::math::{Rectangle, Vector2};

/// Function to calculate the bounding rectangle that is between two vectors. The order of the
/// vectors is irrelevent for this. As long as they are diagonally opposite of each other, this
/// function will work.
pub fn bounding_rect(pos1: Vector2, pos2: Vector2) -> Rectangle {
    let min_x = pos1.x.min(pos2.x);
    let min_y = pos1.y.min(pos2.y);
    let max_x = pos1.x.max(pos2.x);
    let max_y = pos1.y.max(pos2.y);

    Rectangle {
        x: min_x,
        y: min_y,
        width: max_x - min_x,
        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
    }
}