【发布时间】:2020-01-04 08:45:45
【问题描述】:
我正在制作一个射击游戏,其中包含一个可以射击“子弹”的“玩家”。按“WASD”可以控制播放器的移动,按“Space”可以使“播放器”射击。现在我希望 Pygame 能够以不同的速度响应长按的按键。例如,每 10 毫秒响应一次“WASD”,每 1000 毫秒响应一次“空格”。我该怎么办?
我已经尝试过 pygame.key.set_repeat() 并且每个键都会以相同的速度响应。
【问题讨论】:
我正在制作一个射击游戏,其中包含一个可以射击“子弹”的“玩家”。按“WASD”可以控制播放器的移动,按“Space”可以使“播放器”射击。现在我希望 Pygame 能够以不同的速度响应长按的按键。例如,每 10 毫秒响应一次“WASD”,每 1000 毫秒响应一次“空格”。我该怎么办?
我已经尝试过 pygame.key.set_repeat() 并且每个键都会以相同的速度响应。
【问题讨论】:
pygame.key.set_repeat() 设置整个键盘的延迟,它不能区分按键。您需要在您的程序中执行此操作。
一种可能的解决方案是使用set_repeat 将重复事件之间的延迟设置为您希望在游戏中拥有的最短间隔。对于需要较长时间间隔的键,您需要自己检查是否经过了足够的时间来“接受”事件并允许执行相应的操作。
这个示例代码应该让你明白我的意思。
import sys
import pygame
#the action you want to perform when the key is pressed. Here simply print the event key
#in a real game situation, this action would differ according to the key value
def onkeypress(event):
print(event.key)
#dict of key constants for which you want a longer delay and their tracking time
#in ms, initialized to 0. Here only the spacebar
repeat1000 = {pygame.K_SPACE : 0}
pygame.init()
screen = pygame.display.set_mode((500, 500))
#sets repeat interval to 10 milliseconds for all keys
pygame.key.set_repeat(10)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
current_time = pygame.time.get_ticks()
if event.key in repeat1000.keys():
if current_time - repeat1000[event.key] > 1000:
repeat1000[event.key] = current_time
onkeypress(event)
elif event.key in [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d]:
onkeypress(event)
如果您尝试上面的代码,您会看到如果您按住空格键,则每秒都会打印空格键的键(在我的系统上为 32)。如果您按 W A S D 之一,则每 0.01 秒打印一次相应的键(在我的系统上为 119、97、115、100)。
【讨论】: