在pygame中按住一个键时如何切换到持续移动?

Posted

技术标签:

【中文标题】在pygame中按住一个键时如何切换到持续移动?【英文标题】:How do I switch to constant movement when holding down a key in pygame? 【发布时间】:2017-09-03 04:44:44 【问题描述】:

设置了以下代码,因此当头像被移动到屏幕上并且点击空格键或向上键时,它会移动一次,但当它被按住时,它不会一直向上移动(在空中)。我需要更改我的代码,以便在按住键时移动是恒定的。

import pygame, sys, time, random
from pygame.locals import *

class Player(Duck):
    """The player controlled Duck"""


    def __init__(self, x, y, width, height):
        super(Player, self).__init__(x, y, width, height)

        # How many pixels the Player duck should move on a given frame.
        self.y_change = 0
        # How many pixels the spaceship should move each frame a key is pressed.
        self.y_dist = 50


    def MoveKeyDown(self, key):
        """Responds to a key-down event and moves accordingly"""

        if (key == pygame.K_UP or key == K_SPACE):
            self.rect.y -= self.y_dist
    def MoveKeyUp(self, key):
        """Responds to a key-up event and stops movement accordingly"""

        if (key == pygame.K_UP or key == K_SPACE):
            self.rect.y -= self.y_dist


    def update(self):
        """
        Moves the Spaceship while ensuring it stays in bounds
        """
        # Moves it relative to its current location.
        self.rect.move_ip(self.y_change, 0)

        # If the Spaceship moves off the screen, put it back on.
        if self.rect.y <= 0:
            self.rect.y = 0
        elif self.rect.y > window_width:
            self.rect.y = window_width

while True:  # the main game loop
    for event in pygame.event.get(): #Closes game
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYUP:
            player.MoveKeyUp(event.key)
        elif event.type == pygame.KEYDOWN:
            player.MoveKeyDown(event.key)

【问题讨论】:

即使它被关闭为题外话,答案应该是有帮助的:***.com/questions/43154793/… 请提供complete but minimal example。我们想要无需调整即可运行的示例。 【参考方案1】:

MoveKeyDown 方法中,您必须将self.y_change 值设置为所需的速度,而不是调整self.rect.y 值。然后update 方法中的self.rect.move_ip 调用将移动精灵。您必须在主 while 循环中的每一帧都调用 update 方法。

def __init__(self, x, y, width, height):
    super(Player, self).__init__(x, y, width, height)
    # How many pixels the Player duck should move on a given frame.
    self.x_change = 0
    self.y_change = 0
    # How many pixels the spaceship should move each frame a key is pressed.
    self.speed = 50

def MoveKeyDown(self, key):
    """Responds to a key-down event and moves accordingly."""
    if key in (pygame.K_UP, pygame.K_SPACE):
        self.y_change = -self.speed

def MoveKeyUp(self, key):
    if key in (pygame.K_UP, pygame.K_SPACE) and self.y_change < 0:
        self.y_change = 0

def update(self):
    self.rect.move_ip(self.x_change, self.y_change)

【讨论】:

以上是关于在pygame中按住一个键时如何切换到持续移动?的主要内容,如果未能解决你的问题,请参考以下文章

Pygame - 运动加速

玩家精灵在按住移动键时移动而无需输入

按住键时如何进行精灵移动

按住键时如何进行精灵移动

xmind怎么把第二级移到第一级

如何在按键盘中的“输入”键时将焦点移到按钮上