微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

pygame.transform.rotate行为怪异

如何解决pygame.transform.rotate行为怪异

我已经在StackOverflow的其他地方看到了解决此问题的方法,但是对于这种语言,我太陌生了,无法将其应用于我的问题。

我正在制作一个Surface,在其上绘制东西,然后旋转它。结果与此人的问题相同:

矩形随着旋转旋转不规则地移动。这是可以解决的,还是必须更改我的方法

from pygame import * 
import sys

def drawShip(pos,angle,width,height,surface):   

    canvas = Surface((width,height))#A canvas to draw the ship on

    r = ((1),(1),height)#A placeholder rectangle
    draw.rect(canvas,(255,0),r)#Draw r on the surface

    canvas = transform.rotate(canvas,angle)#Rotate the canvas

    surface.blit(canvas,((pos[0] - width/2),(pos[1] - height/2)))#Draw the canvas onto the main surface        

s = display.set_mode((500,500))#Create the main surface   
i = 0

while True:
    for e in event.get():
            if e.type == QUIT:
                sys.exit()
            if e.type == KEYDOWN:
                i += 5
    drawShip((250,250),i,100,s)#Draw a ship
    display.flip()#Update the display

解决方法

请参见How do I rotate an image around its center using Pygame?

获得一个大小为Surfaceget_rect()旋转矩形,并通过关键字参数将矩形的中心设置到所需位置。使用矩形绘制表面。 blit的第二个参数可以是Rect对象,它指定目标位置:

rot_rect = canvas.get_rect(center = pos)
surface.blit(canvas,rot_rect)    

最小示例:

from pygame import * 
import sys

def drawShip(pos,angle,image,surface):   
    rot_image = transform.rotate(image,angle)
    rot_rect = rot_image.get_rect(center = pos)
    surface.blit(rot_image,rot_rect)      

init()
s = display.set_mode((500,500))
clock = time.Clock()

image = Surface((100,100),SRCALPHA)
image.fill((255,0))
angle = 0

while True:
    clock.tick(60)
    for e in event.get():
        if e.type == QUIT:
            sys.exit()
    if any(key.get_pressed()):
        angle += 1
    s.fill(0)
    drawShip((250,250),s)
    display.flip()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。