Pong game for ELEC1620 board.

Revision:
2:482d74ef09c8
Parent:
1:d63a63f0d397
Child:
3:5746c6833d73
--- a/lib/PongEngine.cpp	Fri Mar 05 16:58:05 2021 +0000
+++ b/lib/PongEngine.cpp	Wed Mar 10 16:37:52 2021 +0000
@@ -15,6 +15,7 @@
     // important to update paddles and ball before checking collisions so can
     // correct for it before updating the display
     check_wall_collision();
+    check_paddle_collision();
 }
 
 void PongEngine::draw(N5110 &lcd) {
@@ -27,8 +28,8 @@
     _paddle.draw(lcd);
 }
 
-void PongEngine::check_wall_collision()
-{
+void PongEngine::check_wall_collision() {
+    printf("Pong Engine: Check Wall Collision\n");
     // read current ball attributes
     Position2D ball_pos = _ball.get_pos();
     Position2D ball_velocity = _ball.get_velocity();
@@ -38,15 +39,41 @@
     if (ball_pos.y <= 1) {  //  1 due to 1 pixel boundary
         ball_pos.y = 1;  // bounce off ceiling without going off screen
         ball_velocity.y = -ball_velocity.y;  // flip velocity
-    }
-    // check if hit bottom wall
-    else if (ball_pos.y + size >= (HEIGHT-1) ) {
+    } else if (ball_pos.y + size >= (HEIGHT-1) ) {
         // hit bottom
         ball_pos.y = (HEIGHT-1) - size;  // stops ball going off screen
         ball_velocity.y = -ball_velocity.y;    // flip velcoity 
-    }
+    } else if (ball_pos.x + size >= (WIDTH-1) ) {
+        // hit right wall
+        ball_pos.x = (WIDTH-1) - size;  // stops ball going off screen
+        ball_velocity.x = -ball_velocity.x;    // flip velcoity 
+    } 
 
     // update ball parameters
     _ball.set_velocity(ball_velocity);
     _ball.set_pos(ball_pos);
+}
+
+void PongEngine::check_paddle_collision() {
+    printf("Pong Engine: Check Paddle Collision\n");
+    // read current ball and paddle attributes
+    Position2D ball_pos = _ball.get_pos();
+    Position2D ball_velocity = _ball.get_velocity();
+    Position2D paddle_pos = _paddle.get_pos();  // paddle
+
+    // see if ball has hit the paddle by checking for overlaps
+    if (
+        (ball_pos.y >= paddle_pos.y) && //top
+        (ball_pos.y <= paddle_pos.y + _paddle.get_height() ) && //bottom
+        (ball_pos.x >= paddle_pos.x) && //left
+        (ball_pos.x <= paddle_pos.x + _paddle.get_width() )  //right
+    ) {
+        // if it has, fix position and reflect x velocity
+        ball_pos.x = paddle_pos.x + _paddle.get_width();
+        ball_velocity.x = -ball_velocity.x;
+    }
+
+    // write new attributes
+    _ball.set_velocity(ball_velocity);
+    _ball.set_pos(ball_pos);
 }
\ No newline at end of file