[英]Continuous object creation in pygame?
好的,所以我对这个话题进行了一些研究。 我正在用Python的Pygame创建一个游戏,这是着名的“Raiden 2”的复制品。 我的游戏循环与我见过的游戏循环非常相似。 我正在尝试做的是让构造函数创建一个子弹对象(使用我的Bullet类),同时保持空格键。 但是,以下代码仅为每个按键创建一个子弹。 按住按钮什么都不做,只需创建一个子弹。
while game.play is True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
b = Bullet(x, y)
bullet_group.add(b)
bullet_group.draw(screen)
不知道从哪里开始。 任何帮助都是受欢迎和赞赏的。
这应该按照您的预期工作:
addBullets = False
while game.play is True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
addBullets = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
addBullets = False
if addBullets:
b = Bullet(x, y)
bullet_group.add(b)
bullet_group.draw(screen)
您将子弹的创建从事件处理中移除,并设置只有一个“标志”,如果释放该键以停止创建子弹,则将其取回。
并且......正如jsbueno
的评论中所提到的,这也将起作用:
while game.play is True: for event in pygame.event.get(): pass # do something with events if pygame.key.get_pressed()[pygame.K_SPACE]: b = Bullet(x, y) bullet_group.add(b)
我认为另一个答案是缺乏一个重要的细节。 你很可能不想每帧发射子弹,所以你需要有一些计时器。 最简单的方法是计算帧数,但随后游戏将受到帧速率限制(最好不要这样做)。
firing = False
bullet_timer = 0
while game.play:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game.play = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
firing = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
firing = False
if bullet_timer > 0:
bullet_timer -= 1
elif firing: # Timer is less than 0 and we're firing.
bullet = Bullet()
bullet_group.add(bullet)
bullet_timer = 10 # Reset timer to 10 frames.
与帧速率无关的变体是使用pygame.Clock.tick
返回的时间(自上次调用以来经过的时间)并从timer变量中减去它。 如果计时器<= 0
我们就准备开火了。
clock = pygame.time.Clock()
firing = False
bullet_timer = 0
while game.play:
# `dt` is the passed time since the last tick in seconds.
dt = clock.tick(30) / 1000
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
firing = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
firing = False
if bullet_timer > 0:
bullet_timer -= dt
elif firing: # Timer is below 0 and we're firing.
bullet = Bullet()
bullet_group.add(bullet)
bullet_timer = .5 # Reset timer to a half second.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.