0

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?

Stefan
  • 109,145
  • 14
  • 143
  • 218
IssUseless
  • 47
  • 5
  • _"they don't work properly"_ – that's quite vague. What doesn't work in particular? Can you give an example for char and object pairs that don't work? – Stefan Aug 30 '22 at 16:34
  • the vertical_overlap and horizontal_overlap functions don't work independently – IssUseless Aug 31 '22 at 09:23
  • Yes, you said so. Please provide an example of `char` and `object` so I can see what you mean by that. – Stefan Aug 31 '22 at 10:09
  • An Example: ```@pl = Rectangle.new(x:400,y:300,width:50,height:50,color:'blue'), @char = Rectangle.new(x:500,y:300,width:50,height:50,color:'blue')``` – IssUseless Aug 31 '22 at 10:22
  • Another Example:```horizontal_overlap(@pl,@char)``` or `vertical_overlap(@pl,@char)` – IssUseless Aug 31 '22 at 10:24
  • Returns either true of false depending on whether collision is detected **BUT** They don't work properly – IssUseless Aug 31 '22 at 10:25
  • Seems to work just fine:`horizontal_overlap(@pl,@char)` returns `false` because they don't overlay horizontally – `@pl` is left from `@char`. On the other hand, `vertical_overlap(@pl,@char)` returns `true` because they do overlap vertically – `@pl` and `@char` have the very same y-coordinate. Maybe you have a different understanding of "overlap". Please clarify what you mean by _"don't work properly"_. What do you expect? (and why) – Stefan Aug 31 '22 at 10:33
  • Also ***@pl*** stands for player, Anyways.... The *horizontal_overlap* function returns **true** when ***@pl*** is to the right or the left of ***@char*** no matter how far ***@pl*** is from ***@char*** and the *vertical_overlap* function returns true when ***@pl*** is over of under ***@char*** no mater how far ***@pl*** is over or under from ***@char***. (Sorry for taking long to reply it's 'cuz I had to sweep the floor) – IssUseless Aug 31 '22 at 11:04
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/247706/discussion-between-stefan-and-issuseless). – Stefan Aug 31 '22 at 11:05
  • 'Kay........... – IssUseless Aug 31 '22 at 11:06

1 Answers1

0

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

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

Nifriz
  • 1,033
  • 1
  • 10
  • 21