Detect when two rectangles touch horizontally or vertically

93 views Asked by At

I have these two methods to determine collisions on the x-axis and y-axis:

def horizontal_overlap(char, object)
    char.x + char.width > object.x &&
    char.x < object.x + object.width  #Endl
end

def vertical_overlap(char, object)
    object.y + object.height > char.y &&
    object.y < char.y + char.height  #Endl
end

In my code, there is one moving rectangle and several other (fixed) rectangles. I want to detect if the moving rectangle touches one of the other rectangles. In addition, I want to determine if it touches it horizontally or vertically.

How do I approach this?

1

There are 1 answers

0
Nifriz On

You could use the #contains?(x, y) ⇒ Boolean function.

Here the documentation https://www.rubydoc.info/gems/ruby2d/Ruby2D/Rectangle