Python / PyGame如何在所有四个方向上检查rect是否在另一个rect的正上方或旁边?

时间:2017-09-26 17:44:11

标签: python pygame

我正在用Python和PyGame制作游戏,我想实现一个视线系统,当你在它们的长度或宽度范围内时,敌人可以检测到你(它们是Rects)。检查这个的最有效方法是什么?如果有任何帮助,这就是我所拥有的......

class FOV:
def view_left_top(ax,ay,bx,by,bh):
    return ax < bx and ay < (by + bh) and ay > by

def view_left_bottom(ax,ay,ah,bx,by,bh):
    return ax < bx and ay < (by + bh) and (ay + ah) > by

def view_right_top(ax,ay,aw,bx,by,bw,bh):
    return ax + aw > bx + bw  and ay < (by + bh) and ay > by

def view_right_bottom(ax,ay,aw,ah,bx,by,bw,bh):
    return ax + aw > bx + bw  and ay < (by + bh) and (ay + ah) > by

def view_top_x(ax,ay,bx,by,bw):
    return ay < by and ax > bx and ax < (bx + bw)

def view_top_y(ax,ay,aw,bx,by,bw):
    return ay < by and (ax + aw) > bx and ax < (bx + bw)

def view_bottom_x(ax,ay,bx,by,bw):
    return ay > by and ax > bx and ax < (bx + bw)

def view_bottom_y(ax,ay,aw,bx,by,bw):
    return ay > by and (ax + aw) > bx and ax < (bx + bw)

2 个答案:

答案 0 :(得分:0)

您可以使用pygame.Rect.colliderect(Rect)方法测试两个矩形是否重叠。

import pygame

class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.rect = pygame.Rect(x, y, 32, 32)  #x, y, width, height
    def update(self, screen, entities):
        pygame.draw.rect(screen, (255, 0, 0), self.rect)  #Draws red square

        for e in entities:
            if self.rect.colliderect(e.rect):
                is_colliding = True
                break
            else:
                is_colliding = False

答案 1 :(得分:0)

我最终通过将一些功能组合成一个函数和一个'if'语句来至少清理一下