如何通过改变它的点坐标来旋转对象(Python,Pygame)

时间:2015-02-23 17:39:09

标签: python animation pygame coordinates

我一直在使用Python中的Pygame进行基本游戏,但我不能为我的生活找出一个通过改变它的基本坐标来旋转形状的公式。这就是我到目前为止所拥有的:

pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Singleplayer Mode")
done = False
clock = pygame.time.Clock()

p11 = 100
p12 = 100
p21 = 100 
p22 = 150
p31 = 150
p32 = 125

upspeed = 0
rightspeed = 0
topspeed = 25

pause = "false"

while not done:
    screen.fill(WHITE)        
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key == K_w:
                upspeed -= 1
            if event.key == K_s:
                upspeed += 1
            if event.key == K_d:
                rightspeed += 1
            if event.key == K_a:
                rightspeed -= 1
            if event.key == K_SPACE:
                pass
            if pause == "true":
                if event.key == K_p:
                    pause = "false"
                    print("Game is unpaused.")
                if event.key == K_q:
                    done = True
            if event.key == K_p:
                pause = "true"
                print("Game is paused.")

    if rightspeed > 0:
        rightspeed -= 0.01
    if rightspeed < 0:
        rightspeed += 0.01
    if upspeed > 0:
        upspeed -= 0.01
    if upspeed < 0:
        upspeed += 0.01

    if pause != "true":
        p11 += rightspeed
        p21 += rightspeed
        p31 += rightspeed
        p12 += upspeed
        p22 += upspeed
        p32 += upspeed

    if p12 < 0:
        upspeed = 0
    if p11 < 0:
        rightspeed = 0
    if p31 > w:
        rightspeed = 0
    if p22 > h:
        upspeed = 0

    pygame.draw.polygon(screen, BLACK, [[p11, p12], [p21, p22], [p31, p32]], 0)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

基本上我想要做的就是拍摄我创建的三角形,然后旋转它而不是按下d和a键使其向右或向左移动。我可以用任何公式来改变p11,p12,p21,p22,p31和p32的值来实现这个目的吗?

1 个答案:

答案 0 :(得分:1)

如果您将坐标表示为2d坐标[100,100][100, 150][150, 125],则可以通过应用矩阵来旋转这些坐标

[  0, -1, 
   1,  0   ] (90 degree clockwise rotation)

您可以使用一些库来帮助您,EG numpy

x = np.array( ((100,100), (100, 150), (150, 125)) )
y = np.matrix( ((0,-1), (1, 0)) )
print (x * y)

获得任意旋转矩阵:

def get_matrix(angle) :
     return np.matrix( ((math.cos(angle),-math.sin(angle)), (math.sin(angle), math.cos(angle))) )