Re: 2D vector graphics Problem
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: 2D vector graphics Problem

From: Scott David Daniels <Scott.Daniels@Acm.Org>
Date: Sun May 29 2005 - 18:47:24 CEST

Karl Max wrote:
> def rotate(self, w):
> # This method belongs to the class Vertex
> # w = angle expressed in radiants
> x, y = self.coords
> xRel, yRel = self.relPoint # The rotation should be relative to this
> sin, cos = math.sin(w), math.cos(w)
> x = x * cos - y * sin - xRel * cos + yRel * sin + xRel
> y = x * sin + y * cos - xRel * sin - yRel * cos + yRel
> self.coords = (x,y)

Your equation for y uses the new x, not the old x. Be more free with
names. Here's one way to write it:

class ...
     def rotate(self, angle):
         '''Rotate point angle radians around relPoint'''
         x, y = self.coords
         xRel, yRel = self.relPoint
         sin, cos = math.sin(angle), math.cos(angle)
         newx = x * cos - y * sin - xRel * cos + yRel * sin + xRel
         newy = x * sin + y * cos - xRel * sin - yRel * cos + yRel
         self.coords = newx, newy

If you define a testcase or two, you can catch things like this early.

test = Point(1, 1)
test.rotate(math.pi / 2)
x, y = test.coords
assert (x - -1) ** 2 + (y - 1) ** 2 < .00001

--Scott David Daniels
Scott.Daniels@Acm.Org
Received on Thu Sep 29 16:16:01 2005