1

I making an RTS style game in pygame. I want to move group of selected units all at once. I've implemented this that calculates the time it will take as well as the x and y speeds.

def update(dest_x,dest_y):
        dist_x = dest_x - marine.rect.centerx 
        dist_y = dest_y - marine.rect.centery

        dist = math.hypot(dist_x,dist_y)
        time = dist/25
        if time == 0:
            speed_x = 0
            speed_y = 0
        else:
            speed_x = dist_x/time
            speed_y = dist_y/time

I originally had a loop inside that that also did the movement like so:

def update(dest_x,dest_y):
        dist_x = dest_x - marine.rect.centerx 
        dist_y = dest_y - marine.rect.centery

        dist = math.hypot(dist_x,dist_y)
        time = dist/25
        if time == 0:
            speed_x = 0
            speed_y = 0
        else:
            speed_x = dist_x/time
            speed_y = dist_y/time

        for i in range (int(time)):
            marine.rect.centerx = marine.rect.centerx + speed_x
            marine.rect.centery = marine.rect.centery + speed_y

But the problem with that is that it just builds up the moves then does them all at once. Adding:

marine_list.draw(screen)

into the loop doesn't draw them every step of the way. Adding a wait function:

pygame.time.delay()

does not solve the problem either as it waits between each unit, not each movement. And in any case it once again moves them all at the end anyways. I suspect that it will not do anything like draw before completing the whole module so my thinking is that the drawing section needs to be in the main game loop with the update module returning time,speed_x and speed_y.

I guess my question is how do I take the returned values and structure my loop so that it only moves them once every time it goes through the loop but will stop after a certain amount of loops? I just started using python and I don't know how return works when returning more than one value.

Edit: This is how I'm calling the function, I check for a mouse click then check that it is the right mouse button.

if event.type == pygame.MOUSEBUTTONDOWN:
            if pygame.mouse.get_pressed()[2] == (1):
                for marine in marine_list:
                   Marine.update(mouse_pos[0],mouse_pos[1])
Andre
  • 47
  • 1
  • 5
  • Please show us the `Marine` class, and a more complete [minimal example](https://stackoverflow.com/help/mcve) that we can run. The `update` function that you've posted should probably be inside of the `Marine` class, so that it gets called once per marine instance each frame, and it looks like it needs to be changed. – skrx Jul 08 '17 at 05:50

0 Answers0