Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if 2 ranges intersect in any way in ruby?

Tags:

range

ruby

I am attempting to code hitboxes within Gosu in ruby, and want to check if 2 ranges meet (the ranges being co-ords) i want it to simply give true or false

I've looked into it and found the range.cover? code, however after testing this shows it only checks if one range entirely fits inside another, and not if they only partially connect.

#both sprites are arrays, with the following structure
#[image_data, sprite_x, sprite_y]
#image_data.width would return how wide the image is
#The x and y is the top left of the sprite
  def hit_scan(sprite1, sprite2)
    x_connect = (sprite1[1]..sprite1[1] + sprite1[0].width).cover?(sprite2[1]..(sprite2[1] + sprite2[0].width))
    y_connect = (sprite1[2]..sprite1[2] + sprite1[0].height).cover?(sprite2[2]..(sprite2[2] + sprite2[0].height)
    if x_connect == true
      if y_connect == true
        return true
      else
        return false
      end
    else
      return false
    end
  end

This is what I tried, and only returns true when the entire sprite is in the other one.

I expected that whenever the sprites touched, it would return a true statement, but only when one sprite is in another does it return true.

like image 971
Pixelz Avatar asked Aug 29 '19 20:08

Pixelz


1 Answers

You can check if one range includes begin or end of another one:

r1 = (1..5)
r2 = (4..8)

r1.include?(r2.begin) || r1.include?(r2.end) || r2.include?(r1.begin) || r2.include?(r1.end)

In your case:

r1 = (sprite1[1]..sprite1[1] + sprite1[0].width)
r2 = (sprite2[1]..sprite2[1] + sprite2[0].width)
r1.include?(sprite2[1]) || r1.include?(sprite2[1] + sprite2[0].width) || 
  r2.include(sprite1[1]) || r2.include(sprite1[1] + sprite1[0].width)

assuming that the ranges are not endless.

like image 107
mrzasa Avatar answered Sep 26 '22 21:09

mrzasa