我在使用 pygame 获取曲面中心时遇到问题。当尝试将它们放置在其他表面上时,它默认位于表面的左上角。
为了证明我的意思,我写了一个简短的程序。
import pygame
WHITE = (255, 255, 255)
pygame.init()
#creating a test screen
screen = pygame.display.set_mode((500, 500), pygame.RESIZABLE)
#creating the canvas
game_canvas = screen.copy()
game_canvas.fill(WHITE)
#drawing the canvas onto screen with coords 50, 50 (tho its using the upper left of game_canvas)
screen.blit(pygame.transform.scale(game_canvas, (200, 200)), (50, 50))
pygame.display.flip()
#you can ignore this part.. just making the program not freeze on you if you try to run it
import sys
clock = pygame.time.Clock()
while True:
delta_time = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
如果您运行此程序,它将在屏幕(显示器)上以坐标 50、50 绘制一个 200 x 200 的白色 game_canvas。但不是使用 game_canvas 的中心坐标 50、50.. 左上角是在 50, 50。
那么我如何使用 game_canvas 的中心将其放置在坐标 50、50 或任何其他给定坐标处?
请您参考如下方法:
它总是会在左上角 blit Surface。解决此问题的一种方法是计算必须将 Surface 放置在何处才能使其以某个位置为中心。
x, y = 50, 50
screen.blit(surface, (x - surface.get_width() // 2, y - surface.get_height() // 2))
这会将其中心定位在 (x, y) 坐标处。
或者,您可以创建一个以 x 和 y 为中心的 Rect 对象,并使用它来定位表面。
x, y = 50, 50
rect = surface.get_rect(center=(x, y))
screen.blit(surface, rect)
