[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Rotation question



Andre Roberge wrote:
Ok, here's a quick stab at it...

I couldn't get that to work. Maybe it's something else.
If you have a moment, this code rotates a box on the screen and shows what point I'm interested in tracking. Can you see what I'm doing wrong?


'''
I'm trying to follow a point in its path along the rotation.
The white dot should be approximately in the green square at all times, but it's not.
Here's the manual rotate routine I'm using.
How do I line up that point so newox, newoy follow the green square?
'''



import pygame import math pygame.init() bg = pygame.display.set_mode((640, 480), 32) pic = pygame.Surface((30, 30), pygame.SRCALPHA, 32).convert_alpha() pic.fill([255, 0, 0, 255]) pic.fill([0, 255, 0, 255], (12, 25, 5, 5)) w, h = pic.get_size() ox, oy = 15,30

for angle in range(360):
    radians=(2*3.1416*angle)/360
    cosine=math.cos(radians)
    sine=math.sin(radians)
    Point1x = (-h*sine)
    Point1y=(h*cosine)
    Point2x=(w*cosine-h*sine)
    Point2y=(h*cosine+w*sine)
    Point3x=(w*cosine)
    Point3y=(w*sine)

    minx=min(0,min(Point1x,min(Point2x,Point3x)))
    miny=min(0,min(Point1y,min(Point2y,Point3y)))
    maxx=max(Point1x,max(Point2x,Point3x))
    maxy=max(Point1y,max(Point2y,Point3y))

    DestBitmapWidth =math.ceil(math.fabs(maxx)-minx)
    DestBitmapHeight =math.ceil(math.fabs(maxy)-miny)

    #1. Translate your graph so that (x, y) is the new origin (0, 0).
    x, y = 0, 0 # Origin is 0, 0
    x1, y1 = 15, 30 # Point of interest
    x2 = x1 - x
    y2 = y1 - y

    #2. Rotate about that origin
    x3 = x2 * cosine - y2 * sine
    y3 = x2 * sine   + y2 * cosine

    #3. Translate back to the original reference frame
    newox = x3 + x
    newoy = y3 + y

print "Angle: %d Dest bitmap width, height: %d %d New origin: %d %d" % (angle, DestBitmapWidth, DestBitmapHeight, newox, newoy)

pic2 = pygame.Surface((DestBitmapWidth, DestBitmapHeight), pygame.SRCALPHA, 32).convert_alpha()
pic2.fill([0, 0, 255, 255])
for x in range(DestBitmapWidth):
for y in range(DestBitmapHeight):
SrcBitmapx=int((x+minx)*cosine+(y+miny)*sine)
SrcBitmapy=int((y+miny)*cosine-(x+minx)*sine)
if (SrcBitmapx >= 0 and SrcBitmapx < w and SrcBitmapy >=0 and SrcBitmapy < h) :
c = pic.get_at([SrcBitmapx, SrcBitmapy])
pic2.set_at((x, y), c)
pic2.fill((255, 255, 255), (newox, newoy, 2, 2))


    bg.fill((0, 0, 0))
    bg.blit(pic, (100, 100))
    bg.blit(pic2, (200, 100))
    pygame.display.update()
pygame.quit()