简体   繁体   中英

Getting the center of surfaces in pygame with python 3.4

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?

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 its center at the (x, y) coordinates.

Alternatively, you can create a Rect object with the center at x and y , and use that to position the surface.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM