Skip to content Skip to sidebar Skip to footer

My Pygame Character Leaves Trails When I Move It

I've been trying to make a game in Python but when I move my character it leaves a trail behind. I know it doesn't show that much but if you get close you can see the trail and it

Solution 1:

Before you flip the display you need to blit the background. This will 'erase' the trail. Then draw the current image and flip the display.

    disp.blit(background, (0,0)) # or whatever location you need
    disp.blit(current_image, (x,y))
    pygame.display.flip()

Solution 2:

This is a complete solution with a scrolling background:

import pygame

pygame.init()
width = 800
height = 600
black = (0, 0, 0)
white = (255, 255, 255)
ship_width = 56
ship_height = 64
disp = pygame.display.set_mode((width, height))
pygame.display.set_caption("space_game")
clock = pygame.time.Clock()
background = pygame.image.load('background.png')
background_height = background.get_rect().height
ship = pygame.image.load('ship.png')

def game_loop():
    x = width * 0.45
    y = height * 0.80
    x_ch = 0
    y_ch = 0
    x_bg = 0
    game_exit = False
    while not game_exit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    x_ch = -5
                if event.key == pygame.K_d:
                    x_ch = 5
                if event.key == pygame.K_w:
                    y_ch = -5
                if event.key == pygame.K_s:
                    y_ch = 5
                if (event.key == pygame.K_ESCAPE) or (event.key == pygame.K_q):
                    game_exit = True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    x_ch = 0
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    y_ch = 0
        if (x + x_ch) > width - ship_width or (x + x_ch) < 0:
            x_ch = 0
        if (y + y_ch) > height - ship_height or (y + y_ch) < 0:
            y_ch = 0
        x += x_ch
        y += y_ch
        x_loop = x_bg % background_height
        disp.blit(background, (0, x_loop - background_height))
        if x_loop < height:
            disp.blit(background, (0, x_loop))
        x_bg += 5
        disp.blit(ship, (x, y))
        pygame.display.update()
        clock.tick(60)

game_loop()
pygame.quit()

The result:

space_game.gif

A ship with transparent background:

ship.png

The starry background:

background.png

I am posting this answer in case someone needs a working example as a starting point.


Solution 3:

I think you're missing a pygame.display.flip(). Add it after your pygame.display.update() line.


Post a Comment for "My Pygame Character Leaves Trails When I Move It"