Search code examples
pythonpygamemoverect

PyGame Rect Updates But Won't Move In My while Loop?


i want to Simulate Spring Physics but i dont know How can i use PyGame To Update The Rect.

but when i run my code nothing works the rect wont move can someone please help me??? here is my code:

maxmag = 100
mag = 100

screen.fill((255, 255, 255))
ball = pygame.draw.circle(screen, (0, 0, 255), (250, 250 + mag), 75)
cube = pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(250,0,10,250 + mag))

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    mag -= 1
    if mag <= -maxmag:
        maxmag -= 10
        mag = maxmag

    cube = pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(250,0,10,250 + mag))
    cube.update(pygame.Rect(250,0,10,250 + mag))
    #cube = pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(250,0,10,250 + mag))

    print(mag)

    clock.tick(60)

    pygame.display.flip()

pygame.quit()

thank you for reading :D


Solution

  • This is how animation works with pygame:

    import pygame
    
    pygame.init ()
    screen = pygame.display.set_mode ((600, 400))
    clock = pygame.time.Clock ()
    
    x_step = 2
    y_step = 2
    x = y = 100
    running = True
    while running :
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        screen.fill ((255, 255, 255))
        pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(x,y,50,50))
        x += x_step
        if x > 550  or x < 0 : x_step = -x_step
        y += y_step
        if y > 350 or y < 0 : y_step = -y_step
        pygame.display.flip()
        clock.tick (70)
    
    pygame.quit()