pygame中的平滑移动

3
我刚开始学习pygame,并且在尝试移动屏幕上的矩形时遇到了一些问题。我已经设置好了当我按下箭头键时,矩形会向上、下、左、右移动。然而,当我按住键时,它不会继续移动。我必须多次按键才能使其移动到任何地方。
我尝试使用pygame.key.get_pressed()方法,如Python - Smooth Keyboard Movement in Pygame中所述,但没有任何效果。
我注意到,偶尔如果我按住箭头键一段时间,矩形会持续移动,但只有大约一秒钟,然后停止。
这个问题可能已经被解决了,但我还没有找到答案。
以下是代码:
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计算机上,如果有任何区别的话。 - somerandomnerd
1个回答

3

我曾遇到类似的问题,所以我不使用get_pressed()方法,而是使用一个字典,并在按下键时更新它:

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()使矩形在按上箭头时出现,并且它起作用了。然后我更改了它,尝试在按箭头键时移动矩形,但它不会移动。这是代码: - somerandomnerd
哎呀。 显然我不知道我在这里做什么。 就是昨天刚开了我的账户哈哈。 我不知道怎样把代码放到注释里?@Qudit - somerandomnerd
无法在注释中包含大量文本。您可以编辑您的问题。 - Qudit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接