2D vector graphics Problem
Scott David Daniels
Scott.Daniels at Acm.Org
Sun May 29 12:47:24 EDT 2005
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 at Acm.Org
More information about the Python-list
mailing list