C# XNA 2D Multiple boxes collision detection and movement

Posted by zini on Game Development See other posts from Game Development or by zini
Published on 2012-10-29T19:30:46Z Indexed on 2012/10/29 23:22 UTC
Read the original article Hit count: 231

Filed under:
|
|
|

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?

© Game Development or respective owner

Related posts about XNA

Related posts about c#