rust_training_tool::collision

Function collide_with_rect

source
pub fn collide_with_rect(
    self_direction: &Vec2,
    self_bounding_box: &Rect,
    other_bounding_box: &Rect,
) -> Option<BounceDirection>
Expand description

A function to check collision between an object moving in self_direction with a bounding box self_bounding_box, and some other bounding box. If bounding boxes intersect, return the direction the moving object should bounce, otherwise, return None.

ยงExample

use rust_training_tool::collision;
use eframe::egui::{Pos2, Rect, Vec2};

// I am moving up
let self_direction = -Vec2::Y;
let self_bounding_box = Rect::from_center_size(Pos2::ZERO, Vec2::new(1.0, 1.0));
let other_bounding_box = Rect::from_center_size(
    Pos2::new(1.0, 0.9),
    Vec2::new(1.0, 1.0),
);
assert!(matches!(
    collision::collide_with_rect(
        &self_direction,
        &self_bounding_box,
        &other_bounding_box
    ),
    Some(collision::BounceDirection::Down)
));

// I am moving right
let self_direction = Vec2::X;
let other_bounding_box = Rect::from_center_size(
    Pos2::new(0.9, 1.0),
    Vec2::new(1.0, 1.0),
);
assert!(matches!(
    collision::collide_with_rect(
        &self_direction,
        &self_bounding_box,
        &other_bounding_box
    ),
    Some(collision::BounceDirection::Left)
));