def update(self, dt): direction = 0 if InputWatcher.isDown(pygame.K_LEFT) or InputWatcher.isDown(pygame.K_a): direction -= 1 if InputWatcher.isDown(pygame.K_RIGHT) or InputWatcher.isDown(pygame.K_d): direction += 1 # Apply player or friction force if direction == -1: self.velocity[0] -= PLAYER_FORCE elif direction == 1: self.velocity[0] += PLAYER_FORCE else: self.velocity[0] *= FRICTION_FORCE # Clamp velocity if (self.velocity[0] > MAX_SPEED): self.velocity[0] = MAX_SPEED if (self.velocity[0] < -MAX_SPEED): self.velocity[0] = -MAX_SPEED # Set position from velocity self.position = [self.position[0] + self.velocity[0] * dt, self.position[1] + self.velocity[1] * dt] # Clamp position in scene if (self.position[0] > SHIP_SCREEN_RIGHT): self.position[0] = SHIP_SCREEN_RIGHT self.velocity = [0,0] if (self.position[0] < 0): self.position[0] = 0 self.velocity = [0,0]
def gameLoop(): dinoScene=FIRST_SCENE.DinoScene() # Game loop currentTime = pygame.time.get_ticks() IS_PLAYING = True while IS_PLAYING: previousTime = currentTime currentTime = pygame.time.get_ticks() deltaTime = currentTime - previousTime # Reset the screen CoreApp.screen.fill((0,0,0,0)) # HACK: If you drag screen in Windows, it locks main thread # This averts the bug, but may introduce new bugs. Look into this - CP if (deltaTime > 100): deltaTime = 0 # Step the world - times by 0.001 to convert to seconds CoreApp.world.Step((deltaTime) * 0.001, CoreApp.VELOCITY_ITERATION, CoreApp.POSITION_ITERATION) dinoScene.update(deltaTime) dinoScene.draw() # Swap to other screen buffer pygame.display.flip() # One second / Target FPS is ideal frame time lapse timeLapse = pygame.time.get_ticks() - currentTime if (timeLapse < 1000 / CoreApp.FPS): pygame.time.wait(1000 / CoreApp.FPS - timeLapse) # Must empty event or game stalls for event in pygame.event.get(): if event.type == QUIT: IS_PLAYING = False # TEMP: Leave scene if press ESC - CP IS_PLAYING = not InputWatcher.isDown(pygame.K_ESCAPE)