python 为屏幕pygame创建边界

2fjabf4q  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(152)

对于我的allevel课程,我正在用pygame做一个游戏。我遇到了一个问题,在左边和顶部阻止我的精灵通过边界,但在右边和底部,当我通过那个障碍时,精灵出现在对面的边缘。我希望这是有意义的。这是我目前为这一节准备的代码。x1和y1是我的第一个精灵。s坐标和x2和y2是我的第二个。

if x1 > WIDTH - Char1WIDTH or x1 < 0:
            x1 = 0

        if y1 > HEIGHT - Char1HEIGHT or y1 <0:
            y1 = 0
            
        if x2 > WIDTH - Char2WIDTH or x2 < 0:
            x2 = 0

        if y2 > HEIGHT - Char2HEIGHT or y2 <0:
            y2 = 0
w8rqjzmb

w8rqjzmb1#

如果子画面在右边,您需要将子画面与窗口的右边缘对齐;如果子画面在底部,您需要将子画面与窗口的底部对齐:

if x1 < 0:
    x1 = 0
if x1 > WIDTH - Char1WIDTH:
    x1 = WIDTH - Char1WIDTH

if y1 < 0:
    y1 = 0
if y1 > HEIGHT - Char1HEIGHT:
    y1 = HEIGHT - Char1HEIGHT

if x2 < 0:
    x2 = 0
if x2 > WIDTH - Char2WIDTH:
    x2 = WIDTH - Char2WIDTH

if y2 < 0:
    y2 = 0
if y2 > HEIGHT - Char2HEIGHT:
    y2 = HEIGHT - Char2HEIGHT

分别

x1 = max(0, min(WIDTH - Char1WIDTH, x1))
y1 = max(0, min(HEIGHT- Char1HEIGHT, y1))

x2 = max(0, min(WIDTH - Char2WIDTH, x2))
y2 = max(0, min(HEIGHT- Char2HEIGHT, y2))

但是我推荐使用pygame.Rect对象和clamp_ip。请分别参见pygame.Rect.clamp()pygame.Rect.clamp_ip()
返回一个新的矩形,该矩形已完全移动到参数Rect内部。

border_rect = pygame.Rect(0, 0, WIDTH, HEIGHT)
player1_rect = pygame.Rect(x1, y1, Char1WIDTH, Char1HEIGHT)
player2_rect = pygame.Rect(x2, y2, Char2WIDTH, Char2HEIGHT)

player1_rect.clamp_ip(border_rect)
x1, y1 = player1_rect.topleft  

player2_rect.clamp_ip(border_rect)
x2, y2 = player2_rect.topleft

相关问题