Mirai's Miscellaneous Misadventures

M47 / core / collisions.c

/* license: AGPLv3 or later */
/* copyright 2023 zamfofex */

#include <mimimi.h>

void mimimi_collision_tick(struct mimimi_collision *collision)
{
	struct mimimi_position **positions, *position;
	int i, j, k;
	int y;
	int *a, *b, d;
	int push;
	
	positions = collision->positions;
	
	for (i = 0 ; i < collision->count ; i++)
	{
		k = i;
		for (j = i - 1 ; j >= 0 ; j--)
		{
			if (positions[i]->x <= positions[j]->x) break;
			
			position = positions[k];
			positions[k] = positions[j];
			positions[j] = position;
			
			k = j;
		}
	}
	
	for (i = 1 ; i < collision->count ; i++)
	{
		y = positions[i]->y - positions[i - 1]->y;
		if (y > collision->height) continue;
		if (y < -collision->height) continue;
		
		a = &positions[i]->x;
		b = &positions[i - 1]->x;
		d = *b - *a;
		if (d < collision->proximity)
		{
			push = collision->strength / (d + collision->tolerance);
			*a -= push;
			*b += push;
		}
	}
}