Mirai's Miscellaneous Misadventures

M45 / core / collisions.c

1/* license: AGPLv3 or later */
2/* copyright 2023 zamfofex */
3
4#include <mimimi.h>
5
6void mimimi_collision_tick(struct mimimi_collision *collision)
7{
8	struct mimimi_position **positions, *position;
9	int i, j, k;
10	int y;
11	int *a, *b, d;
12	int push;
13	
14	positions = collision->positions;
15	
16	for (i = 0 ; i < collision->count ; i++)
17	{
18		k = i;
19		for (j = i - 1 ; j >= 0 ; j--)
20		{
21			if (positions[i]->x <= positions[j]->x) break;
22			
23			position = positions[k];
24			positions[k] = positions[j];
25			positions[j] = position;
26			
27			k = j;
28		}
29	}
30	
31	for (i = 1 ; i < collision->count ; i++)
32	{
33		y = positions[i]->y - positions[i - 1]->y;
34		if (y > collision->height) continue;
35		if (y < -collision->height) continue;
36		
37		a = &positions[i]->x;
38		b = &positions[i - 1]->x;
39		d = *b - *a;
40		if (d < collision->proximity)
41		{
42			push = collision->strength / (d + collision->tolerance);
43			*a -= push;
44			*b += push;
45		}
46	}
47}