为什么 pygame 中的机器人移动速度如此不一致?
Why do my bots in pygame move at such an inconsistent speed?
所以我的问题是我的机器人会以不一致的速度移动,有时甚至不动。我试过用 clock.ticks(30)
更改 fps(然后更少),但它不会变得更平滑!
pygame.init()
clock = pygame.time.Clock()
bot4x = random.randint(0, 600)
bot4y = random.randint(0, 600)
randb4 = round(random.randint(0, 4))
def bot4():
screen.blit(pygame.image.load("DOT.png"), (bot4x, bot4y))
clock.tick(60)
run = True
while run:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if randb4 == 1:
bot4x = bot4x + 5
elif randb4 == 2:
bot4x = bot4x - 5
elif randb4 == 3:
bot4y = bot4y + 5
elif randb4 == 4:
bot4y = bot4y - 5
if bot4x >= 568:
bot4x = 568
elif bot4x <= 0:
bot4x = 0
elif bot4y >= 568:
bot4y = 568
elif bot4y <= 0:
bot4y = 0
bot4()
pygame.display.update()
这是Indentation的事情。您必须在应用程序循环而不是事件循环中计算移动:
pygame.init()
clock = pygame.time.Clock()
bot4x = random.randint(0, 600)
bot4y = random.randint(0, 600)
randb4 = round(random.randint(0, 4))
def bot4():
screen.blit(pygame.image.load("DOT.png"), (bot4x, bot4y))
clock.tick(60)
run = True
while run:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# INDENTATION
#<--|
if randb4 == 1:
bot4x = bot4x + 5
elif randb4 == 2:
bot4x = bot4x - 5
elif randb4 == 3:
bot4y = bot4y + 5
elif randb4 == 4:
bot4y = bot4y - 5
if bot4x >= 568:
bot4x = 568
elif bot4x <= 0:
bot4x = 0
elif bot4y >= 568:
bot4y = 568
elif bot4y <= 0:
bot4y = 0
bot4()
pygame.display.update()
所以我的问题是我的机器人会以不一致的速度移动,有时甚至不动。我试过用 clock.ticks(30)
更改 fps(然后更少),但它不会变得更平滑!
pygame.init()
clock = pygame.time.Clock()
bot4x = random.randint(0, 600)
bot4y = random.randint(0, 600)
randb4 = round(random.randint(0, 4))
def bot4():
screen.blit(pygame.image.load("DOT.png"), (bot4x, bot4y))
clock.tick(60)
run = True
while run:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if randb4 == 1:
bot4x = bot4x + 5
elif randb4 == 2:
bot4x = bot4x - 5
elif randb4 == 3:
bot4y = bot4y + 5
elif randb4 == 4:
bot4y = bot4y - 5
if bot4x >= 568:
bot4x = 568
elif bot4x <= 0:
bot4x = 0
elif bot4y >= 568:
bot4y = 568
elif bot4y <= 0:
bot4y = 0
bot4()
pygame.display.update()
这是Indentation的事情。您必须在应用程序循环而不是事件循环中计算移动:
pygame.init()
clock = pygame.time.Clock()
bot4x = random.randint(0, 600)
bot4y = random.randint(0, 600)
randb4 = round(random.randint(0, 4))
def bot4():
screen.blit(pygame.image.load("DOT.png"), (bot4x, bot4y))
clock.tick(60)
run = True
while run:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# INDENTATION
#<--|
if randb4 == 1:
bot4x = bot4x + 5
elif randb4 == 2:
bot4x = bot4x - 5
elif randb4 == 3:
bot4y = bot4y + 5
elif randb4 == 4:
bot4y = bot4y - 5
if bot4x >= 568:
bot4x = 568
elif bot4x <= 0:
bot4x = 0
elif bot4y >= 568:
bot4y = 568
elif bot4y <= 0:
bot4y = 0
bot4()
pygame.display.update()