Python 我正在尝试使用pygame group模块射击多发子弹,但我没有';I don’我不知道如何正确地做这件事
问题1:我尝试使用pygame组类模块最多发射5发子弹,但我最多只能发射1发子弹 这是bullet类:Python 我正在尝试使用pygame group模块射击多发子弹,但我没有';I don’我不知道如何正确地做这件事,python,pygame,Python,Pygame,问题1:我尝试使用pygame组类模块最多发射5发子弹,但我最多只能发射1发子弹 这是bullet类: class Bullets(pygame.sprite.Sprite): def __init__(self,image,location): pygame.sprite.Sprite.__init__(self) self.image = image self.rect=self.image.get_rect() self.location =location
class Bullets(pygame.sprite.Sprite):
def __init__(self,image,location):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect=self.image.get_rect()
self.location =location
self.rect.left,self.rect.top = self.location
下面:我将“子弹”设定为精灵
def bullet_group(group):
for bullet in group:
print(group.sprites)
group.remove(bullet)
# After shooting a bullet, I want to remove the bullet from the group
# in order to change the 'shoot_point'(which is the location of the bullet)
# back to where it starts
shoot_point_x = fixed_shoot_point_x #fixed_shoot_point is the start location
shoot_point_y = fixed_shoot_point_y #of the bullet
group.add(bullet)
在主while循环之前:
group=pygame.sprite.Group()
for i in range(0,5):
group.add(bullet)
我做了5颗子弹精灵
在下面的主代码中:
if event.type == pygame.KEYDOWN:
if #some code
elif event.key == pygame.K_SPACE:
fixed_bullet_speed_change = [round(-(math.cos(math.atan2(RealTank.Trect.centery-shoot_point_y,RealTank.Trect.centerx-shoot_point_x))),1)*10,round(-(math.sin(math.atan2(RealTank.Trect.centery-shoot_point_y,RealTank.Trect.centerx-shoot_point_x))),1)*10]
# the line of code above is just some calculations that is not related to the question
group.remove(bullet)
# I removed the sprite from the group after shooting some bullets, in order to
# shoot another one
if event.type == pygame.KEYUP:
if #some code
elif event.key == pygame.K_SPACE:
group.add(bullet)
# adding back another one
有人知道我做错了什么吗
问题2:
当我执行“打印(group.sprites)”并按“空格键”时,我每次按它都会得到更多的sprites
==================================================================
下面是我所有的代码:(你不需要看到它……这是不必要的)
尝试下面的代码,将我的问题可视化
图片:
只创建bullet的一个实例-需要5个实例
group = pygame.sprite.Group()
for i in range(5):
bullet = Bullets(RealTank.bullet_image, [shoot_point_x, shoot_point_y])
group.add(bullet)
医生::
将任意数量的精灵添加到此组这将只添加精灵
尚未成为该组成员的。
在
while循环中
创建新的bulletbullet=Bullets()
(变量名bullet
无所谓,id(bullet)
无所谓)并尝试删除它(remove(bullet)
),但此实例不在组中,因此它不删除任何内容。后来你添加了bullet(add(bullet)
),它添加了它,因为这个实例还不在组中。我不知道把remove(bullet)和add(bullet)放在哪里。。。你能帮忙吗?至于我,remove()
和add()
都在合适的位置,但是bullet=Bullets()
放错了位置。它应该在add()
之前。顺便说一句:我认为最大的错误是:在中,当为True时,您创建了项目符号的新实例(和坦克
),以在新位置显示它。这没有意义。创建一个Tank实例,并在需要时仅更改其参数。子弹也是一样,只有在发射新子弹时才创建新实例,而不是一直。
group = pygame.sprite.Group()
for i in range(5):
bullet = Bullets(RealTank.bullet_image, [shoot_point_x, shoot_point_y])
group.add(bullet)