public Boolean CollisionCheck(float x1, float y1, float width1, float height1, float x2, float y2, float width2, float height2)
{
float left1 = x1;
float left2 = x2;
float right1 = x1 + width1;
float right2 = x2 + width2;
float top1 = y1;
float top2 = y2;
float bottom1 = y1 + height1;
float bottom2 = y2 + height2;
if (bottom1 < top2)
return false;
if (top1 > bottom2)
return false;
if (right1 < left2)
return false;
if (left1 > right2)
return false;
return true;
}
That's my collision detection code, which should return true is 2 boxes are touching in any direction.
It works if I'm comparing 2 different images (Ie. the floor tiles and the character (Pacman - if Pacman isn't touching the floor tile he falls, dies, and respaws:
for (int i = 0; i < noOfTiles; i++)
{
if (CollisionCheck(pacmanPos.X, pacmanPos.Y, frameSize.X, frameSize.Y, tilePos[i].X, tilePos[i].Y, frameSize2.X, frameSize2.Y))
{
//continue as normal
}
else
{
pacmanPos.Y ++;
}
}
However, I have an array of enemies (munchies) and trying to stop them spawning on top of each other is proving difficult (They re-spawn in a random x and y coordinate):
for (int i = 0; i < noOfMunchies; i++)
if (CollisionCheck(munchiePos[i].X, munchiePos[i].Y, munchieSize, munchieSize, munchiePos[i].X, munchiePos[i].Y, munchieSize, munchieSize))
{
// change the position of the munchie that collided
munchiePos[i].X = Math.Max(0, rand.Next(gameWidth) - munchieSize);
munchiePos[i].Y = Math.Max(-500, rand.Next(gameHeight) - gameHeight);
}
}
I understand the problem, it's just checking a collision with the munchie at position i, with the same munchie at position i... but I don't understand how to fix it :/
Thank you to anyone who can help, i'm truly stuck T_T