Skip to content

Instantly share code, notes, and snippets.

@iminurnamez
Last active August 29, 2015 14:06
Show Gist options
  • Save iminurnamez/e1fb9ea7abe38c1cc203 to your computer and use it in GitHub Desktop.
Save iminurnamez/e1fb9ea7abe38c1cc203 to your computer and use it in GitHub Desktop.
pygame angle functions
"""A module of funtions dealing with angles in pygame.
All functions (other than project) take lists or tuples
of pygame coordinates as origin, destination
and return the appropriate angle in radians.
"""
from math import pi, cos, sin, atan2, degrees, radians
import pygame as pg
def get_angle(origin, destination):
"""Returns angle in radians from origin to destination.
This is the angle that you would get if the points were
on a cartesian grid. Arguments of (0,0), (1, -1)
return .25pi(45 deg) rather than 1.75pi(315 deg).
"""
x_dist = destination[0] - origin[0]
y_dist = destination[1] - origin[1]
return atan2(-y_dist, x_dist) % (2 * pi)
def get_xaxis_reflection(origin, destination):
"""Returns angle in radians reflected on x-axis. This is the
reflection angle of a top or bottom collision.
"""
x_dist = origin[0] - destination[0]
y_dist = origin[1] - destination[1]
return atan2(-y_dist, -x_dist) % (2 * pi)
def get_yaxis_reflection(origin, destination):
"""Returns angle in radians reflected on y-axis.
This is the angle of reflection for a side collision.
"""
x_dist = origin[0] - destination[0]
y_dist = origin[1] - destination[1]
return atan2(y_dist, x_dist) % (2 * pi)
def get_opposite_angle(origin, destination):
"""Returns angle in radians from destination to origin."""
x_dist = origin[0] - destination[0]
y_dist = origin[1] - destination[1]
return atan2(-y_dist, x_dist) % (2 * pi)
def project(pos, angle, distance):
"""Returns tuple of pos projected distance at angle
adjusted for pygame's y-axis.
"""
return (pos[0] + (cos(angle) * distance),
pos[1] - (sin(angle) * distance))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment