Advertisement

AABB collision

Started by March 29, 2024 09:20 PM
50 comments, last by JoeJ 6 months ago

here is my latest code

#include <iostream>
#include <vector>

using namespace std;

class Rect
{
public:
	float x = 0;
	float y = 0;
	float w = 0;
	float h = 0;
};

// you forgot to copy the intersection function:
bool intersectRect(const Rect& rect1, const Rect& rect2)
{
	return rect1.x < rect2.x + rect2.w && rect1.x + rect1.w > rect2.x &&
		rect1.y < rect2.y + rect2.h && rect1.y + rect1.h > rect2.y;
}

int main(int argc, char* args[])
{

	vector<Rect> r(3 * 6);

	for (int y = 0; y < 6; y++)
	{
		for (int x = 0; x < 3; x++)
		{
			int index = y * 3 + x;
			r[index].x = x * 40 + 260;
			r[index].y = y * 80;
			r[index].w = 40;
			r[index].h = 80;
			cout << r[index].x << " " << r[index].y << " " << r[index].w << " " << r[index].h << endl;
 		}
	}

	Rect rect1;
	Rect rect2;
	
	rect1.x = 300;
	rect1.y = 0;
	rect1.w = 5;
	rect1.h = 5;
	
	rect2.x = 260;
	rect2.y = 0;
	rect2.w = 40;
	rect2.h = 80;
	cout << intersectRect(rect1, rect2) << endl;

	return 0;
}

Good.
You know hat's next: Make a function to visualize the rectangles 60 times per second using SDL / OpenGL, move one with the keyboard, test for all collisions, work on a game… \:D/

This topic is closed to new replies.

Advertisement