如何解决玩家移动的 Pygame FPS 问题Python
当我以 60 FPS 运行时,玩家的移动速度比我以 30 FPS 运行时更快。 我正在使用增量时间并将其传递给 all_sprites 更新,但它似乎不起作用 我还尝试使用 self.dt 自行更新播放器,它似乎工作得更好,但帧速率之间仍然存在巨大差异
main.py:
import pygame as pg
from settings import *
from sprites import *
from os import path
class Game:
def __init__(self):
pg.init()
self.screen = pg.display.set_mode((WIDTH,HEIGHT))
pg.display.set_caption("Movement")
self.clock = pg.time.Clock()
self.load_data()
self.running = True
def load_data(self):
pass
def new(self):
self.all_sprites = pg.sprite.LayeredUpdates()
self.player = Player(self)
self.run()
def run(self):
self.playing = True
while self.playing:
self.dt = self.clock.tick(FPS) *.001 * FPS
self.events()
self.update()
self.draw()
def update(self):
self.all_sprites.update(self.dt)
def events(self):
# Game loop - events
for event in pg.event.get():
# check for closing window
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
def draw(self):
# Game loop - draw
self.screen.fill((0,0))
self.all_sprites.draw(self.screen)
pg.display.flip()
def show_start_screen(self):
pass
def show_go_screen(self):
pass
if __name__ == "__main__":
g = Game() # instance of the game class
g.show_start_screen()
while g.running:
g.new()
g.show_go_screen()
pg.quit()
精灵.py:
import pygame as pg
from settings import *
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
def __init__(self,game):
self._layer = 2
self.groups = game.all_sprites
pg.sprite.Sprite.__init__(self,self.groups)
self.game = game
self.image = pg.Surface((30,40))
self.image.fill((0,255,255))
self.rect = self.image.get_rect()
self.vel = vec(0,0)
self.acc = vec(0,0)
self.pos = vec(WIDTH/2,HEIGHT/2)
def limit_velocity(self,max_vel):
self.vel.x = max(-max_vel,min(self.vel.x,max_vel))
if abs(self.vel.x) < .01:
self.vel.x = 0
def update(self,dt):
keys = pg.key.get_pressed()
self.horz_movement(dt,keys)
def horz_movement(self,dt,keys):
self.acc.x = 0
if keys[pg.K_LEFT]:
self.acc.x += -PLAYER_ACC
if keys[pg.K_RIGHT]:
self.acc.x += PLAYER_ACC
self.acc.x += self.vel.x * PLAYER_FRICTION
self.vel.x += self.acc.x * dt
self.limit_velocity(5)
self.pos.x += self.vel.x * dt - (self.acc.x * .5) * (dt * dt)
self.rect.x = self.pos.x
self.rect.y = self.pos.y
if self.pos.x > WIDTH:
self.pos.x = 0
settings.py:
#game settings
FPS = 30
WIDTH = 600
HEIGHT = 800
#player settings
PLAYER_ACC = 1.1
PLAYER_FRICTION = -.05
解决方法
在 main.py 的 run()
函数中,更改
self.dt = self.clock.tick(FPS) *.001 * FPS
到任一
self.dt = self.clock.tick(FPS) *.001 * 30
或
self.dt = self.clock.tick(FPS) *.001 * 60
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。