Windspar

Pygame Player Smooth Movement

Jun 20th, 2021
716
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import pygame
  2. from pygame.sprite import Group, Sprite
  3.  
  4. class Entity(Sprite):
  5.     # @param anchor is rect position in text form. "topleft", "topright", "center"
  6.     def __init__(self, image, velocity, position, anchor):
  7.         super().__init__()
  8.         self.image = image
  9.         self.rect = image.get_rect()
  10.         setattr(self.rect, anchor, position)
  11.         self.velocity = velocity
  12.         self.position = pygame.Vector2(self.rect.center)
  13.  
  14.     def move(self, *args):
  15.         if len(args) == 1:
  16.             self.position += args[0]
  17.         else:
  18.             self.position += args
  19.  
  20.         self.rect.center = self.position
  21.  
  22.     def set_position(self, *args):
  23.         if len(args) == 1:
  24.             self.position = pygame.Vector2(args[0])
  25.         else:
  26.             self.position = pygame.Vector2(args)
  27.  
  28.         self.rect.center = self.position
  29.  
  30. def main():
  31.     pygame.init()
  32.     surface = pygame.display.set_mode((800, 600))
  33.     clock = pygame.time.Clock()
  34.     rect = surface.get_rect()
  35.     running = True
  36.     delta = 0
  37.     fps = 60
  38.  
  39.     image = pygame.Surface((20, 20), pygame.SRCALPHA)
  40.     image.fill(pygame.Color("firebrick"))
  41.  
  42.     player = Entity(image, 100, rect.center, "center")
  43.     sprites = Group(player)
  44.  
  45.     while running:
  46.         for event in pygame.event.get():
  47.             if event.type == pygame.QUIT:
  48.                 running = False
  49.  
  50.         direction = pygame.Vector2()
  51.         key_states = pygame.key.get_pressed()
  52.         if any([key_states[k] for k in (pygame.K_UP, pygame.K_w)]):
  53.             direction.y -= 1
  54.  
  55.         if any([key_states[k] for k in (pygame.K_DOWN, pygame.K_s)]):
  56.             direction.y += 1
  57.  
  58.         if any([key_states[k] for k in (pygame.K_LEFT, pygame.K_a)]):
  59.             direction.x -= 1
  60.  
  61.         if any([key_states[k] for k in (pygame.K_RIGHT, pygame.K_d)]):
  62.             direction.x += 1
  63.  
  64.         if direction != pygame.Vector2():
  65.             # Real world movement.
  66.             direction.normalize_ip()
  67.             player.move(direction * delta * player.velocity)
  68.  
  69.  
  70.         surface.fill(pygame.Color("black"))
  71.         sprites.draw(surface)
  72.         pygame.display.flip()
  73.         # Smooth movement
  74.         delta = clock.tick(fps) * 0.001
  75.  
  76.     pygame.quit()
  77.  
  78. main()
  79.  
RAW Paste Data