Moving a rectangle with python3

Viewed 46

I am trying to make a rectangle move in pygame Here is the code that I am trying to get to work:

currBlock1 = pygame.draw.rect(surface, (0, 255, 255), (340, 50, 60, 30))
currBlock2 = pygame.draw.rect(surface, (0, 255, 255), (310, 80, 60, 30))
currBlock1.move(340, 80)
currBlock2.move(310, 110)

What is wrong here?

1 Answers

pygame.Rect.move doesn't move the rectangle itself. The method returns a new and moved rectangle. You have to use pygame.Rect.move_ip, which operates in place. Further the argument to move/move_ip is an offset rather than a position:

currBlock1.move_ip(0, 30)
currBlock2.move_ip(0, 30)

Actually you recreate the same rectangles in every frame. You need to construct the pygame.Rect() objects before the application loop and you have to move it in the loop:

currBlock1 = pygame.Rect(340, 50, 60, 30)
currBlock2 = pygame.Rect(310, 80, 60, 30)

# application loop
while run:

    # [...]

    pygame.draw.rect(surface, (0, 255, 255), currBlock1)
    pygame.draw.rect(surface, (0, 255, 255), currBlock2)
    currBlock1.move_ip(0, 30)
    currBlock2.move_ip(0, 30)
Related