Skip to content

Instantly share code, notes, and snippets.

@piboistudios
Forked from rust-play/playground.rs
Last active July 12, 2018 20:54
Show Gist options
  • Save piboistudios/eda3d0a5d490d506bf36afcc3a15ba1c to your computer and use it in GitHub Desktop.
Save piboistudios/eda3d0a5d490d506bf36afcc3a15ba1c to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// Simple Axis-Aligned Bounding Box
// Author: Gabriel Hayes
#[derive(Debug)]
struct AABB {
x: i64,
y: i64,
wx: i64,
hy: i64,
}
impl AABB {
fn new(x: i64, y: i64, wx: i64, hy: i64) -> AABB {
AABB {
x: x,
y: y,
wx: wx,
hy: hy
}
}
pub fn get_right(&self) -> i64 {
return self.x + self.wx;
}
pub fn get_top(&self) -> i64 {
return self.y + self.hy;
}
pub fn translate(&mut self, x: i64, y: i64) -> (i64, i64) {
let (x, y) = self.ray(x, y);
self.x += x;
self.y += y;
(x, y)
}
// this is where you would do a collision check and decrease x and y accordingly (to 0 if movement is completely restricted)
pub fn ray(&self, x: i64, y: i64) -> (i64, i64) {
(x, y)
}
pub fn contains<'a>(&self, quad: &'a AABB) -> bool {
self.wx > quad.wx
&& self.hy > quad.hy
}
pub fn collides<'a>(&self, quad: &'a AABB) -> bool {
// check bottom
(quad.y > self.y && quad.y < self.get_top()
&& (
// check left
(quad.x > self.x && quad.x < self.get_right())
||
// check right
(quad.get_right() > self.x && quad.get_right() < self.get_right())
)
)
||
// check top
(quad.get_top() > self.y && quad.get_top() < self.get_top()
&& (
// check left
(quad.x > self.x && quad.x < self.get_right())
||
// check right
(quad.get_right() > self.x && quad.get_right() < self.get_right())
)
)
}
}
// test
fn main() {
let mut newQuad = AABB::new(0, 0, 2, 2);
println!("newQuad: {:#?}", newQuad);
println!("newQuad.get_right(): {}", newQuad.get_right());
println!("newQuad.get_top(): {}", newQuad.get_top());
//newQuad.translate(5, 0);
let mut anotherQuad = AABB::new(0, 3, 1, 1 ); // a smaller quad not in the bounds of the larger quad
println!(
"newQuad can contain anotherQuad? {}",
newQuad.contains(
&anotherQuad
)
);
println!(
"newQuad collides with anotherQuad? {}",
newQuad.collides(
&anotherQuad
)
);
anotherQuad.translate(0, -2); // move it within the bounds of the other quad
println!(
"newQuad collides with anotherQuad? {}",
newQuad.collides(
&anotherQuad
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment