Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
lib/PongEngine.cpp
- Committer:
- eencae
- Date:
- 2021-03-10
- Revision:
- 2:482d74ef09c8
- Parent:
- 1:d63a63f0d397
- Child:
- 3:5746c6833d73
File content as of revision 2:482d74ef09c8:
#include "PongEngine.h" PongEngine::PongEngine(){} void PongEngine::init(int paddle_position, int paddle_height, int paddle_width, int ball_size, int speed){ printf("Pong Engine: Init\n"); _ball.init(ball_size,speed); _paddle.init(paddle_position, paddle_height, paddle_width); } void PongEngine::update(UserInput input) { printf("Pong Engine: Update\n"); _ball.update(); _paddle.update(input); // 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) { printf("Pong Engine: Draw\n"); // draw the elements in the LCD buffer // pitch lcd.drawRect(0,0,WIDTH,HEIGHT,FILL_TRANSPARENT); lcd.drawLine(WIDTH/2,0,WIDTH/2,HEIGHT-1,2); _ball.draw(lcd); _paddle.draw(lcd); } 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(); int size = _ball.get_size(); // check if hit top wall 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 } 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); }