Getting the center of surfaces in pygame with python 3.4

半城伤御伤魂 提交于 2020-01-05 03:06:33

问题


I'm having troubles getting the center of surfaces with pygame. It defaults to the upper left corner of surfaces when trying to place them on other surfaces.

To demonstrate what I mean I wrote a short program.

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()

If you run this program it will draw a 200 by 200 white game_canvas on the screen (display) at the coords 50, 50. But instead of using the center of the game_canvas at the coords 50, 50.. the upper left is at 50, 50.

So how do I use the center of the game_canvas to have it place at the coords 50, 50 or any other given coords?


回答1:


It will always blit the Surface at the topleft corner. A way around this is to calculate where you have to place the Surface in order for it to be centered around a position.

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

This will position it's center at the (x, y) coordinates.



来源:https://stackoverflow.com/questions/40953796/getting-the-center-of-surfaces-in-pygame-with-python-3-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!