Jump to content
  • Advertisement
Sign in to follow this  
Patriarch K

Same object collision

This topic is 2160 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Imagine that I have an object Box. I create the box with the property dy++ so that it is falling down all the time until it hits the ground. But if I want to create another object and put it above the first so that a collision is made and the box lands on the other box and so on. What is the best way to do this?

I've been trying something like

for(Box b1 : boxes){

   for(Box b2 : boxes){

       if(b1.intersects(b2) && b1.direction == down){

           collision = true

            blablablablabla

}

}

 

Yeah, not exactly like that, but that kind of method. But that does not work very well for me. Do you have an idea how to make it work properly?

                           

Share this post


Link to post
Share on other sites
Advertisement

You only need to handle collisions between any two objects once, so you have a symmetry problem here. If you first handle "A collides with B", then you must not handle "B collides with A" later on. And, by definition, an object can never collide with itself, so you must exclude this case.

 

I don't know how you would go about doing this with foreach syntax, but the basic idea is that if you have N objects, your loop looks like this:

 

for A from 0 to N - 1 do
    for B from A + 1 to N - 1 do
        if (Object A collides with Object B) then // handle stuff

 

This will ensure you never handle the same collision twice, and also excludes same-object collisions.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!