如何设置pygame.transform.rotate()的旋转中心?
我想让一个矩形围绕一个不是中心的点旋转。到目前为止,我的代码是:
import pygame
pygame.init()
w = 640
h = 480
degree = 45
screen = pygame.display.set_mode((w, h))
surf = pygame.Surface((25, 100))
surf.fill((255, 255, 255))
surf.set_colorkey((255, 0, 0))
bigger = pygame.Rect(0, 0, 25, 100)
pygame.draw.rect(surf, (100, 0, 0), bigger)
rotatedSurf = pygame.transform.rotate(surf, degree)
screen.blit(rotatedSurf, (400, 300))
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
我可以通过改变角度来实现不同的旋转,但现在的旋转是围绕矩形的中心进行的。我想把旋转的点设置为矩形中心以外的其他点。
5 个回答
我同意MegaIng和skrx的看法。不过我也得承认,看完他们的回答后,我还是没完全明白这个概念。后来我找到了一份关于在边缘旋转的炮台的游戏教程。
运行之后,我心里还是有疑问,但我发现他们用的炮台图片其实是个小技巧。
这张图片并不是围绕炮台的中心居中的,而是围绕支点居中的,图片的另一半是透明的。意识到这一点后,我把同样的做法应用到了我虫子的腿上,现在它们都能正常工作了。以下是我的旋转代码:
def rotatePivoted(im, angle, pivot):
# rotate the leg image around the pivot
image = pygame.transform.rotate(im, angle)
rect = image.get_rect()
rect.center = pivot
return image, rect
希望这对你有帮助!
我也遇到过这个问题,找到了一种简单的解决办法:你可以创建一个更大的区域(长度和高度都加倍),然后把较小的区域放到这个更大的区域里,这样旋转的中心点就是更大的区域的中心。现在你只需要围绕中心旋转这个更大的区域就可以了。
def rotate(img, pos, angle):
w, h = img.get_size()
img2 = pygame.Surface((w*2, h*2), pygame.SRCALPHA)
img2.blit(img, (w-pos[0], h-pos[1]))
return pygame.transform.rotate(img2, angle)
(如果你画个草图,可能会更容易理解,但相信我:这个方法有效,而且在我看来比其他解决方案更简单易懂。)
要让一个表面围绕它的中心旋转,首先我们要旋转这个图像,然后得到一个新的矩形(rect),并把之前矩形的center
坐标传给它,这样就能保持它在中心位置。如果想要围绕一个任意的点旋转,我们基本上也可以这样做,但还需要在中心位置(也就是旋转的支点)加上一个偏移向量,这样才能移动这个矩形。每次旋转图像时,这个向量也需要一起旋转。
所以我们需要保存这个支点(图像或精灵的原始中心)——可以用元组、列表、向量或者矩形来存储,还有偏移向量(也就是我们移动矩形的量),然后把它们传给rotate
函数。接着我们旋转图像和偏移向量,得到一个新的矩形,把支点加上偏移作为center
参数传入,最后返回旋转后的图像和新的矩形。
import pygame as pg
def rotate(surface, angle, pivot, offset):
"""Rotate the surface around the pivot point.
Args:
surface (pygame.Surface): The surface that is to be rotated.
angle (float): Rotate by this angle.
pivot (tuple, list, pygame.math.Vector2): The pivot point.
offset (pygame.math.Vector2): This vector is added to the pivot.
"""
rotated_image = pg.transform.rotozoom(surface, -angle, 1) # Rotate the image.
rotated_offset = offset.rotate(angle) # Rotate the offset vector.
# Add the offset vector to the center/pivot point to shift the rect.
rect = rotated_image.get_rect(center=pivot+rotated_offset)
return rotated_image, rect # Return the rotated image and shifted rect.
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# The original image will never be modified.
IMAGE = pg.Surface((140, 60), pg.SRCALPHA)
pg.draw.polygon(IMAGE, pg.Color('dodgerblue3'), ((0, 0), (140, 30), (0, 60)))
# Store the original center position of the surface.
pivot = [200, 250]
# This offset vector will be added to the pivot point, so the
# resulting rect will be blitted at `rect.topleft + offset`.
offset = pg.math.Vector2(50, 0)
angle = 0
running = True
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
keys = pg.key.get_pressed()
if keys[pg.K_d] or keys[pg.K_RIGHT]:
angle += 1
elif keys[pg.K_a] or keys[pg.K_LEFT]:
angle -= 1
if keys[pg.K_f]:
pivot[0] += 2
# Rotated version of the image and the shifted rect.
rotated_image, rect = rotate(IMAGE, angle, pivot, offset)
# Drawing.
screen.fill(BG_COLOR)
screen.blit(rotated_image, rect) # Blit the rotated image.
pg.draw.circle(screen, (30, 250, 70), pivot, 3) # Pivot point.
pg.draw.rect(screen, (30, 250, 70), rect, 1) # The rect.
pg.display.set_caption('Angle: {}'.format(angle))
pg.display.flip()
clock.tick(30)
pg.quit()
这里有一个使用pygame.sprite.Sprite
的版本:
import pygame as pg
from pygame.math import Vector2
class Entity(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = pg.Surface((122, 70), pg.SRCALPHA)
pg.draw.polygon(self.image, pg.Color('dodgerblue1'),
((1, 0), (120, 35), (1, 70)))
# A reference to the original image to preserve the quality.
self.orig_image = self.image
self.rect = self.image.get_rect(center=pos)
self.pos = Vector2(pos) # The original center position/pivot point.
self.offset = Vector2(50, 0) # We shift the sprite 50 px to the right.
self.angle = 0
def update(self):
self.angle += 2
self.rotate()
def rotate(self):
"""Rotate the image of the sprite around a pivot point."""
# Rotate the image.
self.image = pg.transform.rotozoom(self.orig_image, -self.angle, 1)
# Rotate the offset vector.
offset_rotated = self.offset.rotate(self.angle)
# Create a new rect with the center of the sprite + the offset.
self.rect = self.image.get_rect(center=self.pos+offset_rotated)
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
entity = Entity((320, 240))
all_sprites = pg.sprite.Group(entity)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
keys = pg.key.get_pressed()
if keys[pg.K_d]:
entity.pos.x += 5
elif keys[pg.K_a]:
entity.pos.x -= 5
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.draw.circle(screen, (255, 128, 0), [int(i) for i in entity.pos], 3)
pg.draw.rect(screen, (255, 128, 0), entity.rect, 2)
pg.draw.line(screen, (100, 200, 255), (0, 240), (640, 240), 1)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()