首先,我将介绍当前的 cmets。 MattDMo 是对的,这不是一个代码编写服务,而是一种帮助人们理解他们的问题或为什么事情有效或为什么他们不工作的方法。最好先尝试,如果你想不通,再问你的问题。 marienbad 的链接确实使图像移动,但以一种不方便的方式。每次您按下某个键时,该链接的代码都会移动您的图像(很有用,我建议您检查一下),但是在按住某个键的同时移动也很好。
在按住一个键的同时让图像移动是很棘手的。我的偏好是使用布尔值。
如果您没有使用勾选方法,请立即停止并准备好一个。查看 pygame.org/docs 以了解如何操作,他们有很好的示例代码。没有它,运动将无法按照您的意愿进行,因为如果您不限制它,此循环将运行得与您的计算机可以处理的一样快,因此您甚至可能看不到您的运动。
from pygame.locals import * # useful pygame variables are now at your disposle without typing pygame everywhere.
speed = (5, 5) # Amount of pixels to move every frame (loop).
moving_up = False
moving_right = False
moving_down = False
moving_left = False # Default starting, so there is no movement at first.
以上代码适用于您的 while 循环之外。您的 for 循环事件将需要稍微更改,以改进您的代码,我建议在此处使用函数,或使用字典来消除所有这些 if 语句的需要,但我不会仅仅因为我的答案更简单并获得点对面。我省略了一些细节,比如 event.quit,因为你已经有了它们。
如果你不包括键盘部分,你的角色将永远不会停止移动!
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_w:
moving_up = True
if event.key == K_d
moving_right = True
if event.key == K_s:
moving_down = True
if event.key == K_a:
moving_left = True
if event.type == KEYUP:
if event.key == K_w:
moving_up = False # .. repeat this for all 4.
然后在循环的后面...
if moving_up:
y_coord += -speed[1] # Negative speed, because positive y is down!
if moving_down:
y_coord += speed[1]
if moving_right:
x_coord += speed[0]
if moving_left:
x_coord += -speed[0]
现在您的 x/y 坐标在设置为移动时会发生变化,这将用于对您的图像进行 blit!确保在这种情况下不要使用 elif,如果你拿着 2 个键,你希望能够通过组合键来移动,比如向右和向上,这样你就可以向东北移动。