我早些时候问过这个问题,但是我认为自己说错了,所以这次我要添加图片。
我有一个游戏,在屏幕底部有一个人(实际上是唐纳德·特朗普),向来袭的敌人向上方射击子弹。
他有枪,在枪管末端,我想补充一点,当我按下空格键时会出现火焰精灵,在300ms之后它将消失(直到我再次按下空格键并继续循环)。
以下是游戏的图片以及我的意思:
我该怎么做? :)
答案 0 :(得分:0)
只需创建一个变量即可存储超时值(如果按下该键),并从该值中减去经过每一帧的时间。
如果该值> 0,则显示带有火焰的图像。如果该值为0,则显示没有火焰的图像。
这是我一起砍的一个简单例子:
import pygame
class Actor(pygame.sprite.Sprite):
def __init__(self, *grps):
super().__init__(*grps)
# create two images:
# 1 - the no-fire-image
# 2 - the with-fire-image
self.original_image = pygame.Surface((100, 200))
self.original_image.set_colorkey((1,2,3))
self.original_image.fill((1,2,3))
self.original_image.subsurface((0, 100, 100, 100)).fill((255, 255, 255))
self.fire_image = self.original_image.copy()
pygame.draw.rect(self.fire_image, (255, 0, 0), (20, 0, 60, 100))
# we'll start with the no-fire-image
self.image = self.fire_image
self.rect = self.image.get_rect(center=(300, 240))
# a field to keep track of our timeout
self.timeout = 0
def update(self, events, dt):
# every frame, substract the amount of time that has passed
# from your timeout. Should not be less than 0.
if self.timeout > 0:
self.timeout = max(self.timeout - dt, 0)
# if space is pressed, we make sure the timeout is set to 300ms
pressed = pygame.key.get_pressed()
if pressed[pygame.K_SPACE]:
self.timeout = 300
# as long as 'timeout' is > 0, show the with-fire-image
# instead of the default image
self.image = self.original_image if self.timeout == 0 else self.fire_image
def main():
pygame.init()
screen = pygame.display.set_mode((600, 480))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
dt = 0
sprites_grp = pygame.sprite.Group()
# create out sprite
Actor(sprites_grp)
# standard pygame mainloop
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
sprites_grp.update(events, dt)
screen.fill((80, 80, 80))
sprites_grp.draw(screen)
pygame.display.flip()
dt = clock.tick(60)
if __name__ == '__main__':
main()