diff options
-rw-r--r-- | Level.cpp | 61 | ||||
-rw-r--r-- | Level.h | 2 |
2 files changed, 48 insertions, 15 deletions
@@ -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 @@ -33,6 +33,8 @@ class Level { void loadMap(int levelNo); int cameraX; + + bool checkCollision(SDL_Rect r); }; #endif |