Skip to content

Instantly share code, notes, and snippets.

@taylorlapeyre
Created December 12, 2012 01:03
Show Gist options
  • Save taylorlapeyre/4263944 to your computer and use it in GitHub Desktop.
Save taylorlapeyre/4263944 to your computer and use it in GitHub Desktop.
Used to detect if two Rectangles are intersecting
# A simple Rectangle class
class Rectangle
attr_accessor :x, :y, :width, :height
def initialize(x, y, width, height)
@x, @y = x, y
@width, @height = width, height
end
def empty?
@width <= 0 || height <= 0
end
# Determine if this Rectangle overlaps another
def overlaps?(rect)
return false if self.empty? or rect.empty?
(rect.x + rect.width) > @x &&
(rect.y + rect.height) > @y &&
(@x + @width) > rect.x &&
(@y + @height) > rect.y
end
end
# Sample Run
# Make three Rectangles
r1 = Rectangle.new(0, 0, 4, 8)
r2 = Rectangle.new(1, 1, 4, 8)
r3 = Rectangle.new(10, 10, 4, 8)
puts r1.overlaps? r2 # Returns true
puts r1.overlaps? r3 # Returns false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment