如何解决我将如何随机旋转和缩放从 pygame 中的类创建的每个精灵
我正在尝试清理我的代码,并将脚本移动到不同的文件。我想将我的图像(在这种情况下,流星)放在随机位置,随机旋转和大小。我可以让它去随机的地方,但就是不知道如何随机缩放和旋转它。 这是我以前使用的,它给了我想要的东西,随机大小和随机位置旋转的流星。
import pygame,random
screen = pygame.display.set_mode((1280,720))
pic = pygame.image.load('assets/meteor.png').convert_alpha()
rotimage = pygame.transform.rotozoom(pic,random.randint(0,359),random.randint(1,2))
random_x = random.randint(0,1280)
random_y = random.randint(0,720)
while True:
screen.blit(rotimage,(random_x,random_y))
pygame.display.update()
它像这样工作得很好,但我不知道如何在另一个文件中应用它。我的第二个 python 文件看起来像这样。
import random
import pygame
display_width = 1280
display_height = 720
rotation = random.randint(0,359)
size = random.randint(1,2)
pic = pygame.image.load('assets/meteor.png')
pygame.init()
class Meteor(pygame.sprite.Sprite):
def __init__(self,x=0,y=0):
pygame.sprite.Sprite.__init__(self)
self.image = pic
self.rect = self.image.get_rect()
self.rect.center = (x,y)
all_meteors = pygame.sprite.Group()
for i in range(3):
new_x = random.randrange(0,display_width)
new_y = random.randrange(0,display_height)
pygame.transform.rotozoom(pic,rotation,size) # How do I put this in
all_meteors.add(Meteor(new_x,new_y)) #this only allows x and y
我的新主文件看起来像这样
while True:
meteors.all_meteors.update()
meteors.all_meteors.draw(screen)
pygame.display.update()
解决方法
我认为首先创建一个 Meteor 对象,然后在将其添加到 all_meteors 之前更新它的图片应该可以解决问题。也许用这样的东西替换 for 循环:
for i in range(3):
new_x = random.randrange(0,display_width)
new_y = random.randrange(0,display_height)
met = Meteor(new_x,new_y)
rotation = random.randint(0,359) # Some line here to pick a random rotation
size = random.randint(1,3) # some line here to pick a random scale
met.pic = pygame.transform.rotozoom(met.pic,rotation,size) # How do I put this in
all_meteors.add(met) #this only allows x and y
注意:我忘记了 pygame.transform.rotozoom()
是否是就地操作。如果是,则将 met.pic = pygame.transform.rotozoom()
替换为 pygame.transform.rotozoom()
-- 删除 met.pic =
。
另一种方法是直接调整类:
class Meteor(pygame.sprite.Sprite):
def __init__(self,x=0,y=0):
pygame.sprite.Sprite.__init__(self)
self.rotation = random.randint(0,359)
self.size = random.randint(1,2)
self.image = pic
self.image = pygame.transform.rotozoom(self.image,self.rotation,self.size)
self.rect = self.image.get_rect()
self.rect.center = (x,y)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。