问题描述
如果 pygame 程序只是一个基本实体,您可以使用箭头键正常移动,我怎么能这样做,如果按下空格,基于按下时按住的箭头键,玩家会冲刺稍微向指定方向?我的想法是,当按下空格时,程序会检查其他键是否被按下,并基于此快速增加 x 和/或 y 坐标,然后在特定时间停止,但我不知道如何制作停止,因为所有这些都发生在主游戏循环中。任何见解都受到高度赞赏。
解决方法
您可以使用 time.perf_counter
。
因此要使用该功能,您需要导入模块 time
import time
现在您可以在按下空格时将 time.perf_counter
的值存储在变量中。
import time
jumping = False
start_time = 0
while True:
if ("space is pressed"): # Replace condition with what you want
jumping = True
start_time = time.perf_counter()
# Add your code here
if jumping:
# change of x,y and other jumping mechanism code here
if jumping and time.perf_counter() - start_time > 1: # Replace 1 with the amount you want this if condition to trigger,also add value in seconds
jumping = False
,
我不确定你的代码是什么样的,但我会这样做:
def dash(self):
keys = pygame.keys.get_pressed()
if keys[pygame.K_SPACE] and not self.dashing and self.jumping:
# ^^ Can be any key
if self.facing_right:
self.x += 20
if self.facing_left:
self.x -= 20
self.dashing = True
确保当你落地时它会self.dashing = False
,否则你将能够永远冲刺。
如果您使用 OOP,只需将此函数放在 player class
中即可。
否则,如果您不使用类,请将其放在文件中的任何位置并取出所有 self.
。