When I run with 60 FPS the player moves faster than when I run at 30 FPS. I'm using delta time and passing it to the all_sprites update, but it seems that it is not working I have also tried to update the player it self with self.dt and it seems to work better but still there is a huge difference between frame rates
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, 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()
sprites.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
In the run()
function in main.py, change
self.dt = self.clock.tick(FPS) *.001 * FPS
to either
self.dt = self.clock.tick(FPS) *.001 * 30
or
self.dt = self.clock.tick(FPS) *.001 * 60
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.