图像出现在屏幕上,但我无法使用程序中的w,s,a,d键移动它。我该如何解决?
import pygame, sys
from pygame.locals import *
pygame.init()
black = (0,0,0)
spriteLoc = ('sprite.png')
#backgroundLoc = ('background.png')
clock = pygame.time.Clock()
pygame.key.set_repeat(30,30)
pygame.display.set_caption('Focus.')
screen = pygame.display.set_mode((800,600))
sprite = pygame.image.load(spriteLoc).convert_alpha()
#background = pygame.image.load(backgroundLoc).convert_alpha()
#bgx,bgy = (0,0)
class Player():
def __init__(self,x,y,image):
self.x = x
self.y = y
self.image = image
# self.posx = posx
# self.posy = posy
def playerEvents(self):
global posx
global posy
posx = 0
posy = 0
if event.type == KEYDOWN:
if pygame.key == K_w:
posy -= 5
elif pygame.key == K_s:
posy += 5
elif pygame.key == K_a:
posx -= 5
elif pygame.key == K_d:
posx += 5
if event.type == KEYUP:
if pygame.key == K_w:
posy = 0
elif pygame.key == K_s:
posy = 0
elif pygame.key == K_a:
posx = 0
elif pygame.key == K_d:
posx = 0
self.x = self.x + posx
self.y = self.y + posy
#screen.blit(background,(bgx,bgy))
screen.blit(self.image,(self.x, self.y))
me = Player(50,50,sprite)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
screen.fill(black)
me.playerEvents()
clock.tick(60)
pygame.display.flip()
当我将posx和posy全局变为正数并按下任意键或将鼠标移到窗口上时,精灵向下移动。使它们消极地将它们移向相反的方向。正如您所注释的代码所示,我尝试使用背景图像来查看是否有所不同。我搜索,研究,评论了可能的问题区域,并重新安排了一切。感谢您的帮助!
答案 0 :(得分:1)
您应该在pygame.key
方法中将event.key
更改为playerEvents
。