如何使图像从天空中落下



我现在有我想要使用的图像,并且知道你需要在y方向上使用重力和速度,但我想知道如何最好地将它们放在一个类中。

如果可能的话,我也想知道如何制作,这样图像就有随机出现和掉落的机会。

下面是一个可能的示例:

import pygame
import random

pygame.init()
screen = pygame.display.set_mode((900, 600))
clock = pygame.time.Clock()

class FallingImage:
def __init__(self, file, x, y, width, height):
self.file = file
self.x = x
self.y = y
self.width = width
self.height = height
self.image = pygame.transform.scale(pygame.image.load(self.file).convert_alpha(), (self.width, self.height))
def draw(self):
screen.blit(self.image, (self.x, self.y))

falling_img = FallingImage('your_image.png', 300, -100, 50, 100)
run = True
while run:
clock.tick(60)
screen.fill((0, 0, 0))
falling_img.draw()
falling_img.y += 25
if falling_img.y > 600:
falling_img.y = -150
falling_img.x = random.randint(0, 900)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()

最新更新