rect2.nim 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # author: Ethosa
  2. import vector2
  3. {.used.}
  4. type
  5. Rect2Obj* = object
  6. x*, y*, w*, h*: float
  7. proc Rect2*(x, y, w, h: float): Rect2Obj {.inline.} =
  8. Rect2Obj(x: x, y: y, w: w, h: h)
  9. proc Rect2*(pos, size: Vector2Obj): Rect2Obj {.inline.} =
  10. Rect2Obj(
  11. x: pos.x, y: pos.y,
  12. w: size.x, h: size.y
  13. )
  14. proc contains*(self: Rect2Obj, x, y: float): bool {.inline.} =
  15. self.x <= x and self.x+self.w >= x and self.y <= y and self.y+self.h >= y
  16. proc contains*(self: Rect2Obj, vector: Vector2Obj): bool {.inline.} =
  17. self.contains(vector.x, vector.y)
  18. proc contains*(self, other: Rect2Obj): bool {.inline.} =
  19. (self.contains(other.x, other.y) and
  20. self.contains(other.x+other.w, other.y) and
  21. self.contains(other.x, other.y+other.h) and
  22. self.contains(other.x+other.w, other.y+other.h))
  23. proc intersects*(self, other: Rect2Obj): bool =
  24. if self.w > other.w and self.h > other.h:
  25. (self.contains(other.x, other.y) or
  26. self.contains(other.x, other.y+other.h) or
  27. self.contains(other.x+other.w, other.y) or
  28. self.contains(other.x+other.w, other.y+other.h))
  29. else:
  30. (other.contains(self.x, self.y) or
  31. other.contains(self.x, self.y+self.h) or
  32. other.contains(self.x+other.w, self.y) or
  33. other.contains(self.x+other.w, self.y+self.h))
  34. proc contains*(self: Rect2Obj, a, b: Vector2Obj): bool =
  35. let
  36. left = intersects(a, b, Vector2(self.x, self.y), Vector2(self.x, self.y+self.h))
  37. right = intersects(a, b, Vector2(self.x+self.w, self.y), Vector2(self.x+self.w, self.y+self.h))
  38. top = intersects(a, b, Vector2(self.x, self.y), Vector2(self.x+self.w, self.y))
  39. bottom = intersects(a, b, Vector2(self.x, self.y+self.h), Vector2(self.x+self.w, self.y+self.h))
  40. left or right or bottom or top
  41. proc clamp*(a, b, c: float): float {.inline.} =
  42. if a < b:
  43. b
  44. elif a > c:
  45. c
  46. else:
  47. a
  48. proc isCollideWithCircle*(self: Rect2Obj, x, y, r: float): bool =
  49. let
  50. dx = clamp(x, self.x, self.x+self.w) - x
  51. dy = clamp(y, self.y, self.y+self.h) - y
  52. dx*dx + dy*dy <= r*r
  53. # --- Operators --- #
  54. proc `$`*(x: Rect2Obj): string {.inline.} =
  55. "Rect2(x: " & $x.x & ", y: " & $x.y & ", w: " & $x.w & ", h: " & $x.h & ")"