# C# XNA 2D Multiple boxes collision detection and movement

Hi,

I've been making simple game where you shoot boxes that are coming towards you. All game objects are simple rectangles.

Now I have problem with collision detection; how to check where the collision comes so I can change the coordinates right? I have this kind of situation:

http://imgur.com/8yjfW

Imagine that all of those blocks are moving towards you (green box). If those orange boxes collide with each other, they should "avoid" themselves and not go through each other. I have class Enemy which has properties x, y and such. Now I'm doing the collision like this:

        // os.Count is an amount of other enemies colliding with this enemy
if (os.Count == 0) {   // If enemy doesn't collide with other enemy
lasty = y;
lastx = x;
slope = (x - player.x) / (y - player.y);
x += slope * l; // l is "movement speed" of enemy (float)
if (y > player.y) {
y = lasty;
} else if (y < player.y) {
y += l;
}
} else {
foreach(Enemy b in os) {
if (b.y > this.y) {  // If some colliding enemy is closer player than this enemy, that closer one will be moved towards the player
b.lasty = b.y;
if (!BiggestY(os)) { // BiggestY returns true if this enemy has the biggest Y
b.y += b.l;
}
b.x = b.lastx;
}
}
}


But this is very, very bad way to do this. I know it, but I just can't figure out other way. And as a matter in fact, this method doesn't even work pretty good; if multiple enemies are colliding same enemy they go through each other.

I explained this pretty badly, but I hope that you understand this.

And to sum up, as I said: How to check where the collision comes so I can change the coordinates right?

• You appear to be looking for a discussion, since you pose no question and there's no correct answer to the question you seem to imply. Further questions about how to improve individual code are too localized for the site. – MichaelHouse Oct 29 '12 at 20:23
• Added the question second time at the end of the post – zini Oct 29 '12 at 20:48
• Zini, have you searched the site? There are lots of questions about collision detection and response. You seem to want an answer for your specific code. That's not what this site is about. – MichaelHouse Oct 29 '12 at 21:09