Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 12, 2018 20:46
Show Gist options
  • Save rust-play/ebd5cf20c8e0c31891b027b60482aeeb to your computer and use it in GitHub Desktop.
Save rust-play/ebd5cf20c8e0c31891b027b60482aeeb to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#[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)
}
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())
)
)
}
}
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 );
println!(
"newQuad can contain anotherQuad? {}",
newQuad.contains(
&anotherQuad
)
);
println!(
"newQuad collides with anotherQuad? {}",
newQuad.collides(
&anotherQuad
)
);
anotherQuad.translate(0, -2);
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