Advertisement

Help with sprite "sticking" ...

Started by June 12, 2001 09:47 PM
0 comments, last by Vanukoff 23 years, 8 months ago
Scenario: I have some square sprites that are bouncing around the screen and when one hits another, they are supposed to bounce. It works OK, except sometimes two sprites somehow get overlapped, and "stick" together, then they just vibrate within each other. Here is the pertinent code:
  

for(int j=0; j<NUMOBJ; j++)
{
    for(int k=(j+1); k<NUMOBJ; k++)
    {
        if(object[j].sprite->collision( object[k].sprite))
        {
            dx = abs(object[j].sprite->pos.x - object[k].sprite->pos.x);
            dy = abs(object[j].sprite->pos.y - object[k].sprite->pos.y);
            if(dx>dy)
            {
                object[j].sprite->pos.x -= object[j].sprite->vel.x;
                object[k].sprite->pos.x -= object[k].sprite->vel.x;
                 
                temp = object[j].sprite->vel.x;
                object[j].sprite->vel.x = object[k].sprite->vel.x;
                object[k].sprite->vel.x = temp;
            }
            else
            {
                object[j].sprite->pos.y -= object[j].sprite->vel.y;
                object[k].sprite->pos.y -= object[k].sprite->vel.y;

                temp = object[j].sprite->vel.y;
                object[j].sprite->vel.y = object[k].sprite->vel.y;
                object[k].sprite->vel.y = temp;
            }
        }
    }
}

  
So, basically, if two objects collide, I take the difference in their X positions (dx) and Y positions (dy). If dx is greater, they are hitting each other left-to-right, so I move them back (in the X direction) and swap their X velocities. Otherwise, dy was greater, so they are hitting each other top-to-bottom, so I move them back (in the Y direction) and swap their Y velocities. It works OK for most of the time, but they still get locked within one another randomly. BTW, when the objects are initially placed on the screen, I ensure they are not overlapping. Thanks in advance for any suggestions.
What you should do is when you''ve detected a collision, you should project the two objects back in time to the actual point at which they collided, then perform the collision code, then bring them back to the present point in time. Doing so increases the realism of the collisions, and avoids glitches like the one you''re experiencing.

This topic is closed to new replies.

Advertisement