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:


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?

  • \$\begingroup\$ 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. \$\endgroup\$ – MichaelHouse Oct 29 '12 at 20:23
  • \$\begingroup\$ Added the question second time at the end of the post \$\endgroup\$ – zini Oct 29 '12 at 20:48
  • 4
    \$\begingroup\$ 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. \$\endgroup\$ – MichaelHouse Oct 29 '12 at 21:09

You could use a physics library such as Box2DX: this would handle the collisions, as well as physics which would make your collisions work/look better.

| improve this answer | |
  • \$\begingroup\$ Remember if an answer helps you, please up vote it. \$\endgroup\$ – user22020 Nov 1 '12 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.