Created
October 10, 2012 00:55
-
-
Save pydsigner/3862496 to your computer and use it in GitHub Desktop.
Rotating a Red Box
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pygame | |
pygame.init() | |
# 1000 ms in a second, cycle length of 30 seconds | |
CYCLE = 1000. * 30 | |
def add_vectors(vec1, vec2): | |
return vec1[0] + vec2[0], vec1[1] + vec2[1] | |
def negate_vector(vec): | |
return -vec[0], -vec[1] | |
def rotate_box(box, degrees): | |
rotated = pygame.transform.rotate(box, degrees) | |
# Find the offset o | |
offset = add_vectors(negate_vector(rotated.get_rect().center), | |
box.get_rect().center) | |
return rotated, offset | |
def degrees_from_time(t): | |
""" | |
Get the degrees to rotate, which is: | |
percentage_of_cycle_complete = time_elapsed_in_cycle / cycle_length | |
degrees_to_rotate = percentage_of_cycle_complete * 360 | |
""" | |
t = t % CYCLE | |
return t / CYCLE * 360 | |
def main(): | |
screen = pygame.display.set_mode((400, 400)) | |
box = pygame.Surface((200, 200), pygame.SRCALPHA) | |
box.fill((255, 0, 0)) | |
# 400 - 200 / 2 | |
base_offset = (100, 100) | |
time_elapsed = 0 | |
clock = pygame.time.Clock() | |
while True: | |
for e in pygame.event.get(): | |
if e.type == pygame.QUIT or (e.type == pygame.KEYDOWN and | |
e.key == pygame.K_ESCAPE): | |
pygame.quit() | |
return | |
ms = clock.tick(60) | |
time_elapsed += ms | |
to_rotate = degrees_from_time(time_elapsed) | |
rotated, offset = rotate_box(box, to_rotate) | |
screen.fill((0, 0, 0)) | |
screen.blit(rotated, add_vectors(base_offset, offset)) | |
pygame.display.update() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment