0

How can i move different things in the game with different speeds? Using pygame.time.delay or pygame.time.wait will have an impact on the whole game. I want something like having a Rect moving at clock.tick(30) while another Rect moves at clock.tick(10). How can i do this?

Edit: What i'm looking for is actually not only the movement (this could be done of course with different movement amounts to be added to Rect.xandRect.y). For example i have drawn a man on its Surface who should run after a ball, i press the K_UP or K_DOWN and want also his legs to move (to have a more nice running picture!), so i draw them again at different positions and so on. So i need something more of controlling the frames rate i think.

2 Answers2

1

This is what the Clock module in pygame is for. Check my answer in this question https://stackoverflow.com/a/35620064/5878272 on how to do it.

Community
  • 1
  • 1
Fredrik
  • 1,389
  • 1
  • 14
  • 32
0

You can use thread, but the code can become messy...

Or you can set a "base" tick in your application, and then in your main loop, count iterations of the loop.

Example:

tick = 5 # one iteration = 5ms (it is the frame rate: 200FPS (theoric, of course! I think you might give an higer value)

#counters
rect1Count = 0
rect2Count = 2

delays 
rect1Delay = 10
rect2Delay = 30   

rect1Modulo = rect1Delay / tick # = 2
rect2Modulo = rect2Delay / tick # = 6

#main loop
while True:
    pygame.time.delay(tick)
    rect1Count +=1
    rect2Count +=1
    if rect1Count%rect1Modulo == 0:
         #move rect1 every 2 iteration (because 5 * 2 = 10)
         rect1Count = 0
    if rect2Count%rect2Modulo == 0:
         #every 3 iterations (so 5 * 6 = 30ms
         #move rect2
         rect2Count = 0
    #render code, etc...
    #You can easily add your K_UP and K_DOWN event here

I reset counter every iteration, to don't see counter values grow up too high...

Vincent
  • 1,016
  • 6
  • 11
  • Can you please send a link to read about Threads? Are they pygame-specific or common python Threads? –  Apr 02 '16 at 17:20
  • Thank you for your idea. Why are you setting `rect1Count` and `rect2Count` to 0 in the main loop, since your using `%` do you need that? –  Apr 02 '16 at 17:25
  • 1
    @AmirTeymuri I reset counters to 0 in the main loop, to prevent them for growing too high and using too many memory... But if you have infinite memory, you don't have to do this! – Vincent Apr 11 '16 at 07:21
  • 1
    And for threads, just see the doc : https://docs.python.org/3/library/threading.html?highlight=thread#module-threading (python 3.x) or https://docs.python.org/2.7/library/threading.html?highlight=thread#module-threading (python 2.x) – Vincent Apr 11 '16 at 07:25