1

Whenever I attempt to move the yellow spaceship in my Pygame tutorial, it moves slightly but then goes back to its initial position. I'm following a tutorial, and can't seem to find the error. Can someone help me?


def draw_window(red,yellow):
    gameDisplay.fill(PURPLE)
    gameDisplay.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y))
    gameDisplay.blit(RED_SPACESHIP, (red.x, red.y))

    pygame.display.update()
    pygame.display.flip()


def yellow_handle_movement(keys_pressed,yellow):

    if keys_pressed[pygame.K_a]:  # LEFT
        yellow.x -= VELOCITY
    if keys_pressed[pygame.K_d]:  # RIGHT
        yellow.x += VELOCITY
    if keys_pressed[pygame.K_w]:  # UP
        yellow.y -= VELOCITY
    if keys_pressed[pygame.K_s]:  # DOWN
        yellow.y += VELOCITY


while True:
    red = pygame.Rect(750, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
    yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)


    clock = pygame.time.Clock()
    for event in pygame.event.get():
        clock.tick(FPS)
        if event.type == pygame.QUIT:
            sys.exit(0)
        keys_pressed = pygame.key.get_pressed()
        yellow_handle_movement(keys_pressed, yellow)

        draw_window(red,yellow)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Joe biden
  • 13
  • 3

2 Answers2

0

You must draw and move the object in the application loop, not in the event loop. The event is executed only when an event occurs, but the application loop is executed in every frame. The object must be created once before the application loop, not constantly in the loop. When the objects are created in the loop, it causes the objects to be continuously recreated at the original position.

red = pygame.Rect(750, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)

while True:

    clock = pygame.time.Clock()
    for event in pygame.event.get():
        clock.tick(FPS)
        if event.type == pygame.QUIT:
            sys.exit(0)
    
    # INDENTATION
    #<--|
    keys_pressed = pygame.key.get_pressed()
    yellow_handle_movement(keys_pressed, yellow)

    draw_window(red,yellow)

The typical PyGame application loop has to:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • @Joebiden The code in my answer is tested and works fine. Please read [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Rabbid76 Jun 17 '23 at 18:22
0

You are resetting your red and yellow object every time in your loop. Move it out before the loop as

...
red = pygame.Rect(750, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)
yellow = pygame.Rect(100, 300, SPACESHIP_WIDTH, SPACESHIP_HEIGHT)

while True:
    ...
Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53