python/pygame如何在所有四个方向上的另一个矩形上方或旁边的rect检查



我正在与Python和Pygame一起制作游戏,我想实现一个视线系统,当您在您的长度或宽度之内时,敌人可以检测到您(它们是矩形)。检查此问题的最有效方法是什么?如果有任何帮助,这就是我拥有的...

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)

您可以使用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

我最终通过将其中的某些功能组合到一个函数和'if'语句

中,至少可以将其清除一点。

相关内容

最新更新