how to check if two objects in the same position using rect.colliderect(rect2) after some time of game passes?

StackOverflow https://stackoverflow.com/questions/19881471

  •  30-07-2022
  •  | 
  •  

Question

Well, I need to make dog chasing the ball and the ball chasing the mouse cursor. When the dog in the same position as the ball, the game should stop and print "Game over". Now, my code checks if the two objects in the same position immediately after starting the game, so it ends, because at the start objects in the same position. How can I make it check positions after some time of game passes?

`
    if rect.colliderect(rect2) == True:
        clock.tick(1000)
        self.chasing = False
        rect3 = self.fontim.get_rect()
        rect3 = rect3.move((self.width-rect3.width)//2,
                          (self.height-rect3.height)//2)

    pygame.display.flip()

MyGame().run()
pygame.quit()
sys.exit()

`

Was it helpful?

Solution

Use pygame.time.Clock

Usage:

You first create a Clock. Then once every frame, you should call Clock.tick(), which will return the amount of milliseconds passed since the last call. This way you can increment a milliseconds_passed variable, and also check, when a certain amount of time has passed.

I recommend to make a subclass of Clock, and add a millisenonds_passed variable, which will avoid any clutter in your code.

EDIT:

There are a few mistakes in your code.

Firstly, Clock.tick() is not called once every frame. It is called once every frame when the dog collides with the ball. Move it preferably to your run method.

Secondly, you are not getting the return value of your clock. As I wrote, it returns the amount of milliseconds passed since the last call. So create a new variable, that will be increased by what that method returns. Lastly what you will need is a simple check, you could even do it in the same if statement. Like this:

if rect.colliderect(rect2) == True and self.time_passed/1000 > 5:

OTHER TIPS

Make a timer which is initialized when the game starts, and whenever a collision is encountered, check if time > 2 seconds for instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top