| 1 | module StarFrame
|
|---|
| 2 | class Sprite
|
|---|
| 3 | class Collision
|
|---|
| 4 | class Rect < Collision
|
|---|
| 5 | attr_reader :x, :y, :width, :height
|
|---|
| 6 |
|
|---|
| 7 | def initialize target, method_name, x, y, width, height
|
|---|
| 8 | super
|
|---|
| 9 | @x, @y, @width, @height = x, y, width, height
|
|---|
| 10 | end
|
|---|
| 11 |
|
|---|
| 12 | def collide? other
|
|---|
| 13 | case other
|
|---|
| 14 | when Circle
|
|---|
| 15 | return collide_circle?(other)
|
|---|
| 16 | when Rect
|
|---|
| 17 | left, top, right, bottom = rect
|
|---|
| 18 |
|
|---|
| 19 | width, height = @width+other.width, @height+other.height
|
|---|
| 20 | left, top = left-other.width, top-other.height
|
|---|
| 21 | when Dot
|
|---|
| 22 | left, top, right, bottom = rect
|
|---|
| 23 | else
|
|---|
| 24 | return super
|
|---|
| 25 | end
|
|---|
| 26 | Collision.dot_in_rect?(other.global_position, [[left, top], [right, bottom]])
|
|---|
| 27 | end
|
|---|
| 28 |
|
|---|
| 29 | private
|
|---|
| 30 | def rect
|
|---|
| 31 | left, top = global_position
|
|---|
| 32 | right, bottom = left+@width, top+@height
|
|---|
| 33 | [left, top, right, bottom]
|
|---|
| 34 | end
|
|---|
| 35 |
|
|---|
| 36 | def collide_circle? other
|
|---|
| 37 | left, top, right, bottom = rect
|
|---|
| 38 |
|
|---|
| 39 | vleft, vtop = left-other.radius, top-other.radius
|
|---|
| 40 | vright, vbottom = right+other.radius, bottom+other.radius
|
|---|
| 41 |
|
|---|
| 42 | other_position = other.global_position
|
|---|
| 43 | return false unless Collision.dot_in_rect?(other_position, [[vleft, vtop], [vright, vbottom]])
|
|---|
| 44 |
|
|---|
| 45 | case
|
|---|
| 46 | when other_position[0] < left
|
|---|
| 47 | x = left
|
|---|
| 48 | when other_position[0] > right
|
|---|
| 49 | x = right
|
|---|
| 50 | else
|
|---|
| 51 | return true
|
|---|
| 52 | end
|
|---|
| 53 |
|
|---|
| 54 | case
|
|---|
| 55 | when other_position[1] < top
|
|---|
| 56 | y = top
|
|---|
| 57 | when other_position[1] > bottom
|
|---|
| 58 | y = bottom
|
|---|
| 59 | else
|
|---|
| 60 | return true
|
|---|
| 61 | end
|
|---|
| 62 |
|
|---|
| 63 | return Collision.dot_in_circle?([x, y], [other_position, other.radius])
|
|---|
| 64 | end
|
|---|
| 65 | end
|
|---|
| 66 | end
|
|---|
| 67 | end
|
|---|
| 68 | end
|
|---|