用于将绘制的对象居中的Python坐标系问题

时间:2019-10-30 19:06:29

标签: python pygame

我们想在宽度为w且高度为h的表面上创建一个宽度为a和高度为b的矩形。

如果矩形需要与表面左边缘相距x_offset且垂直居中,那么我们必须传递给pygame.Rect函数的left,top,width,height的值是什么?在表面上?

我遇到了这个问题,我知道left等于x_offset,但是我不知道如何找出我尝试绘制的其他任何对象。

3 个答案:

答案 0 :(得分:2)

只需首先使用您知道的值创建Rect对象:

rect = pygame.Rect(x_offset, 0, w, h)

并使用其centery属性将矩形居中:

rect.centery = the_other_surface.get_rect().centery

答案 1 :(得分:0)

如果将变量重命名为可读的内容,则可以提供帮助。 例如:

rect_width = w
rect_height = h

surface_width = a
surface_height = b

rect_width和rect_height将是Rect的宽度和高度。 x_offset将在左侧。

rect_left = x_offset

要使其垂直居中,请找到垂直中心:

surface_center_v = surface_height / 2

然后将矩形放置在那里。

rect_top = surface_center_v

但是,这仅放置矩形的顶部边缘,我们需要垂直中心。 因此,将矩形的位置向上调整为矩形高度的一半,以使矩形的垂直中心与曲面的垂直中心对齐。

rect_top -= rect_height / 2

现在您已经拥有了rect_left,rect_top,rect_width和rect_height。

答案 2 :(得分:0)

要使用所有指定的变量(而不是将绝对大小硬编码到程序中),我将对要绘制的曲面和矩形都使用pygame的Rectangle对象。

import pygame
from time import sleep
pygame.init()

# Declare our variables and initialize
a,b = 0,0 # Declare screen dimensions.
w,h = 0,0 # Declare rectangle dimensions.
x,y = 0,0 # Declare placement locations on screen surface.

# Now set specific values to our variables
a = 500 # Screen Width
b = 500 # Screen Height

# We could use any surface here (such as for a sprite), but let's use the screen.
screen = pygame.display.set_mode((a,b),32) # Create a screen surface of size a X b
screen.fill(pygame.Color("DARKBLUE"))      # Fill it with Dark Blue.
screen_rect = screen.get_rect()            # Create a rectangle object for the screen.

w = 200 # Make the rectangle 200 wide.
h = 100 # Make the rectangle 100 high.
rec = pygame.Rect((x,y,w,h)) # Create a rectangle object for our drawn rectangle.
# Rec holds all of the placement and size values for the rectangle we want to draw.
rec_color = (255,0,0) # Let's draw a red rectangle.

distance_x = 50 # Place the rectangle 50 pixels over from the left side of the screen.
rec.x = distance_x                # Set rec's x value equal to distance_x.
rec.centery = screen_rect.centery # Set rec's y value to center of the screen y-axis
# Pygame's Rectangle Object handles the calculations for us. NICE! 

pygame.draw.rect(screen,rec_color,rec,2) # Draw a rectangle on the screen using a line
                                         # that is 2-pixels wide. (Use 0 to fill.)
pygame.display.flip()                    # Show the screen.

print("\nrec =",rec,end="\n\n")          # Let's see rec's final values.
sleep(3)                                 # Sleep for 3 seconds.
exit()                                   # Quit