| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- // 碰撞检测工具函数
- // 来源: u-charts.ts
- /**
- * 坐标点接口
- */
- export interface Point {
- x: number;
- y: number;
- }
- /**
- * 碰撞对象接口
- */
- export interface CollisionObject {
- start: Point;
- end?: Point;
- width: number;
- height: number;
- center?: Point;
- area?: {
- start: Point;
- end: Point;
- width: number;
- height: number;
- };
- }
- /**
- * 工具函数集合接口
- */
- export interface Util {
- isCollision(obj1: CollisionObject, obj2: CollisionObject): boolean;
- }
- /**
- * 避免碰撞
- * 通过调整对象位置来避免与目标对象碰撞
- * @param obj - 待调整的碰撞对象
- * @param target - 目标碰撞对象数组
- * @returns 调整后的碰撞对象
- */
- export function avoidCollision(
- obj: CollisionObject,
- target?: CollisionObject[]
- ): CollisionObject {
- if (target) {
- // is collision test
- while (util.isCollision(obj, target[0] as CollisionObject)) {
- if (obj.start.x > 0) {
- obj.start.y--;
- } else if (obj.start.x < 0) {
- obj.start.y++;
- } else {
- if (obj.start.y > 0) {
- obj.start.y++;
- } else {
- obj.start.y--;
- }
- }
- }
- }
- return obj;
- }
- /**
- * 检测两个对象是否碰撞
- * @param obj1 - 第一个碰撞对象
- * @param obj2 - 第二个碰撞对象
- * @returns 是否碰撞
- */
- export function isCollision(obj1: CollisionObject, obj2: CollisionObject): boolean {
- obj1.end = {} as Point;
- obj1.end.x = obj1.start.x + obj1.width;
- obj1.end.y = obj1.start.y - obj1.height;
- obj2.end = {} as Point;
- obj2.end.x = obj2.start.x + obj2.width;
- obj2.end.y = obj2.start.y - obj2.height;
- 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;
- return !flag;
- }
- /**
- * 工具函数对象(保持与原 u-charts 兼容)
- */
- export const util: Util = {
- isCollision: isCollision
- };
|