当我按w / a / s / d时,我希望我的角色向上/向左/向下/向右移动。我认为应该发生的是,例如,当我按下d:
main()
将“看到”发生了事件
看到我按下了一个键
转到player1.move()
看到关键是d
转到Character.move_right(self)
更新x_pos
和x_vel
返回main()
转到player1.display()
在更新的x_pos
和x_vel
更新屏幕
“勾选时间”
import sys
import pygame
class Character(object):
def __init__(self, surface, x_vel, y_vel, x_pos, y_pos):
self.surface = surface
self.x_vel = x_vel
self.y_vel = y_vel
self.x_pos = x_pos
self.y_pos = y_pos
self.size = (5, 20)
def move_right(self):
self.x_vel += 5
self.x_pos += self.x_vel
def move_left(self):
self.x_vel -= 5
self.x_pos += self.x_vel
def move_up(self):
self.y_vel -= 5
self.y_pos += self.y_vel
def move_down(self):
self.y_vel += 5
self.y_pos += self.y_vel
def move(self):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
Character.move_up(self)
elif event.key == pygame.K_a:
Character.move_left(self)
elif event.key == pygame.K_s:
Character.move_down(self)
elif event.key == pygame.K_d:
Character.move_right(self)
self.character = pygame.Rect((self.x_pos, self.y_pos), self.size)
def display(self):
pygame.draw.rect(self.surface, (255, 255, 255), self.character)
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
fps = 30
def main():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
else:
player1 = Character(screen, 0, 0, 200, 200)
player1.move()
player1.display()
pygame.display.update(screen_rect)
clock.tick(fps)
if __name__ == "__main__":
main()
答案 0 :(得分:5)
总结可能的错误:
正如@tobias_k指出你的事件已被消耗。这可以像这样修复
def move(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
....
def main():
player1 = Character(screen, 0, 0, 200, 200)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
else:
player1.move(event)
其次,将角色的创建移出主循环
def main():
player1 = Character(screen, 0, 0, 200, 200)
while True: