How to animate an object from left to right on screen without it trailing?

Viewed 35

how can I make it so my draw cloud function will move left to right just once on my screen without creating a trail? I tried moving my for loop into my while loop but that didn't work.

import pygame
pygame.init()
size = (640, 480)

win = pygame.display.set_mode(size)

width = win.get_width()
height = win.get_height()

blue = (135, 255, 255)

def draw_cloud(x, y, size):
  pygame.draw.circle(win, (255,255,255), (x, y), int(size* .5))
  pygame.draw.circle(win, (255,255,255), (int(x + size * .5), y), int(size * .6))
  pygame.draw.circle(win, (255,255,255), (x + size, int(y - size * .1)), int(size * .4))

pygame.draw.rect(win, (0,160,3), (0,400,640,80))
pygame.draw.rect(win, (135,255,255), (0,0,640,400))

for i in range(60, 600, 100):
    draw_cloud(i, 120, 80)
    pygame.display.update()

running = True
myClock = pygame.time.Clock()

while running:
   for event in pygame.event.get():
     if event.type == pygame.QUIT:
       running = False
  
   myClock.tick(60)

pygame.quit()
1 Answers

You have draw the entire scene continuously in the application loop and you have to clear the background with fill():

import pygame
pygame.init()
size = (640, 480)

win = pygame.display.set_mode(size)
myClock = pygame.time.Clock()

width = win.get_width()
height = win.get_height()
blue = (135, 255, 255)

def draw_cloud(x, y, size):
  pygame.draw.circle(win, (255,255,255), (x, y), int(size* .5))
  pygame.draw.circle(win, (255,255,255), (int(x + size * .5), y), int(size * .6))
  pygame.draw.circle(win, (255,255,255), (x + size, int(y - size * .1)), int(size * .4))

x = 640
running = True
while running:
   for event in pygame.event.get():
     if event.type == pygame.QUIT:
       running = False

   win.fill(0)
   pygame.draw.rect(win, (0,160,3), (0,400,640,80))
   pygame.draw.rect(win, (135,255,255), (0,0,640,400))  
   draw_cloud(x, 120, 80)
   pygame.display.update()
   
   x -= 1
   if x < -120:
       x = 640

   myClock.tick(60)

pygame.quit()

The typical PyGame application loop has to:

Related