1
0
Fork 0

First attempt on handling bounce direction

This commit is contained in:
Gregory Eremin 2015-10-05 12:38:42 +03:00
parent 4f433796b4
commit 8bb2aa21e1
No known key found for this signature in database
GPG Key ID: 5EFA427EEC26E86C
3 changed files with 55 additions and 13 deletions

View File

@ -12,14 +12,29 @@ Brick::Brick(SDL_Renderer *r, int x, int y, Color c) {
Brick::~Brick() {}
bool Brick::collides_with(int x1, int y1, int x2, int y2) {
return (
BounceDirection Brick::collide(int x1, int y1, int x2, int y2) {
if (!(
visible &&
brick.x < x2 &&
brick.x + BRICK_WIDTH > x1 &&
brick.y < y2 &&
brick.y + BRICK_HEIGHT > y1
);
brick.x <= x2 &&
brick.x + BRICK_WIDTH >= x1 &&
brick.y <= y2 &&
brick.y + BRICK_HEIGHT >= y1
)) {
return None;
}
if (y1 <= brick.y - BRICK_HEIGHT/2) {
return Bottom;
} else if (y1 >= brick.y + (BRICK_HEIGHT/2)) {
return Top;
} else if (x1 < brick.x) {
return Left;
} else if (x1 > brick.x) {
return Right;
} else {
DEBUG("WTF!");
return None;
}
}
void Brick::destroy() {

View File

@ -11,12 +11,20 @@ typedef enum Color {
PURPLE
} Color;
typedef enum BounceDirection {
None,
Top,
Bottom,
Left,
Right
} BounceDirection;
class Brick {
public:
Brick(SDL_Renderer *r, int x, int y, Color c);
~Brick();
bool collides_with(int x1, int y1, int x2, int y2);
BounceDirection collide(int x1, int y1, int x2, int y2);
void destroy();
void render();
private:

View File

@ -66,9 +66,16 @@ void Scene::move_pad_relative(int delta) {
}
void Scene::launch_ball() {
ball.x = SCREEN_WIDTH/2 - BALL_RADIUS;
ball.y = SCREEN_HEIGHT/2 - BALL_RADIUS;
ball_moving = true;
ball_velx = 3;
ball_vely = -2;
ball_vely = 5;
if (rand() > RAND_MAX/2) {
ball_velx = -ball_velx;
}
}
void Scene::move_ball() {
@ -95,22 +102,34 @@ void Scene::move_ball() {
}
// Bottom
if (ball.y >= SCREEN_HEIGHT) {
// Game over
launch_ball();
DEBUG("Loser!");
}
// Pad
if (ball.x >= pad.x && ball.x <= pad.x + PAD_WIDTH && ball.y + 2*BALL_RADIUS >= pad.y) {
ball_vely = -ball_vely;
}
// Bricks
for (int i = NUM_BRICKS; i > 0; --i) {
for (int i = NUM_BRICKS; i >= 0; --i) {
int x1 = ball.x;
int y1 = ball.y;
int x2 = ball.x + 2*BALL_RADIUS;
int y2 = ball.y + 2*BALL_RADIUS;
if (bricks[i].collides_with(x1, y1, x2, y2)) {
BounceDirection dir = bricks[i].collide(x1, y1, x2, y2);
switch (dir) {
case None:
continue;
case Top:
case Bottom:
ball_vely = -ball_vely;
bricks[i].destroy();
break;
case Left:
case Right:
ball_velx = -ball_velx;
break;
}
bricks[i].destroy();
}
}