Python:Pygame:如何让小球沿sin()曲线动?

1 投票
1 回答
3998 浏览
提问于 2025-04-17 14:33

你怎么让一个球像正弦曲线那样,重复地波动移动呢?

1 个回答

5

你可以使用一个计数器,或者用pygame里的Clock,也可以直接用pygame.time.get_ticks来计算时间。下面有一些示例代码可以帮助你入门。

import math
import pygame

pygame.init()
screen = pygame.display.set_mode((400,400))

while True:
    t = pygame.time.get_ticks() / 2  % 400 # scale and loop time
    x = t
    y = math.sin(t/50.0) * 100 + 200       # scale sine wave
    y = int(y)                             # needs to be int

    screen.fill((0,0,0))
    pygame.draw.circle(screen, (255,255,255), (x, y), 40)

    pygame.display.flip()

撰写回答