#### Archived

This topic is now archived and is closed to further replies.

# Help with sprite "sticking" ...

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

## Recommended Posts

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; jcollision( 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.

##### Share on other sites
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.

1. 1
Rutin
24
2. 2
3. 3
JoeJ
18
4. 4
5. 5

• 13
• 38
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631714
• Total Posts
3001861
×