lq_math_util.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import {IPos, IRect} from "../data/lq_interface";
  2. export class LQMathUtil {
  3. public static random(min: number, max: number): number {
  4. if (min === max) {
  5. return min;
  6. } else if (min < max) {
  7. return Math.random() * (max - min) + min;
  8. } else {
  9. return Math.random() * (min - max) + max;
  10. }
  11. }
  12. public static random_int(min: number, max: number): number {
  13. return Math.floor(this.random(min, max));
  14. }
  15. public static get_radians(pos: IPos, target_pos: IPos) {
  16. const r = Math.atan2(target_pos.y - pos.y, target_pos.x - pos.x);
  17. return r > 0 ? r : r + 6.28;
  18. }
  19. public static intersects_rect(r1: IRect, r2: IRect): boolean {
  20. return Math.abs(r1.x - r2.x) < r1.half_width + r2.half_width && Math.abs(r1.y - r2.y) < r1.half_height + r2.half_height;
  21. }
  22. public static intersects_point_rect(p: IPos, r: IRect): boolean {
  23. return (p.x > r.x - r.width * 0.5) && (p.x < r.x + r.width * 0.5) && (p.y > r.y - r.height * 0.5) && (p.y < r.y + r.height * 0.5);
  24. }
  25. public static intersects_point_circle(p1: IPos, p2: IPos, r: number) {
  26. return p1.sub(p2).magSqr() < r * r;
  27. }
  28. public static intersects_circle(p1: IPos, r1: number, p2: IPos, r2: number) {
  29. return p1.sub(p2).mag() < r1 + r2;
  30. }
  31. public static intersects_circle_rect(p: IPos, r: number, rect: IRect) {
  32. const relative_x = p.x - rect.x;
  33. const relative_y = p.y - rect.y;
  34. const dx = Math.min(relative_x, rect.half_width);
  35. const dx1 = Math.max(dx, -rect.half_width);
  36. const dy = Math.min(relative_y, rect.half_height);
  37. const dy1 = Math.max(dy, -rect.half_height);
  38. return (dx1 - relative_x) * (dx1 - relative_x) + (dy1 - relative_y) * (dy1 - relative_y) <= r * r;
  39. }
  40. }