I am trying to create an animation system and need to keep track of how much time has passed so that I can change the frame of the animation on time. However I am having trouble keeping track of when “t”, the total time in milliseconds, passes a set integer, 175, because the framerate of 60 causes uncommon numbers.
I have tried simply using a modulus operator to get it to work but that doesn’t work. I can’t wrap my head around this myself, any help is appreciated.
import pygame, sys
from pygame.math import Vector2
WIDTH, HEIGHT = 600, 400
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
fps = 60
dt = 0 #Delta time
t = 0 #Time in milliseconds
class AnimationController:
def __init__(self, animations, animation, frame, frameGap=175):
#Load all animations
self.animations = []
for anim in animations:
list = []
for img in anim:
list.append(pygame.image.load(f'{img}').convert_alpha())
self.animations.append(list)
self.animation = animation
self.frame = frame
self.frameGap = frameGap
def UpdateFrame(self, time):
#self.animations[animation number][frame number]
pass
objects = []
class Object:
def __init__(self, pos, size, velo=Vector2(), texture=(255,0,0)):
self.pos = pos
self.size = size
self.velo = velo
if isinstance(texture, str):
self.texture = pygame.image.load(texture).convert_alpha()
else:
self.texture = texture
objects.append(self)
def rect(self):
return pygame.Rect(self.pos.x, self.pos.y, self.size.x, self.size.y)
def Draw(self):
if isinstance(self.texture, tuple):
pygame.draw.rect(screen, self.texture, self.rect())
if isinstance(self.texture, pygame.Surface):
screen.blit(self.texture, self.pos)
#Add and implement an Animator() class
def Update(self, friction, dt):
self.velo.x *= 1/(1+(friction*dt))
self.pos.x += self.velo.x*dt
for object in objects:
if object != self and object.rect().colliderect(self.rect()):
if self.velo.x > 0:
self.pos.x = object.pos.x - self.size.x
if self.velo.x < 0:
self.pos.x = object.pos.x + object.size.x
self.velo.y *= 1/(1+(friction*dt))
self.pos.y += self.velo.y*dt
for object in objects:
if object != self and object.rect().colliderect(self.rect()):
if self.velo.y > 0:
self.pos.y = object.pos.y - self.size.y
if self.velo.y < 0:
self.pos.y = object.pos.y + object.size.y
player = Object(Vector2(290,190),Vector2(20,20))
wall = Object(Vector2(100,100),Vector2(50,50))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.velo.y = -5
if keys[pygame.K_DOWN]:
player.velo.y = 5
if keys[pygame.K_LEFT]:
player.velo.x = -5
if keys[pygame.K_RIGHT]:
player.velo.x = 5
screen.fill((255,255,255))
for object in objects:
object.Draw()
player.Update(0.1, dt)
pygame.display.update()
dt = clock.tick(fps)/10
t += dt*10
if t % 175 == 0:
print(t)