長方形の交差判定
問題文中の top < bottom は間違いじゃないかと書いたら,グラフィックイメージの座標だと考えればOKだとコメントをもらった。なるほど。
判定方法は,要するに一方の長方形の4つある頂点のどれかか,もう一方の長方形の内部にあれば重なってると判定していいわけだ。
今日はRubyで書いた。
class Rect
def initialize(left, top, right, bottom)
@left = left
@top = top
@right = right
@bottom = bottom
end
def vertexes
[ [@left, @top],
[@left, @bottom],
[@right, @bottom],
[@right, @top] ]
end
def inner?(x,y)
(@left < x && x < @right) && (@top < y && y < @bottom)
end
def overlap?(rect)
rect.vertexes.any?{|x,y| inner?(x,y) }
end
end
r1 = Rect.new( 0, 0, 100, 100)
r2 = Rect.new(100, 0, 200, 100)
r3 = Rect.new( 50, 50, 150, 100)
p r1.overlap?(r2) # => false
p r1.overlap?(r3) # => true
p r2.overlap?(r3) # => true
追記:
このコードだと長方形がX方向とY方向の両方にずれていないと正しく判定できないことに気づいた。極端な話,ぴったりと重なっている長方形が「重なっていない」判定になる。
irb(main):001:0> r1 = Rect.new(0,0,100,100)
=> #<Rect:0x499f9f4 @top=0, @left=0, @bottom=100, @right=100>
irb(main):002:0> r1.overlap?(r1)
=> false
なんてこったい。
