mr5
mr5

Reputation: 3580

Logic flow of rectangle to N-rectangles collision detection

I have a really hard time here figuring out the error in my program.

My code only works in 2 rectangles but if I increment number of rectangle, it doesn't work at all.

My program flows like this:

pseudo code

for (i = 0 to N_of_rectangles - 1)
{

    Rectangle& r1 = rect[i];

    if (r1.is_grab_by_mouse())
    {
        for (j = 0 to N_of_rectanges - 1)
        {
            if (i == j)
            {
                skip_this_loop    //skip for any self-checking
            }

            Rectangle& r2 = rect[j];

            if (not Rectangle.collide(r1, r2))
            {

                if (r1.restricken_move()) break;    //restricken move will be true if
                                                    //*this rect will collide to !*this
                if (r1.movement == HORIZONTAL)
                    r1.move_x_along_with_mouse()
                else    //VERTICAL
                    r1.move_y_along_with_mouse()
            }
            else
            {
                r1.resolve_collision()
            }
        }
    }
}

I did try all the algorithm for rectangle collision detection I searched in google and mine but it seems that I have a logic flaw here.

(PS. my rec-collision detection is not for rotated rectangles)

Upvotes: 0

Views: 188

Answers (1)

MisterJ
MisterJ

Reputation: 929

Why do you have 2 loops in there? Anyways I think that you should only move r1 if he does not collide at all, not everytime he does not collide with a rectangle. The code should be like that :

boolean collision=false
   for (j to N_of_rectanges)
   {
      if (i == j)
      {
        skip_this_loop
      }

       if (Rectangle.collide(r1, r2))
      {
         r1.resolve_collision()
         collision=true
      }
    }
  if(not collision){
    r1.move()
  }

Upvotes: 1

Related Questions