【问题标题】:Pygame, if key pressed and then released actionPygame,如果按下键然后释放动作
【发布时间】:2026-01-19 01:55:01
【问题描述】:

我正在为一款游戏尝试物理,并想尝试如何加快速度。

我当前的代码是这样的

    def left(self):
        self.x -= 1 * self.xvelocity
        if not self.xvelocity == 10:
            self.xvelocity += 1

    def right(self):
        self.x += 1 * self.xvelocity
        if not self.xvelocity == 10:
            self.xvelocity += 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    keys_pressed = pygame.key.get_pressed()

    if keys_pressed[pygame.K_LEFT]:
        player.left()

    if keys_pressed[pygame.K_RIGHT]:
        player.right()

如果释放了左右键,我想将 xvelocity 重置回 0。目前这还没有发生,所以如果你向右移动并加速,然后向左移动,你仍然有相同的速度。

我尝试通过添加以下内容来修复它:

    def left(self, *args):
        if args:
            self.x -= 1 * self.xvelocity
            if not self.xvelocity == 10:
                self.xvelocity += 1
        else:
            self.xvelocity = 0

    def right(self, *args):
        if args:
            self.x += 1 * self.xvelocity
            if not self.xvelocity == 10:
                self.xvelocity += 1
        else:
            self.xvelocity = 0

但是如果你改变方向,我无法获得必须再次加速的效果。我错过了什么吗?

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    您可以尝试按如下方式分解左/右输入:

    1) left. Increase velocity to left till max 
    2) right. increase velocity to right till max 
    3) L+R. Invalid 
    4) No input. Velocity resets to zero 
    5) L->R/R->L. left velocity resets to zero and now increases in right direction. vice-versa
    

    查看您的初始代码,您犯了一个错误,即在没有将速度归零的情况下翻转标志。您的“速度”变量实际上是速度。您在更改 self.x 时使用的符号代表您的方向。我提出了一种稍微不同的方法,以确保您的速度中包含方向。 -ve 向左,+ve 向右。请记住,您可能需要为无输入和 L+R 创建案例。

    def left(self):
        if self.xvelocity>0: #If heading to the right, reset velocity to 0
            self.xvelocity = 0
        else: #We were not heading to the right so begin left ward velocity
            self.xvelocity -=1
        self.x += 1*max(-10,self.xvelocity) #another way to set limit on negative velocity
    
    def right(self): # simply a reflect of the above
        if self.xvelocity<0:
            self.xvelocity = 0
        else:
            self.xvelocity +=1
        self.x += 1*min(10,self.xvelocity)
    

    【讨论】:

      最近更新 更多