Gri*_*der 4 python pygame center rect
我在使用 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()
Run Code Online (Sandbox Code Playgroud)
如果你运行这个程序,它会在屏幕(显示器)的坐标 50, 50 处绘制一个 200 x 200 的白色 game_canvas。但不是使用坐标 50, 50 处的 game_canvas 的中心..左上角位于 50 ,50。
那么如何使用 game_canvas 的中心将其放置在坐标 50、50 或任何其他给定坐标处?
它总是会在左上角位块传输 Surface。解决这个问题的方法是计算必须将 Surface 放置在哪里,才能使其以某个位置为中心。
x, y = 50, 50
screen.blit(surface, (x - surface.get_width() // 2, y - surface.get_height() // 2))
Run Code Online (Sandbox Code Playgroud)
这会将其中心定位在 (x, y) 坐标处。
或者,您可以创建一个Rect中心位于x和 的对象y,并使用它来定位曲面。
x, y = 50, 50
rect = surface.get_rect(center=(x, y))
screen.blit(surface, rect)
Run Code Online (Sandbox Code Playgroud)