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
(log in to comment)
Comments
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.
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.
richard on 2010/03/31 08:21:
Nope, you need to compare rects.