Advertisement
Windspar

Simple Example Image Facing Mouse

Mar 26th, 2024 (edited)
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | Gaming | 0 0
  1. import pygame
  2.  
  3. TRANSPARENT = 0, 0, 0, 0
  4.  
  5. # Image Orientation Matter. Right Side Is Top
  6. def create_triangle(size, color):
  7.     rect = pygame.Rect((0, 0), size)
  8.     surface = pygame.Surface(size, pygame.SRCALPHA)
  9.     surface.fill(TRANSPARENT)
  10.     points = rect.midright, rect.bottomleft, rect.topleft
  11.     pygame.draw.polygon(surface, color, points)
  12.     return surface
  13.  
  14. def rotate_image(sprite, target):
  15.     vector = pygame.Vector2(target) - sprite.rect.center
  16.     # Second Value Is The Angle
  17.     angle = vector.as_polar()[1]
  18.     # Always Rotate From Original Image. Rotate With Negative Angle Because Topleft Is (0, 0)
  19.     sprite.image = pygame.transform.rotate(sprite.original_image, -angle)
  20.     sprite.rect = sprite.image.get_rect(center=sprite.rect.center)
  21.  
  22. def main(caption, width, height, flags=0, fps=60):
  23.     # Simple Pygame Setup
  24.     pygame.display.set_caption(caption)
  25.     surface = pygame.display.set_mode((width, height), flags)
  26.     rect = surface.get_rect()
  27.     clock = pygame.time.Clock()
  28.     running = True
  29.     delta = 0
  30.     fps = fps
  31.  
  32.     # Variables
  33.     background_color = 'black'
  34.     triangle = pygame.sprite.Sprite()
  35.     triangle.image = create_triangle((50, 50), 'dodgerblue')
  36.     triangle.rect = triangle.image.get_rect(center=rect.center)
  37.     triangle.original_image = triangle.image
  38.  
  39.     # Main Loop
  40.     while running:
  41.         for event in pygame.event.get():
  42.             if event.type == pygame.MOUSEMOTION:
  43.                 rotate_image(triangle, event.pos)
  44.             elif event.type == pygame.QUIT:
  45.                 running = False
  46.  
  47.         # Logic
  48.  
  49.         # Draw
  50.         surface.fill(background_color)
  51.         surface.blit(triangle.image, triangle.rect)
  52.  
  53.         # Render Buffer To Screen
  54.         pygame.display.flip()
  55.         # Idle And Get Delta Time
  56.         delta = clock.tick(fps)
  57.  
  58. pygame.init()
  59. main('Facing Towards Mouse', 800, 600)
  60. pygame.quit()
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement