2

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?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
kekula
  • 21
  • 5

1 Answers1

1

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)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • I tried it right now, doesn't work either – kekula Oct 11 '20 at 06:22
  • I tried again, this time with predefined Rect objects. It still won't work. I don't know why, honestly. – kekula Oct 11 '20 at 06:42
  • Sorry, but it stll won't work for some reason. Maybe I should use blit() instead? – kekula Oct 11 '20 at 07:00
  • Here is the link to my pastebin with full code: https://pastebin.com/J2kenAmL – kekula Oct 11 '20 at 07:07
  • @kekula You have to redraw the rectangle after you've changed its position. The rectangle are just pixels on the pixels on the screen. Read the answer to [Why is my pygame application loop not working properly?](https://stackoverflow.com/questions/60387348/how-to-make-a-camera-for-a-2d-topdown-game-in-pygame/60390374#60390374) – Rabbid76 Oct 11 '20 at 07:16