[Tutor] 2d rotation gives unexpected results.

Dave Angel davea at davea.name
Tue Jul 23 21:29:39 CEST 2013


On 07/23/2013 08:27 AM, enmce wrote:
> Hello!
> This is my first post, nice to meet you all!
> I`m biology student from Russia, trying to learn python to perform some simple simulations.

Hello, and welcome.

However, please don't post identical messages on tutor and python-list. 
  The response you got there from Peter Otten was right on.
>
> Here`s my first problem.
> I`m trying to perform some simple 2d vector rotations in pygame, in order to learn the basics of linear algebra and 2d transformations. So far i understand matrix multiplication pretty well, and probably all my math is right. Eventually i`m planning to write Poly class, and use it to rotate and translate some simple shapes. But when i try and write it in the program, i get very weird results, like all points of rectangle with coordinates [0,0],[0,100],[100,0],[100,100] start to go spiral and eventually shrink to the center instead of rotating right. Although even Excel calculations with this formulas give me right result.
> What is wrong with my code?
>
> [code]import pygame
> import math as m
>
> black = ( 0, 0, 0)
> white = ( 255, 255, 255)
> green = ( 0, 255, 0)
> red = ( 255, 0, 0)
>
> class Poly():
>      pos = [100,100] #x and y coordinates of a point
>      rot = m.radians(1) #rotation in degrees
>      def draw(self): #draw point
>          pygame.draw.circle(screen,white,self.pos,10,0)
>      def rotate(self): # rotation method
>          sin = m.sin(self.rot) #calculationg sin and cos
>          cos = m.cos(self.rot)
>          x_rot = int(self.pos[0]*cos-self.pos[1]*sin) #mulpitplicating vector to rotation matrix
>          y_rot = int(self.pos[0]*sin+self.pos[1]*cos)
>

By calling int() on those two lines, you have just drastically changed 
the point's location.  That won't be visible right away, but when you 
use that value repeatedly, the error will add up pretty quickly.

In fact, just repeatedly calculating those values will eventually 
produce some noticeable errors.  Those errors can be eliminated as well, 
but it'll be a bit harder.





-- 
DaveA



More information about the Tutor mailing list