问题描述
好的,我是 PyGame 的新手,我正在制作太空入侵者游戏,我目前正在构建运动脚本。
出于某种原因,当我按下右键时,我的角色无限向右移动。
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Space Invader')
icon = pygame.image.load('pepper.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370
playerY = 480
playerX_Change = 0
def player (x,y): screen.blit(playerImg,(x,y) )
running = True
while running:
# RGB STANDS FOR RED,GREEN,BLUE THE NUMBERS GOES MAX TO 255 FOR EXAMPLE_:
screen.fill((0,30)) # this will display yellow
for event in pygame.event.get():
if event.type == pygame.QUIT: #if we click the X the program ends
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_Change = -0.1
if event.key == pygame.K_RIGHT:
playerX_Change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_Change = 0.1
playerX += playerX_Change
player(playerX,playerY)
pygame.display.update()
解决方法
我建议使用 pygame.key.get_pressed()
而不是键盘事件。
键盘事件(参见 pygame.event 模块)仅在键的状态改变时发生一次。 KEYDOWN
事件在每次按下键时发生一次。 KEYUP
每次释放键时出现一次。将键盘事件用于单个操作或逐步移动。
pygame.key.get_pressed()
返回一个包含每个键状态的序列。如果某个键被按下,则该键的状态为 True
,否则为 False
。使用 pygame.key.get_pressed()
评估按钮的当前状态并获得连续移动:
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('Space Invader')
icon = pygame.image.load('pepper.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370
playerY = 480
def player (x,y):
screen.blit(playerImg,(x,y) )
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: #if we click the X the program ends
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] :
playerX += 0.1
if keys[pygame.K_LEFT] :
playerX -= 0.1
# RGB STANDS FOR RED,GREEN,BLUE THE NUMBERS GOES MAX TO 255 FOR EXAMPLE_:
screen.fill((0,30)) # this will display yellow
player(playerX,playerY)
pygame.display.update()