【问题标题】:Getting the center of surfaces in pygame with python 3.4使用 python 3.4 在 pygame 中获取曲面的中心
【发布时间】:2016-12-03 23:44:30
【问题描述】:

我在使用 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。但不是在坐标 50、50 处使用 game_canvas 的中心......是 50, 50。

那么如何使用 game_canvas 的中心将其放置在坐标 50、50 或任何其他给定坐标处?

【问题讨论】:

    标签: python pygame center rect


    【解决方案1】:

    它总是会在左上角对 Surface 进行 blit。解决此问题的一种方法是计算您必须将 Surface 放置在何处才能使其以某个位置为中心。

    x, y = 50, 50
    screen.blit(surface, (x - surface.get_width() // 2, y - surface.get_height() // 2))
    

    这会将其中心定位在 (x, y) 坐标处。

    或者,您可以创建一个以xy 为中心的Rect 对象,并使用它来定位表面。

    x, y = 50, 50
    rect = surface.get_rect(center=(x, y))
    screen.blit(surface, rect)
    

    【讨论】:

    • 谢谢,这一直困扰着我。然而,为了让它工作,我将我的 game_canvas 从屏幕副本更改为它自己的 pygame 表面,并在 blit 之外进行了转换。现在效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    相关资源
    最近更新 更多