【问题标题】:Complete drawing a circle in a specific amount of time在特定时间内完成画圆
【发布时间】:2019-05-20 02:06:22
【问题描述】:

我正在尝试用圆圈创建倒计时。圆圈将显示与给定时间相比已经过去了多少时间。因此,如果倒计时是 10 秒并且已经过了 5 秒,则将绘制半圈。我想出了这段代码:

from math import pi
import pygame


pygame.init()

(x, y) = (800, 600)
screen = pygame.display.set_mode((x, y))
clock = pygame.time.Clock()

radius = 50
# Just to place the circle in the center later on
top_left_corner = ((x / 2) - (radius / 2), (y / 2) - (radius / 2))
outer_rect = pygame.Rect(top_left_corner, (radius, radius))

countdown = 1000  # seconds

angle_per_frame = 2 * pi / (countdown * 60)
angle_drawn = 0
new_angle = angle_per_frame
while True:
    if angle_drawn < 2 * pi:
        new_angle += angle_drawn + angle_per_frame
        pygame.draw.arc(screen, (255, 255, 255), outer_rect, angle_drawn, new_angle, 10)
        angle_drawn += angle_per_frame
    clock.tick(60)
    pygame.display.update(outer_rect)

所以fps = 60 在每一帧中我都在画2 * pi / countdown * fps,将一个完整的圆圈分成几帧。然后在每一帧中,画出圆圈的一部分。似乎画的圈很好,但不能用于定时器,原因有二:

  1. 这个圆圈似乎比给定的时间更短。

  2. 在画圆时,圆的最后一部分似乎画得更快。

谁能指出我做错了什么?

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    问题是您将new_angle 增加了angle_drawn + angle_per_frame,并且因为您将angle_per_frame 添加到angle_drawn,所以每一帧都会更大。

    我宁愿使用clock.tick 返回的增量时间,否则如果帧速率不是恒定的,可能会出现不准确的情况。然后将angle_per_second 的值乘以dt 以获得该帧的正确值。

    另外,因为如果角度差太小,pygame.draw.arc 不起作用,我不得不从起始角度减去 0.2,并且必须在绘图开始前添加一个短暂的延迟。

    from math import pi
    import pygame
    from pygame import freetype
    
    
    pygame.init()
    
    x, y = 800, 600
    screen = pygame.display.set_mode((x, y))
    clock = pygame.time.Clock()
    FONT = freetype.Font(None, 32)
    WHITE = pygame.Color('white')
    
    radius = 50
    # Just to place the circle in the center later on
    top_left_corner = (x/2 - radius/2, y/2 - radius/2)
    outer_rect = pygame.Rect(top_left_corner, (radius, radius))
    
    countdown = 10  # seconds
    angle_per_second = 2*pi / countdown
    angle = 0
    dt = 0  # dt is the time since the last clock.tick call in seconds.
    time = 0
    
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
    
        time += dt
        angle += angle_per_second * dt
        # Delay the drawing a little bit, because draw.arc doesn't work
        # with very small angle differences.
        if angle > 0.2:
            pygame.draw.arc(screen, WHITE, outer_rect, angle-0.2, angle, 10)
    
        rect = pygame.draw.rect(screen, (50, 50, 50), (400, 340, 100, 50))
        FONT.render_to(screen, (410, 350), str(round(time, 2)), WHITE)
        dt = clock.tick(60) / 1000  # / 1000 to convert it to seconds.
        pygame.display.update([outer_rect, rect])
    

    【讨论】:

    • 太好了,谢谢!我发现起始角度总是0,不用担心小角度!
    猜你喜欢
    • 2014-02-10
    • 2020-02-23
    • 2013-07-07
    • 2012-01-28
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多