Search code examples
mathluageometry

Lua math, detect if rectangle is inside the other rectangle


I'm trying to make a UI system similar to GMOD's vgui library (https://wiki.facepunch.com/gmod/vgui). In this library you can create an element, then child of that element. The child of a parent element will be clipped by the parent element's size. So if you have a redbox that has a width and height of 100, the the child element's of the redbox CANNOT be drawn outside the redbox and so on.


Solution

  • local parent_x = Parent.INTERNAL_VARS.draw_start_x
    local parent_y = Parent.INTERNAL_VARS.draw_start_y
    local parent_width  = Parent._width
    local parent_height = Parent._height
    
    v.INTERNAL_VARS.draw_start_x = parent_x + v.x
    v.INTERNAL_VARS.draw_start_y = parent_y + v.y
    
    local child_x = v.INTERNAL_VARS.draw_start_x
    local child_y = v.INTERNAL_VARS.draw_start_y
    local child_width  = v._width
    local child_height = v._height
    
    local x = math.max(child_x, parent_x)
    local y = math.max(child_y, parent_y)
    
    draw.DrawOutlinedRect(
       x,
       y,
       math.min(child_x + child_width,  parent_x + parent_width ) - x,
       math.min(child_y + child_height, parent_y + parent_height) - y
    )