如何在按下pygame中的某个键时切换到不断的移动?
问题描述:
下面的代码被设置,所以当头像位移到屏幕并且敲击空格键或向上键时,它会移动一次,但当它被按下时,它不会不断地向上移动(在空中)。我需要改变我的代码,所以当按住键的时候,移动是不变的。如何在按下pygame中的某个键时切换到不断的移动?
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)
答
在MoveKeyDown
方法您必须将self.y_change
值设定为所希望的速度,而不是调整self.rect.y
值。 update
方法中的self.rect.move_ip
调用将移动精灵。您必须在主循环中的每一帧调用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)
即使它被关闭作为题外话,答案应该是帮助:http://stackoverflow.com/questions/43154793/in-pygame-why-can-i-not-move-my- sprite-while-button-is-held-down/43161906#43161906 – The4thIceman
请提供[完整但很简单的示例](http://stackoverflow.com/help/mcve)。我们需要可以不经调整就运行的示例。 – skrx