Skip to content

Instantly share code, notes, and snippets.

@fourbytes
Last active May 6, 2016 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fourbytes/aa69067e218d91197e973257150faa1c to your computer and use it in GitHub Desktop.
Save fourbytes/aa69067e218d91197e973257150faa1c to your computer and use it in GitHub Desktop.
// http://recordit.co/LKXWw6hvLK
// player *snaps* to top y of bottom right block when jumping on right wall (and same for left wall, snaps to bottom left top y).
// when player hits top or bottom half of block from the side, it snaps to the the top or bottom of the block relatively.
pub fn collides<F: Point>(a: &AABB<F>, b: &AABB<F>) -> bool {
return na::partial_lt(a.mins(), b.maxs()) &&
na::partial_gt(a.maxs(), b.mins());
}
let mut y_diff = player.velocity.y * args.dt;
let mut x_diff = player.velocity.x * args.dt;
let mut player_translation = Vector2::new(x_diff, y_diff);
let mut future_player_bounds = player.get_bounding_box().append_translation(&player_translation);
if future_player_bounds.mins().x < 0.0 {
player_translation = Vector2::new(0.0, 0.0);
player_translation.x = -(player.position.x + x_diff);
future_player_bounds.append_translation_mut(&player_translation);
}
for point in get_surrounding_points(&future_player_bounds) {
let block_res = self.blocks.get_mut(&Vector2::new(point[0], point[1]));
if block_res.is_some() {
let block = block_res.unwrap();
let block_bounds = block.get_bounding_box();
if collides(&block_bounds, &future_player_bounds) {
player_translation = Vector2::new(0.0, 0.0);
// calculate the difference between centers
let x_diff = block_bounds.center().x - future_player_bounds.center().x;
let y_diff = block_bounds.center().y - future_player_bounds.center().y;
if y_diff.abs() > x_diff.abs() {
if y_diff > 0.0 {
// Top side of entity
player_translation.y += block_bounds.mins().y - future_player_bounds.maxs().y;
// set blue color overlay
block.color = [0.0, 0.0, 1.0, 1.0];
} else {
// Bottom side of entity
player.jumping = false;
player_translation.y -= future_player_bounds.mins().y - block_bounds.maxs().y;
// set red color overlay
block.color = [1.0, 0.0, 0.0, 1.0];
}
} else {
if x_diff > 0.0 {
// Right side of entity
player_translation.x += block_bounds.mins().x - future_player_bounds.maxs().x;
// set light green color overlay
block.color = [0.5, 1.0, 0.5, 1.0];
} else {
// Left side of entity
player_translation.x -= future_player_bounds.mins().x - block_bounds.maxs().x;
// set green color overlay
block.color = [0.0, 1.0, 0.5, 1.0];
}
}
future_player_bounds.append_translation_mut(&player_translation);
} else {
block.color = [0.5, 0.5, 0.9, 1.0];
}
}
}
player.position.y = future_player_bounds.mins().y;
player.position.x = future_player_bounds.mins().x;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment