I am new to python and graphics but have programmed before. According to http://en.wikipedia.org/wiki/Transformation_matrix#Rotation ,
For rotation by an angle θ
anticlockwise about the origin, the
functional form is x’ = xcosθ − ysinθ
and y’ = xsinθ + ycosθ
But the following python code rotates it in the clockwise direction. Could somebody explain this?. Also translating the rectangle to the origin and back to the center seems to be an overhead. Is there any way to avoid this?. Thanks in advance.
PS: I have looked at pygame.transform.rotate which does this but I would like to start from scratch to get better idea about the graphics. Is there a way to see the source of this method from python interpreter?
import pygame, sys, time
from math import *
from pygame.locals import *
co_ordinates =((200,200),(400,200),(400,300),(200,300))
window_surface = pygame.display.set_mode((500,500),0,32)
BLACK=(0,0,0)
GREEN=(0,255,0)
RED=(255,0,0)
window_surface.fill(BLACK)
ang=radians(30)
"""orig=pygame.draw.polygon(window_surface,GREEN,co_ordinates)
n_co_ordinates = tuple([(((x[0])*cos(ang)-(x[1])*sin(ang)),((x[0])*sin(ang)+(x[1])*cos(ang))) for x in n_co_ordinates])
n_co_ordinates = tuple([((x[0]+300),(x[1]+250)) for x in n_co_ordinates])
print(n_co_ordinates)
pygame.draw.polygon(window_surface,RED,n_co_ordinates)"""
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
for i in range(360):
ang=radians(i)
if i>=360:
i=0
n_co_ordinates = tuple([((x[0]-300),(x[1]-250)) for x in co_ordinates])
n_co_ordinates = tuple([((x[0]*cos(ang)-x[1]*sin(ang)),(x[0]*sin(ang)+x[1]*cos(ang))) for x in n_co_ordinates])
n_co_ordinates = tuple([((x[0]+300),(x[1]+250)) for x in n_co_ordinates])
window_surface.fill(BLACK)
pygame.draw.polygon(window_surface,RED,n_co_ordinates)
pygame.display.update()
time.sleep(0.02)
To rotate in the opposite direction change
angto-ang. I suspect you have got a sign wrong in the rotation matrix, but I can never remember. (EDIT: This is equivalent to changing the sign of thesinterms, becausesin(-x)==-sin(x)andcos(-x)==cos(x).)You can’t avoid the translation to the centre. The reason is that your transformation fixes the origin
(0,0)(since0*cos(...)==0), so you are always rotating about the origin. Thus, to rotate about anywhere else, you have to translate that point to the origin first.Here is the source of
rotate, fromtransform.cin the pygame source. It’s written in C.