如果对象的坐标位于 (0,0),如何处理 pygame 中对象的环绕矩形

问题描述 投票:0回答:1

我有一些代码可以在 pygame 中的某些文本周围包裹一个矩形:

import pygame as pg
font = pg.font.SysFont("Comic Sans MS", 30)

def wrapRect(obj, color='Black'):
    rect = obj.get_rect()
    pg.draw.rect(obj, color, rect.inflate(10,10), 2)
    return obj

playButton = wrapRect(font.render('Play', True, 'Black'))
screen.blit(playButton, (200, 170))

我制作了wrappRect,在作为参数给出的对象周围包裹一个矩形。

这段代码不起作用,因为在 blit() 函数将文本放置在所需的坐标之前,我假设播放按钮的默认坐标是 (0,0),所以当我使用 inflate() 函数时,它使得这些坐标为负。结果,周围的矩形没有显示出来。我该如何做到这一点,以便 wrapRect 考虑到我可能想要将对象重新定位到 (0,0) 之外?

python pygame game-development pygame-surface
1个回答
0
投票

你可以将这行代码“pg.draw.rect(object, color[r,g,b], rect[x,y,w,h], width)”解释为绘制一个(w,h)尺寸, (r,g,b) 颜色,(宽度) 大小边框矩形位于对象的 (x,y) 位置 对象上。

是的,它位于对象的 (x,y) 位置,这意味着该表面具有与屏幕不同的坐标系。就像你看不到在屏幕之外绘制的部分一样,你也看不到在表面之外绘制的部分(即负坐标)。

在“wrapRect”函数中,您对文本表面的矩形进行了膨胀,这将导致矩形的坐标变为负值。您还将边框宽度设置为 2,这样您就看不到文本表面上绘制的任何内容。如果将宽度设置为 0(即填充),您将看到文本表面被颜色填充。

要解决这个问题,可以创建一个矩形表面(背景),然后在矩形表面上绘制边框和文本表面。

def wrapRect(obj,color='Black'):
    obj_rect=obj.get_rect()
    inflated_rect=obj_rect.inflate((10,10))
    nw,nh=inflated_rect.size
    # create a new surface called rect_surf
    # you can think of it as the background of the button
    rect_surf=pygame.Surface((nw,nh))
    rect_surf.fill('White')
    # draw the border on rect_surf
    pygame.draw.rect(rect_surf,color,(0,0,nw,nh),2)
    # draw obj on the center of rect_surf
    obj_rect.center=nw//2,nh//2
    rect_surf.blit(obj,obj_rect)
    return rect_surf

现在您不仅可以在(0,0)处绘制按钮,还可以在其他坐标处绘制按钮。 (只需更改“screen.blit()”的坐标即可)

© www.soinside.com 2019 - 2024. All rights reserved.