如何放慢pygame中的动画?

时间:2018-07-02 07:16:35

标签: python animation pygame

我正在尝试使太阳升起。太阳的起始位置将刚好超出屏幕右下角,在每个循环中,太阳将向左上角移动10点。我将这段代码放在while循环中,以便太阳在到达特定点后停止移动。

但是,当我运行程序时,我看不到我期望的朝阳效果。取而代之的是,太阳只是在我放置的两个x,y坐标上停止了。我以为是因为我的程序太快了,所以我尝试将clock.tick减少到不同的秒数,但这样做的唯一目的是增加程序开始与结束点到太阳直刺之间的时间差。

到目前为止,这是我的代码。为了使代码看起来令人困惑,我还要设置其他动画:

import pygame
import random
import time

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
GREY = (169,169,169)
ORANGE = (255,140,0)
YELLOW  = (255,255,0)

pygame.init()

# Set the width and height of the screen [width, height]
size = (700, 500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("First animation")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

colour_list = []

default_colours = [BLACK,BLACK,BLACK]


one_colour = RED
two_colour = ORANGE
three_colour = GREEN

colour_list = [one_colour,two_colour,three_colour]


#starting position of the sun

circle_x = 750
circle_y = 550

#speed and direction of circle
circle_change_x = -5
circle_change_y = -5



 # -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True




    screen.fill(WHITE)


    # animates the rising of the sun
    pygame.draw.circle(screen,YELLOW,[circle_x,circle_y],50)

    #moves the sun's starting point
    while circle_x >=50 and circle_y >=50:
        circle_x += circle_change_x
        circle_y  += circle_change_y








    #draws the road
    pygame.draw.rect(screen,BLACK,[0,400,700,100],0)
    pygame.draw.rect(screen,WHITE,[100,430,100,25],0)
    pygame.draw.rect(screen,WHITE,[300,430,100,25],0)
    pygame.draw.rect(screen,WHITE,[500,430,100,25],0)


    #draws the street light
    x_position = 345
    y_position = 225
    pygame.draw.rect(screen,GREY,[350,300,15,100],0)
    pygame.draw.rect(screen,BLACK,[x_position,y_position,25,75],0)
    circle_list = []
    for i in range(3):
        y_position += 20
        circle = pygame.draw.circle(screen,default_colours[i],[358,y_position],7)
        circle_list.append(circle)







    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

# Close the window and quit.
pygame.quit()

1 个答案:

答案 0 :(得分:1)

您正在更改while循环中的太阳位置,此while循环将一直运行直到条件circle_x >= 50 and circle_y >= 50False为止。由于此时屏幕将不会更新,并且由于循环将在几秒钟内完成,因此太阳将立即出现在目标位置。

while更改为ifif circle_x >= 50 and circle_y >= 50:,然后圆圈将每帧仅移动一次,直到条件为False。