如何使我的pygame角色平滑移动?当我创建常规程序时,我似乎可以通过减小速度(每步角色移动的距离)和减小时间延迟来获得平滑运动,以便它快速地移动小步。
代码可能如下所示(这里只有一个简单的矩形在屏幕上移动):
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
x = 400
y = 400
width = 60
height = 60
vel = 2
run = True
while run:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - width - vel:
x += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
然而,当我试图将游戏面向对象化时,我没有让角色平滑移动。代码如下。我做错了什么?
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
class player():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 2
self.left = False
self.right = False
def draw(self):
pygame.draw.rect(win, (255, 0, 0), (man.x, man.y, man.height, man.width))
if self.left:
pygame.draw.rect(win, (255, 0, 0), (man.x, man.y, man.height, man.width))
elif self.right:
pygame.draw.rect(win, (255, 0, 0), (man.x, man.y, man.height, man.width))
def re_draw():
win = pygame.display.set_mode((500, 500))
man.draw()
pygame.display.update()
man = player(400, 400, 60, 60)
run = True
while run:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and man.x > man.vel:
man.x -= man.vel
man.left = True
man.right = False
elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel:
man.x += man.vel
man.left = False
man.right = True
re_draw()
pygame.quit()