moved camera to a separate mod and use Rect intersection and has_intersection methods

This commit is contained in:
2015-01-06 16:07:03 +01:00
parent 62c74a0736
commit db4b16c08d
2 changed files with 48 additions and 63 deletions

24
src/camera.rs Normal file
View File

@@ -0,0 +1,24 @@
use sdl2::rect::Rect;
pub struct Camera {
pub x: i32,
pub y: i32,
pub w: i32,
pub h: i32
}
impl Camera {
pub fn new(x: i32, y: i32, w: i32, h: i32) -> Camera {
Camera {
x: x,
y: y,
w: w,
h: h
}
}
pub fn get_rect(&self) -> Rect {
Rect::new(self.x, self.y, self.w, self.h)
}
}

View File

@@ -1,8 +1,6 @@
extern crate sdl2;
use std::cmp::{max, min};
use sdl2::video::{Window, WindowPos, OPENGL};
use sdl2::event::{poll_event, Event};
use sdl2::timer::{get_ticks, delay};
@@ -12,11 +10,13 @@ use sdl2::pixels::Color;
use tile::Layer;
use player::Player;
use camera::Camera;
mod vec;
mod tile;
mod player;
mod camera;
const SCREEN_WIDTH : i32 = 960;
@@ -35,29 +35,6 @@ enum Tile {
}
struct Camera {
x: i32,
y: i32,
width: i32,
height: i32
}
impl Camera {
fn new(x: i32, y: i32, width: i32, height: i32) -> Camera {
Camera {
x: x,
y: y,
width: width,
height: height
}
}
fn get_rect(&self) -> Rect {
Rect::new(self.x, self.y, self.width, self.height)
}
}
fn main() {
sdl2::init(sdl2::INIT_EVERYTHING);
@@ -137,9 +114,9 @@ fn main() {
match *tile {
Tile::Empty => (),
Tile::Floor(_) => {
if collision_detection(position, &player.get_rect()) {
let intersect = collision_intersect(position, &player.get_rect());
if position.has_intersection(&player.get_rect()) {
match position.intersection(&player.get_rect()) {
Some(intersect) => {
if intersect.w >= intersect.h {
if player.velocity.y < 0.0 {
player.position.y += intersect.h as f32;
@@ -159,6 +136,9 @@ fn main() {
player.velocity.x = 0.0;
}
},
None => (),
}
}
}
}
@@ -175,7 +155,7 @@ fn main() {
match *tile {
Tile::Empty => (),
Tile::Floor(_) => {
if collision_detection(position, &ground) {
if position.has_intersection(&ground) {
player.on_ground = true;
}
}
@@ -207,22 +187,3 @@ fn main() {
sdl2::quit();
}
fn collision_detection(lhs: &Rect, rhs: &Rect) -> bool {
if lhs.x + lhs.w <= rhs.x || rhs.x + rhs.w <= lhs.x {
false
}
else if lhs.y + lhs.h <= rhs.y || rhs.y + rhs.h <= lhs.y {
false
}
else {
true
}
}
fn collision_intersect(lhs: &Rect, rhs: &Rect) -> Rect {
let x = max(lhs.x, rhs.x);
let y = max(lhs.y, rhs.y);
Rect::new(x, y, min(lhs.x + lhs.w, rhs.x + rhs.w) - x, min(lhs.y + lhs.h, rhs.y + rhs.h) - y)
}