PyWeek - Quick PyGame Sprite question

Sorry if this is a FAQ but I couldn't find an answer anywhere.

Is there a built in way to stop Sprites overlapping? I want my character to bump into objects and not walk over them.

 I could use collision detection and compare RECTs but I suspect there is a better way?
 
Thanks,
Davy

daftspaniel on 2010/03/31 07:02
edited on 2010/03/31 07:02


Comments: (log in to comment)

Nope, you need to compare rects.
if you are using sprite batch, you can directly use pygame's functions to find the overlapping objects and push them away.
By the way, don't alter the x and y coordinates at the same time, if you check for collisions after each coordinate, then you will automagically know where you came from, and how you should adjust the coordinate so as to make sure two objects don't overlap.
Alright, I'll bite. @Adrwen, I don't understand what you're saying.
Oh right, maybe this'll do the trick, if you actually needed this info...

If you wouldn't use any collision detection, you would change the x and y coordinates one after the other, like:

self.rect.left+=increase #changes x
self.rect.top+=increase #changes y


If however you need to do collision detection, it is better to check after each coordinate has been changed, thus:

self.rect.left+=increase #changes the x coordinate of a typical sprite
collision_detection()
adjust_position()

self.rect.top+=increase #changes the y coordinate of a sprite
collision_detection()
adjust_position()


By doing it that way, you will make sure that you always end up on the right side of whatever you were trying to turn into a solid object.
Thanks for all the replies! I have something sorta working now :-)
Thanks Adrwen! This piece of wisdom seems to have evaded me until now and in every platform game I had some slight collision issues as a result. Works great!

To contribute something myself, I would recommend storing the "previous position" instead of the velocity. And in the integration step you just do x += DRAG * (x - old_x). I find that this saves me a lot of headache since I never have to think about velocity. A limitation is that all your collisions will be inelastic.