81 lines
2.0 KiB
C
81 lines
2.0 KiB
C
#include <stdlib.h> // srand, rand
|
|
#include <time.h> // time
|
|
#include <math.h> // 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_WIDTH = 20;
|
|
*(int *)&b->BALL_HEIGHT = 20;
|
|
*(int *)&b->BALL_VELOCITY = 7;
|
|
*(int *)&b->BALL_ANGLE_MIN_OFFSET = 10;
|
|
*(int *)&b->BALL_ANGLE_MAX_OFFSET = 60;
|
|
*(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() % b->BALL_ANGLE_MAX_OFFSET*2 + b->BALL_ANGLE_MAX_OFFSET/2 - 90;
|
|
} while (-b->BALL_ANGLE_MIN_OFFSET <= angle && angle <= b->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 * b->BALL_VELOCITY * cos(angle * M_PI / 180);
|
|
b->velY = b->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 + 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);
|
|
}
|