#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) { srand(time(NULL)); Ball *b = malloc(sizeof(Ball)); *(int *)&b->BALL_WIDTH = 20; *(int *)&b->BALL_HEIGHT = 20; *(int *)&b->BALL_VELOCITY = 10; *(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 const int angle = rand() % 60 + 60; b->posX = b->SCREEN_WIDTH/2; b->posY = b->SCREEN_HEIGHT/2; b->velX = direction * b->BALL_VELOCITY * cos(angle * 2 * M_PI / 180); b->velY = b->BALL_VELOCITY * sin(angle * 2 * 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 + b->BALL_WIDTH; const int upB = b->posY; const int downB = upB + b->BALL_HEIGHT; const int leftR = r->posX; const int rightR = leftR + r->RACKET_WIDTH; const int upR = r->posY; const int downR = upR + r->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, b->BALL_WIDTH, b->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); }