简体   繁体   English

如何在pygame中旋转表面而不改变其形状

[英]How to rotate a surface in pygame, without changing its shape

I'm writing a class in pygame to create a sprite object, and I'd like to be able to rotate it. 我正在pygame中编写一个类来创建一个sprite对象,并且我希望能够旋转它。 It works fine with an image, and rotates without issue. 它可以很好地处理图像,并且可以毫无问题地旋转。 But when rotating a surface with a plain colour, the box appears to grow and shrink. 但是,当旋转具有纯色的表面时,盒子看起来会增大和缩小。 I know that this is a result of the surface changing size to fit the vertices of the rectangle inside, but how do I stop it? 我知道这是由于表面更改大小以适合内部矩形的顶点而导致的,但是如何停止它呢? I'd like to see a visual rotation. 我想看到视觉上的旋转。

I've created some sample code to show the problem that I'm facing, running it causes the box to simply change in size. 我创建了一些示例代码来显示我所面临的问题,运行它会导致包装盒的尺寸发生变化。

import sys, pygame
from pygame.locals import *

pygame.init()
SCREEN = pygame.display.set_mode((200, 200))
CLOCK  = pygame.time.Clock()

surface = pygame.Surface((50 , 50))
surface.fill((0, 0, 0))
rotated_surface = surface
rect = surface.get_rect()
angle = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    SCREEN.fill((255, 255, 255))
    angle += 5
    rotated_surface = pygame.transform.rotate(surface, angle)
    rect = rotated_surface.get_rect(center = (100, 100))
    SCREEN.blit(rotated_surface, (rect.x, rect.y))

    pygame.display.update()
    CLOCK.tick(30)

How do I fix this issue, to make the surface rotate how I want? 我如何解决此问题,以使曲面旋转到想要的位置?

Any help would be appreciated! 任何帮助,将不胜感激!

You have to create the Surface objects you create to stamp on the display surface in a way they use transparency information (That is - they have to have an alpha channel). 您必须创建创建的Surface对象,以使用透明性信息的方式在显示表面上进行标记(即-它们必须具有alpha通道)。

To do that, is just a question of passing the appropriate flag when creating your surface objects - simply replace this: 为此,仅是在创建表面对象时传递适当标志的问题-只需替换以下内容:

surface = pygame.Surface((50 , 50))

with: 有:

surface = pygame.Surface((50 , 50), pygame.SRCALPHA)

and it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM