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;
}
elseif (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?
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.