我开发了2D平台游戏和物理工作 . 但是,在我看来,玩家的矩形碰撞检查看起来过载,因为它使用世界对象穿过整个数组3次 . 是否可以优化代码并减少通过量?

# First iteration: checks collisions on x-axis 
    self.rect.left += self.x_vel
    self.__check_collisions(objects, 'X')

    # Second: y-axis
    self.rect.top += self.y_vel
    self.onground = False
    self.__check_collisions(objects, 'Y')

    # Third: checks if player is on the ground. When two rects contacts but
    # not intersects, colliderect doesn't consider it as a collide, and 
    # y_vel will increase on the ground. This shouldn't happen.
    for obj in objects:
            if pg.Rect(self.rect.x, self.rect.y + 1, self.size[0], 
                       self.size[1]).colliderect(obj.rect):
                self.onground = True
                self.y_vel = 0

__check_collisions函数:

for obj in objects:
        if pg.Rect.colliderect(self.rect, obj.rect):
            if direction == 'X':
                if self.x_vel > 0:
                    self.rect.right = obj.rect.left
                    self.x_vel = 0
                if self.x_vel < 0:
                    self.rect.left = obj.rect.right
                    self.x_vel = 0
            elif direction == 'Y':
                if self.y_vel > 0:
                    self.onground = True
                    self.rect.bottom = obj.rect.top
                    self.y_vel = 0
                if self.y_vel < 0:
                    self.rect.top = obj.rect.bottom
                    self.y_vel = - self.y_vel / 2