尝试使用pygame启用射击弹丸。当我按下太空按钮后,它只发射1个子弹,fps从100下降到〜30,玩家角色无法移动并且对按钮按下没有反应。在弹丸停止动画后,fps返回到100,我可以按计划移动和射击最多3个弹丸,但是fps再次下降,直到最后一个弹丸到达边界时,我才能移动。
我之前加载的是项目符号图像,而不是绘制项目符号,并以为案件在其中。但是结果并没有改变。我还尝试重新排序blit()
函数,但也没有任何变化。
class Game():
# Some game stuff and functions
def __init__(self):
self.x_default = 800
self.y_default = 600
self.screen = pygame.display.set_mode((self.x_default, self.y_default))
#self.background = pygame.image.load('IMGs/BCK2.bmp').convert()
self.title = 'Title'
self.fps = 100
class Projectile():
# This class is supposed to make projectiles
def __init__(self, x, y, speed_x=5, direction=1, width=10, height=10):
# x&y - starting positions of projectiles
# speed_x & speed_y - starting moving speeds of projectiles in # oX & oY
# a - speed increase over time (cancelled for now)
# direction - stays for its' name
# Directions: [2, 3, 1, 4, 5, 6, -1, 7] starting from 0:00 and moving towards the right side of the clock
self.x = x
self.y = y
self.speed_x = speed_x
self.direction = direction
self.width = width
self.height = height
self.img = pygame.Rect(self.x, self.y, self.width, self.height)
def move_projectile(self, x, speed_x, direction):
# Moves stuff
# For now direction works only in right-left (1 for right, -1 for left)
x += speed_x * direction
return x
while 1:
if pygame.event.poll().type == pygame.QUIT:
sys.exit()
for pr in projectiles:
if (pr.x >= -pr.width) and (pr.x <= Game().x_default):
pr.x = pr.move_projectile(x=pr.x, speed_x=pr.speed_x, direction=pr.direction)
else:
projectiles.remove(pr)
keys = pygame.key.get_pressed()
# ------------ oX moving --------------
if keys[pygame.K_LEFT]:
P.x -= P.speed
P.direction = -1
if keys[pygame.K_RIGHT]:
P.x += P.speed
P.direction = 1
# ------------ Shooting ----------------
if keys[pygame.K_SPACE]:
if len(projectiles) < 3:
if P.direction > 0:
projectiles.append(Projectile(x=P.x + P.width, y=P.y + P.height//2, direction=1))
else:
projectiles.append(Projectile(x=P.x, y=P.y + P.height//2, direction=-1))
# ---------- The blitting process --------------
G.screen.blit(G.background, (0, 0))
G.screen.blit(Block1.img, (Block1.x, Block1.y))
G.screen.blit(Block2.img, (Block2.x, Block2.y))
for pr in projectiles:
pygame.draw.rect(G.screen, (0, 0, 0), pr.img)
G.screen.blit(P.img, (P.x, P.y))
pygame.display.update()
pygame.time.delay(1000//G.fps)
答案 0 :(得分:0)
keys[pygame.K_SPACE]
就是True
。这意味着只要按住键,就会连续生成多个项目符号。
如果要创建单个项目符号,请按 SPACE ,然后使用KEYDOWN
事件(请参见pygame.event
)。
该事件仅在按键时每次发生一次。例如:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if len(projectiles) < 3:
if P.direction > 0:
projectiles.append(Projectile(x=P.x + P.width, y=P.y + P.height//2, direction=1))
else:
projectiles.append(Projectile(x=P.x, y=P.y + P.height//2, direction=-1))
keys = pygame.key.get_pressed()
# [...]