pygame表面以无意义的方式旋转

时间:2019-06-22 10:24:34

标签: python pygame pygame-surface

我正在尝试构建一个简单的游戏,到目前为止,我只是在学习基础知识。
我正在尝试绘制一个倾斜45°的矩形,但是即使阅读了SO上的一些先前的问题,我也无法弄清楚如何使其居中。
因此,我尝试制作一个不断旋转的矩形;这是对应的代码。

alpha=0
while True:
    w, h=screen.get_size()
    s=pygame.Surface((w/2, h))
    pygame.draw.rect(s, col, (300,150,50,10))
    s=pygame.transform.rotozoom(s, alpha, 1)
    alpha+=2
    s.set_colorkey((0,0,0))
    background.blit(s, (0, 0))
    # flip screen, etc 

表面应该永远围绕某个中心旋转(我想用它清楚地知道它是什么),但是它以不规则的方式移动。
这是发生的事情的视频。

编辑:标记为重复,我正在删除视频链接

1 个答案:

答案 0 :(得分:0)

Rotating a rectangle (not image) in pygame为您提供了答案:

示例代码:

import pygame as py  

# define constants  
WIDTH = 500  
HEIGHT = 500  
FPS = 30  

# define colors  
BLACK = (0 , 0 , 0)  
GREEN = (0 , 255 , 0)  

# initialize pygame and create screen  
py.init()  
screen = py.display.set_mode((WIDTH , HEIGHT))  
# for setting FPS  
clock = py.time.Clock()  

rot = 0
rot_speed = 3

# define a surface (RECTANGLE)  
image_orig = py.Surface((100 , 100))  
# for making transparent background while rotating an image  
image_orig.set_colorkey(BLACK)  
# fill the rectangle / surface with green color  
image_orig.fill(GREEN)  
# creating a copy of orignal image for smooth rotation  
image = image_orig.copy()  
image.set_colorkey(BLACK)  
# define rect for placing the rectangle at the desired position  
rect = image.get_rect()  
rect.center = (WIDTH // 2 , HEIGHT // 2)  
# keep rotating the rectangle until running is set to False  
running = True  
while running:  
    # set FPS  
    clock.tick(FPS)  
    # clear the screen every time before drawing new objects  
    screen.fill(BLACK)  
    # check for the exit  
    for event in py.event.get():  
        if event.type == py.QUIT:  
            running = False  

    # making a copy of the old center of the rectangle  
    old_center = rect.center  
    # defining angle of the rotation  
    rot = (rot + rot_speed) % 360  
    # rotating the orignal image  
    new_image = py.transform.rotate(image_orig , rot)  
    rect = new_image.get_rect()  
    # set the rotated rectangle to the old center  
    rect.center = old_center  
    # drawing the rotated rectangle to the screen  
    screen.blit(new_image , rect)  
    # flipping the display after drawing everything  
    py.display.flip()  

py.quit()