summaryrefslogtreecommitdiff
path: root/physics.c
blob: 5b3235615b53abe43c2b3c8045b6c4f5e5fdd441 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <math.h>

#include "dat.h"

static void mink(Body *a, Body *b, float *minx, float *miny, float *maxx, float *maxy);

int
checkcollision(Body *a, Body *b)
{
	float minx, miny, maxx, maxy;

	mink(a, b, &minx, &miny, &maxx, &maxy);

	return minx < 0 && maxx > 0 && miny < 0 && maxy > 0;
}

void
resolvecoll(Body *a, Body *b, float p[2])
{
	float minx, miny, maxx, maxy;
	mink(a, b, &minx, &miny, &maxx, &maxy);

	float hx = fabsf(minx) < fabsf(maxx) ? fabsf(minx) : fabsf(maxx);
	float hy = fabsf(miny) < fabsf(maxy) ? fabsf(miny) : fabsf(maxy);

	if(hx < hy) {
		p[1] = 0;
		p[0] = hx * (fabsf(minx) < fabsf(maxx) ? -1.0 : 1.0);
	} else {
		p[0] = 0;
		p[1] = hy * (fabsf(miny) < fabsf(maxy) ? -1.0 : 1.0);
	}
}

void 
mink(Body *a, Body *b, float *minx, float *miny, float *maxx, float *maxy)
{
	float p[2], s[2];
	
	for(int i = 0; i < 2; i++) {
		s[i] = a->size[i] + b->size[i];
		p[i] = a->pos[i] - b->pos[i];
	}

	*minx = p[0] - s[0];
	*maxx = p[0] + s[0];
	*miny = p[1] - s[1];
	*maxy = p[1] + s[1];
}