0

I'm using Pygame with my group to develop a game for this semester in school. I'm responsible for building the physics engine.

My question: How do I get a player object to stop on collision with a rect object? I've scoured the internet, and this website for answers, but everything seems to complicated to grasp.

Here's the code particular block of code I'm trying to get to work:

if player.rect.left == rect.right:
        player.undo_right()

This block is preceded by the game loop. All I want to do is make it so the player is consistently 20 pixels away from the box. I'll be able to apply better bounds once I get this test to work. Right now, it repels the player sporadically, and never consistently. Sometimes, I'll run it, and it'll bounce away once, and then the player will go through the rectangle freely.

I realize there are numerous links on the internet for this type of thing, but I wanted to try to get collision to work using simple code like this. If I'm not able to, then why? Can someone exaplin a simple and efficient way to do this?

Thanks.

  • 1
    For the obvious comment: what's wrong with **if player.rect.left <= rect.right + 20** ? Isn't that the offset you want? This also detects crossing the boundary if the movement step is more than 1 pixel. – Prune Jan 27 '16 at 20:49
  • you can't use "==" if objects move more than 1 pixel in every step. – furas Jan 27 '16 at 21:09
  • btw `print(player.rect.left, rect.right)` and you see why you can't use `==` and you need `<=` – furas Jan 27 '16 at 21:11

0 Answers0