How to generate objects that don't overlap each other?

Hi, I'm using SDL 2.0 for my project to create retro Frogger prototype.
This is what it looks like now:

https://pasteboard.co/IMtCBnl.png

The code for generating those moving cars:
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
int posValue = 50;
int lowest = -(2 * MAP_WIDTH);
int highest = MAP_WIDTH;
	SDL_Rect tempEnemy;
	for (int i = 0; i < 5; i++)
	{
	  for (int j = 0; j < numOfEnem; j++)
	  {
	   if (i % 2 == 0) //car going right
	   {
	   tempEnemy.x = (rand() % (highest + 1 - lowest)) + lowest //R HERE
	   tempEnemy.y = SCREEN_HEIGHT - moveValueY - posValue;
	   tempEnemy.w = smallSpriteSize;
	   tempEnemy.h = smallSpriteSize;

	   if (i == 4) //for printing the long truck
           tempEnemy.w = longSpriteSize;
	   enemies[i][j] = tempEnemy;
	   }
	   else if (i % 2 == 1) //car going left
	   {
	   tempEnemy.x = (rand() % (highest + 1 - lowest)) + lowest;//L HERE
           tempEnemy.y = SCREEN_HEIGHT - moveValueY - posValue;
           tempEnemy.w = smallSpriteSize;
	   tempEnemy.h = smallSpriteSize;

           enemies[i][j] = tempEnemy;
	   }
	posValue += 50;
	}


Where the comment "HERE" is, there is code which generates the X coordinate position of every car, depending on which direction it's going - left or right.
The values generated are pretty good and everything would look normal if not the overlapping cars over each other... I really cannot see any simple or not very horrible way to check whether the car can be generated to some X area or not...
Could someone, please help me with this?

Thanks and... happy winter break, if you have one
If two objects don't intersect then the first object must be above, below, to the left, or to the right of the second. It can be more than one of these, but it must be at least one. Assuming that x is positive to the right and y is positive down:
1
2
3
4
5
6
bool dontIntersect(const Object &ob1, const Object &ob2) {
    return (ob1.right < ob2.left ||  // ob1 to the right of ob2
         ob1.left > ob2.right ||     // ob1 to the left of ob2
         ob1.bottom < ob2.top ||     // ob1 above ob2
         ob1.top > ob2.bottom);      // ob1 below ob2
}


And since objects intersect or they don't:
bool intersect(const Object &ob1, const Object &ob2) { return !dontIntersect(ob1, ob2); }

This code assumes that objects that butt up against each other intersect. That may or may not be right depending on the application.

That helps decide if two objects intersect but what about when you have a large number of objects? You could keep them sorted left to right, then top to bottom. Now given a new object, use a binary search to generate a range of candidates that might intersect it.
Topic archived. No new replies allowed.