【问题标题】:How could I make a dash in a 2D pygame python program?如何在 2D pygame python 程序中创建破折号?
【发布时间】:2021-02-20 20:57:05
【问题描述】:

如果 pygame 程序只是一个基本实体,你可以用箭头键正常移动,我怎么能做到,如果按下空格,基于按下时按住的箭头键,玩家破折号稍微向指定方向?我的想法是,当按下空格时,程序会检查其他键是否被按住,并基于它快速增加 x 和/或 y 坐标,然后在特定时间停止,但我不知道如何做到这一点停止,因为所有这些都发生在主游戏循环中。任何见解都受到高度赞赏。

【问题讨论】:

  • 你已经描述过了。存储破折号开始的时间,并在破折号时间后停止。

标签: python pygame


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    我不确定你的代码是什么样的,但我会这样做:

    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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2013-10-09
      • 1970-01-01
      • 2011-12-17
      • 2012-05-11
      • 2020-07-06
      相关资源
      最近更新 更多