Python Forum

Full Version: object's movement to left leave shadow on the screen
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone. I've wrote a simple code using pygame and I want my image to move right and left and after collision to wall change direction. The problem is that when I run it in movement to left it has some shadow! in screen. It does move but it leaves something like a shadow of itself on the screen. What would be the problem?

here is my code:
import pygame 
pygame.init()
screen=pygame.display.set_mode((800,600)) 

pygame.display.set_caption('visual rhythm')
icon=pygame.image.load("song.png")
pygame.display.set_icon(icon)

playerImg=pygame.image.load('spaceship.png')
playerX=370
playerY=400
def player(x,y):
    screen.blit(playerImg,(x,y))

running=True
while running:
    screen.fill((0,255,0))
    
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    playerX+=0.2
    player(playerX,playerY)
    if playerX<=0:
        playerX+=0.2
        player(playerX,playerY)
    elif playerX>=746:
        while playerX>=0:
            playerX-=0.2
            player(playerX,playerY)
            pygame.display.update()
    pygame.display.update()
Line 28. Why is there another while loop inside your event loop?
Because I want it to move right again when it hits the left wall.
Look closely at that, and try to rethink how you can do it.
That inner-while loop is drawing the player over and over in multiple places, without ever clearing the screen. That's why you have the shadow... you never clear the screen.

In general, if you have the line pygame.display.update() in more than one place, there's probably a better way to organize your code.

For example, if you use a direction/velocity variable to keep track of which direction it should be moving (instead of a hardcoded +0.2 at the start of your event loop), you can just change the direction. Something like this (I don't have your images, so I changed the player to a white box):
import pygame 
pygame.init()
screen=pygame.display.set_mode((800,600)) 
 
pygame.display.set_caption('visual rhythm')
#icon=pygame.image.load("song.png")
#pygame.display.set_icon(icon)
 
#playerImg=pygame.image.load('spaceship.png')
playerImg = pygame.Surface((10, 10))
playerImg.fill((255, 255, 255))

playerX=370
playerY=400
def player(x,y):
    screen.blit(playerImg,(x,y))
 
directionX = 0.2
running=True
while running:
    screen.fill((0,255,0))
     
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    playerX += directionX
    player(playerX,playerY)
    if playerX<=0:
        directionX = 0.2
        player(playerX,playerY)
    elif playerX>=746:
        directionX = -0.2
    pygame.display.update()