My Pygame Game Engine
at main 1.8 kB view raw
1## Imports 2 3import pygame, math 4 5## Class 6 7class math_utils: 8 9 ## Function for rotating a image around its center in pygame 10 11 def rotate_center(self, image, angle, x, y): 12 13 # Rotate the image 14 15 rotated_image = pygame.transform.rotate(image, angle) 16 17 # Center the image to its designated x and y coordinate to couteract the wierd rotation in pygame 18 19 new_rect = rotated_image.get_rect(center = image.get_rect(center = (x, y)).center) 20 21 return rotated_image, new_rect 22 23 ## Pythagoras Theorem that returns the hypotenus 24 25 def distance_between_points(self, x1, y1, x2, y2): 26 return math.hypot(x2 - x1, y2 - y1) 27 28 ## Gets the direction from one Vector2 to another Vector2 in degrees 29 30 def direction_between_points(self, x1, y1, x2, y2): 31 radians = math.atan2(y2-y1, x2-x1) 32 return(math.degrees(radians)) 33 34 ## Gets the difference between angles 35 36 def angle_difference(self, x, y): 37 return math.atan2(math.sin(x-y), math.cos(x-y)) 38 39 ## Two functions that return the Vector2 from (0, 0) if you were to go at an angle at a speed for example 40 ## length=2 and angle=45 would go to (1.4, 1.4) 41 ## This is useful for example cars in topdown that usually move in a 360 direction 42 43 def lengthdir_x(self, length, angle): 44 radian_angle = angle * math.pi / 180 45 return length * math.cos(radian_angle) 46 47 def lengthdir_y(self, length, angle): 48 radian_angle = angle * math.pi / 180 49 return length * math.sin(radian_angle) 50 51 ## Returns if a Vector2 is in a rectangle 52 53 def in_rect(self, x, y, rectx, recty, width, height): 54 if x > rectx and x < rectx + width: 55 if y > recty and y < recty + height: 56 return True 57 return False