如何使游戏对象在按键被按下时持续移动?

2024-05-07 19:55:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让游戏object(这里是欢迎文本)只要按下键盘上的key就可以移动。但在我的这个密码里

import pygame , sys
from pygame.locals import *

pygame.init()

WHITE = (255 , 255 , 255)
RED   = (255 , 0 , 0)

DISPLAYSURF = pygame.display.set_mode((800 , 400))
pygame.display.set_caption('Welcome Tanks')

#render(text, antialias, color, background=None)
fontObj = pygame.font.SysFont('serif' , 40)
text = fontObj.render('Welcome Folks' , True , RED )

x = 150
y = 29

while True:
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(text ,(x , y))   
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == KEYDOWN or event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit(0)
            elif event.key == K_DOWN:               
                y += 15
            elif event.key == K_UP:
                y -= 15
            elif event.key == K_RIGHT:
                x += 14
            elif event.key == K_LEFT:
                x -= 15
            else:
                x = 150
                y = 29
    pygame.display.update()

即使长时间连续按下key,对象也只移动一次。换句话说,当按下键盘按钮时,对象只改变一次位置。我想让它在我握着钥匙的时候不停地移动。在

我应该查找哪个事件而不是event.KEYDOWN?在


Tags: keytextimporteventtypedisplaysysred
2条回答

我建议您使用key.get_pressed(),例如

while True:
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(text ,(x , y))   
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit(0)
        elif event.type == KEYDOWN or event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit(0)

    if  pygame.key.get_pressed()[K_LEFT]:
        x -= 15

    if  pygame.key.get_pressed()[K_RIGHT]:
        x += 14

    if  pygame.key.get_pressed()[K_UP]:
        y -= 15

    if  pygame.key.get_pressed()[K_DOWN]:
        y += 15
    pygame.display.update()

pygame.key.按下()

Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A True value means the that button is pressed.

Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. You have no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the event queue for this functionality.

你也可以看看doc

 keyState = pygame.key.get_pressed()

声明,然后使用keystate:

^{pr2}$

你可以试试:

if key.get_pressed()
    down = True

while down = True:
    y+= 15

然后得到FPS时钟,这样它就不会仅仅流过screen!在

相关问题 更多 >