1 回答
TA贡献1830条经验 获得超3个赞
您必须使用键盘事件KEYDOWN
(请参阅pygame.event
)而不是pygame.key.get_pressed()
。用于获取自调用pygame.time.get_ticks()
以来的毫秒数。pygame.init()
存储按下按键的时间。如果在一定时间内按下按钮两次,则增加速度:
key_time = 0
fast_key_time = 500 # 0.5 seconds
while True:
current_time = pygame.time.get_ticks()
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if to_x1 == -5 and current_time < key_time + fast_key_time:
to_x1 = -10
else:
to_x1 = -5
key_time = current_time
if event.key == pygame.K_RIGHT:
if to_x1 == 5 and current_time < key_time + fast_key_time:
to_x1 = 10
else:
to_x1 = 5
key_time = current_time
CHARIC_1.xpos1 = CHARIC_1.xpos1 + to_x1
# [...]
最小的例子:
import pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
to_x1 = 0
key_time = 0
fast_key_time = 500 # 0.5 seconds
run = True
while run:
current_time = pygame.time.get_ticks()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if to_x1 == -5 and current_time < key_time + fast_key_time:
to_x1 = -10
else:
to_x1 = -5
key_time = current_time
if event.key == pygame.K_RIGHT:
if to_x1 == 5 and current_time < key_time + fast_key_time:
to_x1 = 10
else:
to_x1 = 5
key_time = current_time
rect.x += to_x1
rect.centerx = rect.centerx % window.get_width()
rect.centery = rect.centery % window.get_height()
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), rect)
pygame.display.flip()
添加回答
举报