目前,每次按下一个键时,精灵只会移动1个像素。当按住左或右键时,我怎么能让管道工精灵不断移动?
while running:
setup_background()
spriteimg = plumberright
screen.blit(spriteimg,(x1, y1))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
x1 = x1 + 0
y1 = y1 - 1
elif event.key == pygame.K_DOWN:
x1 = x1 + 0
y1 = y1 + 1
elif event.key == pygame.K_LEFT:
x1 = x1 -1
y1 = y1 + 0
elif event.key == pygame.K_RIGHT:
x1 = x1 + 1
y1 = y1 + 0
pygame.display.flip()
clock.tick(120)
答案 0 :(得分:22)
您可以使用pygame.key.get_pressed来执行此操作。
示例:
while running:
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
y1 -= 1
if keys[pygame.K_DOWN]:
y1 += 1
答案 1 :(得分:1)
使用该伴侣,它将很好地工作,并将其放入for循环中。
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
playerX_change = -0.1
if event.key == pygame.K_d:
playerX_change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
playerX_change = 0
playerX += playerX_change
player(playerX, playerY)
pygame.display.update()
答案 2 :(得分:0)
当键的状态更改时,键盘事件(请参阅pygame.event模块)仅发生一次。每次按下一个键,KEYDOWN
事件就会发生一次。每次释放键都会发生KEYUP
。使用键盘事件可以执行单个操作或逐步移动。
如果要实现连续运动,则必须使用pygame.key.get_pressed()
。 pygame.key.get_pressed()
返回带有每个键状态的列表。如果按住某个键,则该键的状态为True
,否则为False
。使用pygame.key.get_pressed()
评估按钮的当前状态并连续移动:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
x1 += keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
y1 += keys[pygame.K_DOWN] - keys[pygame.K_UP]
x1 = x1 % window.get_width()
y1 = y1 % window.get_height()
setup_background()
spriteimg = plumberright
screen.blit(spriteimg, (x1, y1))
pygame.display.flip()
clock.tick(120)
最小示例: repl.it/@Rabbid76/PyGame-ContinuousMovement
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
rect.centerx = rect.centerx % window.get_width()
rect.centery = rect.centery % window.get_height()
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), rect)
pygame.display.flip()
pygame.quit()
exit()