2016-12-03 26 views
2

我遇到了使用pygame獲取曲面中心的麻煩。它試圖將它們放置在其他曲面上時默認爲曲面的左上角。使用python獲取pygame中的曲面中心3.4

爲了證明我的意思,我寫了一個簡短的程序。

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

如果你運行這個程序,它會在COORDS 50,50繪製屏幕(顯示器)上的200 200白game_canvas但不是使用game_canvas中心在COORDS 50,50。 。左上角是50,50。

那麼,如何使用game_canvas的中心將它放置在座標50,50或任何其他給定的座標上?

回答

1

它將始終使表面在全角處閃現。解決這個問題的方法是計算你必須放置Surface的位置,以便它以一個位置爲中心。

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

這將定位它的中心在(x,y)座標。

+0

謝謝,這一直困擾着我。然而,爲了實現這個功能,我將我的game_canvas從屏幕副本更改爲它自己的pygame表面,並將我的轉換完成了。現在效果很好。 –