【问题标题】:How to make image move如何使图像移动
【发布时间】:2016-07-19 02:03:17
【问题描述】:

所以我想使用 WASD 键移动图像。我不完全理解如何做到这一点,而且我确实有一个主循环。 这是我的图像的样子和位置

no_image = pygame.image.load("Ideot.png").convert
x_coord = 500 
y_coord = 250
no_position = [x_coord,y_coord]

这段代码在主循环后面。在主循环之后,我实际上是通过这样做来绘制图像

screen.blit(no_image,no_position)

这就是我的循环的样子 完成 = 假

while not done:
   for event in pygame == pygame.Quit:
       done = True

你能展示如何使用 WASD 使图像移动

【问题讨论】:

  • Stack Overflow 不是代码编写或教程服务。请edit您的问题并发布您迄今为止尝试过的内容,包括示例输入、预期输出以及任何错误或回溯的全文

标签: python pygame


【解决方案1】:

首先,我将介绍当前的 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 个键,你希望能够通过组合键来移动,比如向右和向上,这样你就可以向东北移动。

【讨论】:

  • 很抱歉写了这个,,,我实际上是通过谷歌搜索找到的,我的错。谢谢你的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
相关资源
最近更新 更多