#include // srand, rand #include // time #include // sin, cos, M_PI #include "ball.h" #include "racket.h" Ball* Ball_init(int screen_width, int screen_height, int posX_start) { srand(time(NULL)); Ball *b = malloc(sizeof(Ball)); *(int *)&b->BALL_POSX_START = posX_start; *(int *)&b->SCREEN_WIDTH = screen_width; *(int *)&b->SCREEN_HEIGHT = screen_height; Ball_reset(b, 1); return b; } void Ball_reset(Ball *b, int direction) { // 120 deg angle with norm horizontal vector int angle; do { angle = rand() % BALL_ANGLE_MAX_OFFSET*2 + BALL_ANGLE_MAX_OFFSET/2 - 90; } while (-BALL_ANGLE_MIN_OFFSET <= angle && angle <= BALL_ANGLE_MIN_OFFSET); if (direction < 0) { b->posX = b->BALL_POSX_START; } else { b->posX = b->SCREEN_WIDTH - b->BALL_POSX_START; } b->posY = b->SCREEN_HEIGHT/2; b->velX = -direction * BALL_VELOCITY * cos(angle * M_PI / 180); b->velY = BALL_VELOCITY * sin(angle * M_PI / 180); } void Ball_free(Ball *b) { free(b); } int Ball_collision(const Ball *b, const Racket *r) { const int leftB = b->posX; const int rightB = leftB + BALL_WIDTH; const int upB = b->posY; const int downB = upB + BALL_HEIGHT; const int leftR = r->posX; const int rightR = leftR + RACKET_WIDTH; const int upR = r->posY; const int downR = upR + RACKET_HEIGHT; if(downB <= upR || upB >= downR || rightB <= leftR || leftB >= rightR) { return false; } return true; } int Ball_render(const Ball *b, SDL_Renderer *renderer) { SDL_Rect rect = { b->posX, b->posY, BALL_WIDTH, BALL_HEIGHT }; if (SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255) < 0) { printf("SDL_SetRenderDrawColor failed! SDL_Error: %s\n", SDL_GetError()); return 1; } SDL_RenderFillRect(renderer, &rect); return 0; //SDL_RenderCopy(renderer, b->texture, NULL, &rect); }