summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuke Bratch <l_bratch@yahoo.co.uk>2010-11-27 23:00:36 +0000
committerLuke Bratch <l_bratch@yahoo.co.uk>2010-11-27 23:00:36 +0000
commit75098a16e5891973bfe458388ceef33f9dff9423 (patch)
tree5a522aff1f628e95e217f0ae6150e3b1ec23924c
parent63418dfa8adac1f9eee3c8357b54454d0bc0b0d5 (diff)
Level: Implement collision detection
-rw-r--r--Level.cpp61
-rw-r--r--Level.h2
2 files changed, 48 insertions, 15 deletions
diff --git a/Level.cpp b/Level.cpp
index 0cecd50..848c9c4 100644
--- a/Level.cpp
+++ b/Level.cpp
@@ -45,33 +45,51 @@ void Level::changeLevel(int levelNo) {
}
void Level::move() {
- int newX, newY;
+ // Construct a rectangle for player, for collision detection
+ SDL_Rect rect;
+ rect.w = player.getClip()->w;
+ rect.h = player.getClip()->h;
+ // Only record y-coord for now
+ rect.y = player.getY();
// Apply gravity
player.incYVel(GRAVITY);
// Player x-axis movement
- newX = player.getX() + player.getXVel();
- // Don't let player go off either end of the screen
- if (newX >= 0 && newX <= SCREEN_WIDTH - MARCUS_WIDTH) {
- player.setX(newX);
+ rect.x = player.getX() + player.getXVel();
+
+ // If there's a collision in the x-axis ...
+ while (checkCollision(rect)) {
+ // ... fit snugly to edge
+ if (player.getXVel() > 0) {
+ rect.x--;
+ } else {
+ rect.x++;
+ }
+ }
+
+ if (rect.x >= 0 && rect.x <= SCREEN_WIDTH - rect.w) {
+ player.setX(rect.x);
}
// Player y-axis movement
- newY = player.getY() + player.getYVel();
- // Don't let player fall below bottom of screen
- if (newY <= SCREEN_HEIGHT - MARCUS_HEIGHT) {
- player.setY(newY);
- } else {
- // If player was going to fall off, fit snugly to edge
- while (newY > SCREEN_HEIGHT - MARCUS_HEIGHT) {
- newY--;
+ rect.y = player.getY() + player.getYVel();
+
+ // If there's a collision in the y-axis ...
+ if (checkCollision(rect)) {
+ while (checkCollision(rect)) {
+ // ... fit snugly to edge
+ if (player.getYVel() > 0)
+ rect.y--;
+ else
+ rect.y++;
}
- player.setY(newY);
- // Reset velocity
+
player.setYVel(0);
}
+ player.setY(rect.y);
+
player.orient();
}
@@ -138,4 +156,17 @@ void Level::loadMap(int LevelNo) {
// Close map file
map.close();
+}
+
+bool Level::checkCollision(SDL_Rect r) {
+ // Loop through each platform
+ for (int i = 0; i < numPlatforms; i++) {
+ // Check for collisions in the x-axis ...
+ if (r.x - cameraX > platform[i].getX() - r.w && r.x - cameraX < platform[i].getX() + TILE_SIZE)
+ // ... if found, check for collisions in the y-axis
+ if (r.y > platform[i].getY() - r.h && r.y < platform[i].getY() + TILE_SIZE)
+ return true;
+ }
+
+ return false;
} \ No newline at end of file
diff --git a/Level.h b/Level.h
index b6ca8c6..3bfac32 100644
--- a/Level.h
+++ b/Level.h
@@ -33,6 +33,8 @@ class Level {
void loadMap(int levelNo);
int cameraX;
+
+ bool checkCollision(SDL_Rect r);
};
#endif