collision.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // 碰撞检测工具函数
  2. // 来源: u-charts.ts
  3. /**
  4. * 坐标点接口
  5. */
  6. export interface Point {
  7. x: number;
  8. y: number;
  9. }
  10. /**
  11. * 碰撞对象接口
  12. */
  13. export interface CollisionObject {
  14. start: Point;
  15. end?: Point;
  16. width: number;
  17. height: number;
  18. center?: Point;
  19. area?: {
  20. start: Point;
  21. end: Point;
  22. width: number;
  23. height: number;
  24. };
  25. }
  26. /**
  27. * 工具函数集合接口
  28. */
  29. export interface Util {
  30. isCollision(obj1: CollisionObject, obj2: CollisionObject): boolean;
  31. }
  32. /**
  33. * 避免碰撞
  34. * 通过调整对象位置来避免与目标对象碰撞
  35. * @param obj - 待调整的碰撞对象
  36. * @param target - 目标碰撞对象数组
  37. * @returns 调整后的碰撞对象
  38. */
  39. export function avoidCollision(
  40. obj: CollisionObject,
  41. target?: CollisionObject[]
  42. ): CollisionObject {
  43. if (target) {
  44. // is collision test
  45. while (util.isCollision(obj, target[0] as CollisionObject)) {
  46. if (obj.start.x > 0) {
  47. obj.start.y--;
  48. } else if (obj.start.x < 0) {
  49. obj.start.y++;
  50. } else {
  51. if (obj.start.y > 0) {
  52. obj.start.y++;
  53. } else {
  54. obj.start.y--;
  55. }
  56. }
  57. }
  58. }
  59. return obj;
  60. }
  61. /**
  62. * 检测两个对象是否碰撞
  63. * @param obj1 - 第一个碰撞对象
  64. * @param obj2 - 第二个碰撞对象
  65. * @returns 是否碰撞
  66. */
  67. export function isCollision(obj1: CollisionObject, obj2: CollisionObject): boolean {
  68. obj1.end = {} as Point;
  69. obj1.end.x = obj1.start.x + obj1.width;
  70. obj1.end.y = obj1.start.y - obj1.height;
  71. obj2.end = {} as Point;
  72. obj2.end.x = obj2.start.x + obj2.width;
  73. obj2.end.y = obj2.start.y - obj2.height;
  74. let flag = obj2.start.x > obj1.end.x || obj2.end.x < obj1.start.x || obj2.end.y > obj1.start.y || obj2.start.y < obj1.end.y;
  75. return !flag;
  76. }
  77. /**
  78. * 工具函数对象(保持与原 u-charts 兼容)
  79. */
  80. export const util: Util = {
  81. isCollision: isCollision
  82. };