【问题标题】:smooth movement in pygamepygame中的平滑运动
【发布时间】:2016-09-25 10:54:21
【问题描述】:

我刚刚开始尝试了解 pygame,但在尝试在屏幕上移动我的矩形时遇到了一些麻烦。我已经设置好了,当我按下每个箭头键时,矩形将向上、向下、向左和向右移动。但是,当我按住键时,它不会继续移动。我必须多次按键才能让它移动到任何地方。

我已尝试使用Python - Smooth Keyboard Movement in Pygame 帖子中回答的 pygame.key.get_pressed() 方法,但没有任何效果。

我注意到每隔一段时间,如果我按住箭头键一段时间,矩形会继续移动,但只持续大约一秒钟,然后就停止了。

这个问题以前可能已经回答过了,但我一直没能找到答案。

代码如下:

import pygame
import os
import sys

_image_library = {}
def get_image(path):
    global _image_library
    image = _image_library.get(path)
    if image == None:
            canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
            image = pygame.image.load(canonicalized_path)
            _image_library[path] = image
    return image

def detect_collision(x,y):
    if x > 340:
       x -= 1
    if y > 240:
       y -= 1
    if y < 0:
       y += 1
    if x < 0:
       x += 1
    return x,y

pygame.init()
screen = pygame.display.set_mode((800, 550))
done = False
clock = pygame.time.Clock()

x = 30
y = 30

pygame.mixer.music.load("song.mp3")
pygame.mixer.music.play()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]:
        y -= 1
        x,y = detect_collision(x, y)
    if pressed[pygame.K_DOWN]:
        y += 1
        x,y = detect_collision(x, y)
    if pressed[pygame.K_LEFT]:
        x -= 1
        x,y = detect_collision(x, y)
    if pressed[pygame.K_RIGHT]:
        x += 1
        x,y = detect_collision(x, y)

    screen.fill((255, 255, 255))

    pygame.draw.rect(screen, (0, 128, 0), pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)

【问题讨论】:

  • 我使用的是 Python 2.7.11(与 pygame 相同)并且我使用的是 Windows 10 计算机,如果这有什么不同的话。

标签: python pygame


【解决方案1】:

我遇到了类似的问题,所以我没有使用 get_pressed(),而是使用 dict 并在按下键时更新它:

pressed = {}

while True:
    for event in pygame.event.get():
        if event.type == KEYUP:
            pressed[event.key] = False
        elif event.type == KEYDOWN:
            pressed[event.key] = True

然后测试是否按下了一个键(例如向上箭头),只需使用

if pressed.get(K_UP):
    # Do something

在主事件循环内(即 while True)。

【讨论】:

  • 感谢您的回答。我尝试创建字典,但我想我可能设置错了。当我按下向上箭头时,我使用pressed.get() 使一个矩形出现,并且它起作用了。然后我将其更改为在按箭头键时尝试移动矩形,但它不会移动。这是代码:
  • 糟糕。我显然不知道我在这里做什么。昨天刚开户哈哈。我不知道如何将代码放在评论中? @Qudit
  • 无法在 cmets 中包含大量文本。你可以编辑你的问题
猜你喜欢
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多