Duet/src/physics.c

55 lines
1.4 KiB
C

#include "duet.h"
void player_position(float angle,
float *x1, float *y1, float *x2, float *y2)
{
int x=PLAYER_X, y=DHEIGHT/2;
float sin, cos;
sincosf(angle, &sin, &cos);
if(x1) *x1 = x + sin * PLAYER_R;
if(y1) *y1 = y + cos * PLAYER_R;
if(x2) *x2 = x - sin * PLAYER_R;
if(y2) *y2 = y - cos * PLAYER_R;
}
bool player_collision(game_t const *game)
{
float x1, y1, x2, y2;
player_position(game->player_rota, &x1, &y1, &x2, &y2);
for(int i = 0; i < game->cursor; i++) {
if(rect_circle_collide(&game->table[i], x1, y1, PLAYER_SIZE))
return true;
if(rect_circle_collide(&game->table[i], x2, y2, PLAYER_SIZE))
return true;
}
return false;
}
bool rect_circle_collide(rect_t const *r, int cx0, int cy0, int cr)
{
/* Translate so that rectangle center is (0,0) */
cx0 -= r->x;
cy0 -= r->y;
/* Rotate so that rectangle is flat */
float sin, cos;
sincosf(-r->r, &sin, &cos);
float cx = cx0 * cos + cy0 * sin;
float cy = -cx0 * sin + cy0 * cos;
/* Determine point of rectangle closest to center of circle */
float clx=cx, cly=cy;
if(clx < -r->w/2) clx = -r->w/2;
if(clx > r->w/2) clx = r->w/2;
if(cly < -r->h/2) cly = r->h/2;
if(cly > r->h/2) cly = r->h/2;
/* Determine whether that point is in the circle */
return (clx - cx) * (clx - cx) + (cly - cy) * (cly - cy) <= cr * cr;
}