MathUtil.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import { misc, Rect, Vec2, Vec3 } from "cc";
  2. /** 用于计算的临时工 */
  3. const tempVec3 = new Vec3();
  4. /** 用于弧度转角度 */
  5. const rad2Deg = 180 / Math.PI;
  6. /** 用于角度转弧度 */
  7. const deg2Rad = Math.PI / 180;
  8. export class MathUtil {
  9. static readonly zore: Vec2 = new Vec2(1, 0);
  10. /**
  11. * 用于弧度转角度
  12. */
  13. public static get rad2Deg() {
  14. return rad2Deg;
  15. }
  16. /**
  17. * 用于角度转弧度
  18. */
  19. public static get deg2Rad() {
  20. return deg2Rad;
  21. }
  22. /**
  23. * 弧度转角度
  24. * @param radians
  25. */
  26. public static radiansToDegrees(radians: number) {
  27. return radians * rad2Deg;
  28. }
  29. /**
  30. * 角度转弧度
  31. * @param degree
  32. */
  33. public static degreesToRadians(degree: number) {
  34. return degree * deg2Rad;
  35. }
  36. /**限制数大小 */
  37. static Clamp(value: number, min: number, max: number): number {
  38. if (value < min) {
  39. value = min;
  40. } else if (value > max) {
  41. value = max;
  42. }
  43. return value;
  44. }
  45. static Clamp01(value: number): number {
  46. return this.Clamp(value, 0, 1);
  47. }
  48. static PingPong(t: number, length: number): number {
  49. t = this.Repeat(t, length * 2)
  50. return length - Math.abs(t - length)
  51. }
  52. static Repeat(t: number, length: number): number {
  53. return t - (Math.floor(t / length) * length)
  54. }
  55. static Round(num: number): number {
  56. return Math.floor(num + 0.5)
  57. }
  58. static Sign(num: number): number {
  59. if (num > 0) {
  60. num = 1
  61. } else if (num < 0) {
  62. num = -1
  63. } else {
  64. num = 0;
  65. }
  66. return num;
  67. }
  68. static InverseLerp(from: number, to: number, value: number): number {
  69. if (from < to) {
  70. if (value < from) return 0;
  71. if (value > to) return 1;
  72. value = value - from
  73. value = value / (to - from)
  74. return value;
  75. }
  76. if (from <= to) return 0;
  77. if (value < to) return 1;
  78. if (value > from) return 0;
  79. return 1 - ((value - to) / (from - to));
  80. }
  81. static Lerp(from: number, to: number, t: number): number {
  82. return from + (to - from) * this.Clamp01(t);
  83. }
  84. static LerpUnclamped(a: number, b: number, t: number): number {
  85. return a + (b - a) * t;
  86. }
  87. static DeltaAngle(current: number, target: number): number {
  88. let num = this.Repeat(target - current, 360);
  89. if (num > 180) num = num - 360;
  90. return num;
  91. }
  92. static LerpAngle(a: number, b: number, t: number): number {
  93. let num = this.Repeat(b - a, 360)
  94. if (num > 180) num = num - 360;
  95. return a + num * this.Clamp01(t)
  96. }
  97. /**
  98. * 在最小值和最大值之间进行插值,并在极限处进行平滑处理
  99. * @param from
  100. * @param to
  101. * @param t
  102. */
  103. public static smoothStep(from: number, to: number, t: number) {
  104. t = this.Clamp01(t);
  105. t = (-2.0 * t * t * t + 3.0 * t * t);
  106. return (to * t + from * (1.0 - t));
  107. }
  108. /**
  109. * 平滑控制
  110. * @param current 当前值
  111. * @param target 目标值
  112. * @param currentVelocity 当前速度
  113. * @param smoothTime 平滑时间
  114. * @param maxSpeed 最大速度
  115. * @param deltaTime 时间增量
  116. */
  117. public static smoothDamp(current: number, target: number, currentVelocity: number, smoothTime: number, deltaTime: number, maxSpeed: number = Number.POSITIVE_INFINITY) {
  118. smoothTime = Math.max(0.0001, smoothTime);
  119. const num1 = 2 / smoothTime;
  120. const num2 = num1 * deltaTime;
  121. const num3 = (1 / (1 + num2 + 0.47999998927116394 * num2 * num2 + 0.23499999940395355 * num2 * num2 * num2));
  122. const num4 = current - target;
  123. const num5 = target;
  124. const max = maxSpeed * smoothTime;
  125. const num6 = this.Clamp(num4, -max, max);
  126. target = current - num6;
  127. const num7 = (currentVelocity + num1 * num6) * deltaTime;
  128. let velocity = (currentVelocity - num1 * num7) * num3;
  129. let num8 = target + (num6 + num7) * num3;
  130. if ((num5 - current > 0) === (num8 > num5)) {
  131. num8 = num5;
  132. velocity = (num8 - num5) / deltaTime;
  133. }
  134. return {
  135. value: num8,
  136. velocity: velocity,
  137. };
  138. }
  139. /**
  140. * 垂直于原向量V的单位向量
  141. * @param v 一个向量
  142. * @returns
  143. */
  144. static getPerpendicular(v: Vec2): Vec2 {
  145. const perpendicular = new Vec2(-v.y, v.x); //计算垂直向量
  146. const normal = perpendicular.normalize();//归一化
  147. return normal;
  148. }
  149. //角度转向量
  150. static angleToVector(angle: number): Vec2 {
  151. return this.zore.clone().rotate(-misc.degreesToRadians(angle));
  152. }
  153. // 向量转角度
  154. static vectorToAngle(dir: Vec2): number {
  155. return -misc.radiansToDegrees(dir.signAngle(this.zore));
  156. }
  157. // 角度转向量
  158. static angle_to_vector(angle: number): Vec2 {
  159. // tan = sin / cos
  160. // 将传入的角度转为弧度
  161. let radian = this.degreesToRadians(angle);
  162. // 算出cos,sin和tan
  163. let cos = Math.cos(radian);// 邻边 / 斜边
  164. let sin = Math.sin(radian);// 对边 / 斜边
  165. let tan = sin / cos;// 对边 / 邻边
  166. // 结合在一起并归一化
  167. let vec = new Vec2(cos, sin).normalize();
  168. // 返回向量
  169. return (vec);
  170. }
  171. // !!!!!!!!其实使用Math.atan2求出弧度再转角度一样的效果
  172. // 向量转角度
  173. static vector_to_angle(dir: Vec2): number {
  174. // 将传入的向量归一化 一般已经归一化了
  175. //dir.normalize();
  176. // 计算出目标角度的弧度
  177. let radian = dir.signAngle(this.zore);
  178. // 把弧度计算成角度
  179. let angle = -this.radiansToDegrees(radian);
  180. // 返回角度
  181. return (angle);
  182. }
  183. //向量转弧度
  184. static vector_to_radian(dir: Vec2): number {
  185. return dir.signAngle(this.zore);
  186. }
  187. /// <summary>
  188. /// 旋转向量,使其方向改变,大小不变
  189. /// </summary>
  190. /// <param name="v">需要旋转的向量</param>
  191. /// <param name="angle">旋转的角度</param>
  192. /// <returns>旋转后的向量</returns>
  193. static RotationMatrix(x: number, y: number, angle: number): Vec2 {
  194. let radian = this.degreesToRadians(angle);
  195. let sin = Math.sin(radian);
  196. var cos = Math.cos(radian);
  197. var newX = x * cos + y * sin;
  198. var newY = x * -sin + y * cos;
  199. //var newX = x * cos - y * sin;
  200. //var newY = x * sin + y * cos;
  201. return new Vec2(newX, newY);
  202. }
  203. static RotationDir(dir: Vec2, angle: number): Vec2 {
  204. let radian = this.radiansToDegrees(angle);
  205. let sin = Math.sin(radian);
  206. var cos = Math.cos(radian);
  207. var newX = dir.x * cos + dir.y * sin;
  208. var newY = dir.x * -sin + dir.y * cos;
  209. dir.x = newX;
  210. dir.y = newY;
  211. return dir;
  212. }
  213. //扇形范围
  214. public static CheckInView(mPos: Vec2, faceDir: Vec2, tPos: Vec2, dis: number, angle: number): boolean {
  215. //let t = tPos.subtract(mPos);
  216. //let distance = Vec2.lengthSqr(t);
  217. //if(distance<dis*dis)
  218. let distance = Vec2.distance(mPos, tPos);
  219. if (distance < dis) {
  220. if (angle >= 360) return true;
  221. let dir = tPos.subtract(mPos).normalize();
  222. let ang = this.radiansToDegrees(Vec2.angle(faceDir, dir));
  223. if (ang <= angle * 0.5) {
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. //检测点是否在一个凸四边形内
  230. public static InConvexQuad(point: Vec2, pointA: Vec2, pointB: Vec2, pointC: Vec2, pointD: Vec2): boolean {
  231. let vec1: Vec2, vec2: Vec2;
  232. vec1.x = pointB.x - pointA.x;
  233. vec1.y = pointB.y - pointA.y;
  234. vec2.x = point.x - pointA.x;
  235. vec2.y = point.y - pointA.y;
  236. if (this.cross2DPoint(vec2.x, vec2.y, vec1.x, vec1.y)) return false;
  237. vec1.x = pointC.x - pointB.x;
  238. vec1.y = pointC.y - pointB.y;
  239. vec2.x = point.x - pointB.x;
  240. vec2.y = point.y - pointB.y;
  241. if (this.cross2DPoint(vec2.x, vec2.y, vec1.x, vec1.y)) return false;
  242. vec1.x = pointD.x - pointC.x;
  243. vec1.y = pointD.y - pointC.y;
  244. vec2.x = point.x - pointC.x;
  245. vec2.y = point.y - pointC.y;
  246. if (this.cross2DPoint(vec2.x, vec2.y, vec1.x, vec1.y)) return false;
  247. vec1.x = pointA.x - pointD.x;
  248. vec1.y = pointA.y - pointD.y;
  249. vec2.x = point.x - pointD.x;
  250. vec2.y = point.y - pointD.y;
  251. if (this.cross2DPoint(vec2.x, vec2.y, vec1.x, vec1.y)) return false;
  252. return true;
  253. }
  254. /**等同于Vec2.cross */
  255. public static cross2DPoint(x1: number, y1: number, x2: number, y2: number): number {
  256. return x1 * y2 - x2 * y1;
  257. }
  258. /**检测两个2D包围盒(xy为中心点 wh分别为x轴半径宽 y轴半径宽) 是否相交*/
  259. public static AABBAABB2D(pointX1: number, pointY1: number, w1: number, h1: number,
  260. pointX2: number, pointY2: number, w2: number, h2: number): boolean {
  261. if (Math.abs(pointX1 - pointX2) > (w1 + w2)) return false;
  262. if (Math.abs(pointY1 - pointY2) > (h1 + h2)) return false;
  263. return true;
  264. }
  265. /**检测两个3D包围盒 是否相交*/
  266. public static AABBAABB3D(pointX1: number, pointY1: number, pointZ1: number, w1: number, h1: number, t1: number,
  267. pointX2: number, pointY2: number, pointZ2: number, w2: number, h2: number, t2: number): boolean {
  268. if (Math.abs(pointX1 - pointX2) > (w1 + w2)) return false;
  269. if (Math.abs(pointY1 - pointY2) > (h1 + h2)) return false;
  270. if (Math.abs(pointZ1 - pointZ2) > (t1 + t2)) return false;
  271. return true;
  272. }
  273. /**点与点*/
  274. public static pointPoint(point1: Vec2, point2: Vec2): boolean {
  275. if (point1.x == point2.x && point1.y == point2.y) {
  276. return true;
  277. }
  278. return false;
  279. }
  280. //判断点是否在线上,在返回1,不在返回0
  281. public static onSegement(Q: Vec2, p1: Vec2, p2: Vec2): boolean {
  282. let maxx: number, minx: number, maxy: number, miny: number;
  283. maxx = p1.x > p2.x ? p1.x : p2.x; //矩形的右边长
  284. minx = p1.x > p2.x ? p2.x : p1.x; //矩形的左边长
  285. maxy = p1.y > p2.y ? p1.y : p2.y; //矩形的上边长
  286. miny = p1.y > p2.y ? p2.y : p1.y; //矩形的下边长
  287. if (((Q.x - p1.x) * (p2.y - p1.y) == (p2.x - p1.x) * (Q.y - p1.y)) && (Q.x >= minx && Q.x <= maxx) && (Q.y >= miny && Q.y <= maxy)) {
  288. return true;
  289. }
  290. return false;
  291. }
  292. //点与圆的碰撞
  293. //通过计算点到圆心的距离与半径比较判断circle(由中心点和半径构成)
  294. public static pointInCircle(point: Vec2, center: Vec2, radius: number): boolean {
  295. return Vec2.squaredDistance(point, center) <= radius * radius;
  296. }
  297. //点与矩形的碰撞
  298. //通过判断点坐标是否在矩形四个顶点围成的坐标区域内
  299. public static pointInRect(point: Vec2, rect: Rect): boolean {
  300. if (point.x >= rect.x
  301. && point.x <= rect.x + rect.width
  302. && point.y >= rect.y
  303. && point.y <= rect.y + rect.height) return true;
  304. return false
  305. }
  306. //线与矩形的碰撞
  307. public static lineInRect(p1: Vec2, p2: Vec2, rect: Rect): boolean {
  308. let height = p1.y - p2.y;
  309. let width = p2.x - p1.x;
  310. let c = p1.x * p2.y - p2.x - p1.y;//计算叉乘
  311. if ((height * rect.xMin + width * rect.yMin + c >= 0 && height * rect.xMax + width * rect.yMax + c <= 0)
  312. || (height * rect.xMin + width * rect.yMin + c <= 0 && height * rect.xMax + width * rect.yMax + c >= 0)
  313. || (height * rect.xMin + width * rect.yMax + c >= 0 && height * rect.xMax + width * rect.yMin + c <= 0)
  314. || (height * rect.xMin + width * rect.yMax + c <= 0 && height * rect.xMax + width * rect.yMin + c >= 0)
  315. ) {
  316. if ((p1.x < rect.xMin && p2.x < rect.xMin)
  317. || (p1.x > rect.xMax && p2.x > rect.xMax)
  318. || (p1.y > rect.yMin && p2.y > rect.yMin)
  319. || (p1.y < rect.yMax && p2.y < rect.yMax)
  320. ) {
  321. return false;
  322. } else {
  323. return true;
  324. }
  325. } else {
  326. return false
  327. }
  328. }
  329. //两个rect是否相交
  330. public static collisionRectWithRect(rect1: Rect, rect2: Rect): boolean {
  331. //计算相交部分的矩形
  332. //左下角坐标:( lx , ly ) //右上角坐标:( rx , ry )
  333. let lx = Math.max(rect1.xMin, rect2.xMin);
  334. let ly = Math.max(rect1.yMin, rect2.yMin);
  335. let rx = Math.min(rect1.xMax, rect2.xMax);
  336. let ry = Math.min(rect1.yMax, rect2.yMax);
  337. //判断是否能构成小矩形
  338. if (lx > rx || ly > ry) return false; //矩形不相交
  339. return true; //发生碰撞
  340. }
  341. //圆与矩形是否相交
  342. public static collisionRectWithCircle(rect: Rect, p: Vec2, r: number): boolean {
  343. //获取矩形信息
  344. //左下角坐标:( lx , ly )
  345. //右上角坐标:( rx , ry )
  346. let lx = rect.xMin;
  347. let ly = rect.yMin;
  348. let rx = rect.xMax;
  349. let ry = rect.yMax;
  350. //计算圆心到四个顶点的距离
  351. let d1 = Vec2.distance(p, new Vec2(lx, ly));
  352. let d2 = Vec2.distance(p, new Vec2(lx, ry));
  353. let d3 = Vec2.distance(p, new Vec2(rx, ly));
  354. let d4 = Vec2.distance(p, new Vec2(rx, ry));
  355. //判断是否碰撞//判断距离是否小于半径
  356. if (d1 < r || d2 < r || d3 < r || d4 < r) return true;
  357. //是否在圆角矩形的,横向矩形内
  358. if (p.x > (lx - r) && p.x < (rx + r) && p.y > ly && p.y < ry) return true;
  359. //是否在圆角矩形的,纵向矩形内
  360. if (p.x > lx && p.x < rx && p.y > (ly - r) && p.y < (ry + r)) return true;
  361. //不发生碰撞
  362. return false;
  363. }
  364. /**
  365. * 计算向量在指定平面上的投影
  366. * @param vector 被投影的向量
  367. * @param planeNormal 平面法线
  368. */
  369. public static projectOnPlane(vector: Vec3, planeNormal: Vec3) {
  370. // 也可以直接用 Vec3 自带的平面投影函数
  371. // return Vec3.projectOnPlane(new Vec3, targetDir, planeNormal);
  372. // 使用点乘计算方向矢量在平面法线上的投影长度
  373. const projectionLength = Vec3.dot(vector, planeNormal);
  374. // 平面法线与长度相乘得到方向矢量在平面法线上的投影矢量
  375. const vectorOnPlane = tempVec3.set(planeNormal).multiplyScalar(projectionLength);
  376. // 方向矢量减去其在平面法线上的投影矢量即是其在平面上的投影矢量
  377. return Vec3.subtract(new Vec3, vector, vectorOnPlane);
  378. }
  379. /**
  380. * 计算两个向量基于指定轴的夹角(逆时针方向为正方向,值范围 -180 ~ 180)
  381. * @param a 向量 a
  382. * @param b 向量 b
  383. * @param axis 参照轴向量(请确保是归一化的)
  384. */
  385. public static signedAngle(a: Vec3, b: Vec3, axis: Vec3) {
  386. // 将向量 a 和 b 分别投影到以 axis 为法线的平面上
  387. const aOnAxisPlane = this.projectOnPlane(a, axis);
  388. const bOnAxisPlane = this.projectOnPlane(b, axis);
  389. // 归一化处理
  390. const aNormalized = aOnAxisPlane.normalize();
  391. const bNormalized = bOnAxisPlane.normalize();
  392. // 求出同时垂直于 a 和 b 的法向量
  393. const abNormal = Vec3.cross(new Vec3, aNormalized, bNormalized).normalize();
  394. // 将法向量到 axis 上的投影长度
  395. // 若投影长度为正值(+1)则表示法向量与 axis 同向(向量叉乘的右手法则)
  396. const sign = Vec3.dot(abNormal, axis);
  397. // 求出向量 a 和 b 的夹角
  398. const radian = Math.acos(Vec3.dot(aNormalized, bNormalized));
  399. // 混合在一起!
  400. return radian * sign * this.rad2Deg;
  401. }
  402. //获取某点到某点的Y轴方向
  403. static GetYDir(from: Vec3, to: Vec3) {
  404. let dir = to.subtract(from);
  405. dir.y = from.y
  406. return dir.normalize();
  407. }
  408. //向量绕Y轴转一个角度
  409. static RotateAroundAxisY(dir: Vec3, angle: number): Vec3 {
  410. dir = dir.clone();
  411. let rad = this.degreesToRadians(angle);
  412. let cos = Math.cos(rad);
  413. let sin = Math.sin(rad);
  414. dir.x = dir.x * cos + dir.z * sin;
  415. dir.z = dir.x * (-sin) + dir.z * cos;
  416. return dir;
  417. }
  418. //将一个向量围绕X轴旋转angle个角度
  419. static RotateAroundAxisX(dir: Vec3, angle: number): Vec3 {
  420. dir = dir.clone();
  421. let rad = this.degreesToRadians(angle);
  422. let cos = Math.cos(rad);
  423. let sin = Math.sin(rad);
  424. dir.y = dir.y * cos - dir.z * sin;
  425. dir.z = dir.y * sin + dir.z * cos;
  426. return dir;
  427. }
  428. //将一个向量围绕Z轴旋转angle个角度
  429. static RotateAroundAxisZ(dir: Vec3, angle: number): Vec3 {
  430. dir = dir.clone();
  431. let rad = this.degreesToRadians(angle);
  432. let cos = Math.cos(rad);
  433. let sin = Math.sin(rad);
  434. dir.x = dir.x * cos - dir.y * sin;
  435. dir.y = dir.x * sin + dir.y * cos;
  436. return dir;
  437. }
  438. //线段是否与矩形相交
  439. static LineRectIntersection(lineStartPoint: Vec2, lineEndPoint: Vec2, rectMinX: number, rectMaxX: number, rectMinY: number, rectMaxY: number): boolean {//针对四种不同的情况,进行碰撞检测
  440. let minXLinePoint = lineEndPoint;
  441. if (lineStartPoint.x <= lineEndPoint.x) {
  442. minXLinePoint = lineStartPoint;
  443. }
  444. let maxXLinePoint = lineStartPoint;
  445. if (lineStartPoint.x <= lineEndPoint.x) {
  446. maxXLinePoint = lineEndPoint;
  447. }
  448. let minYLinePoint = lineEndPoint;
  449. if (lineStartPoint.y <= lineEndPoint.y) {
  450. minYLinePoint = lineStartPoint;
  451. }
  452. let maxYLinePoint = lineStartPoint;
  453. if (lineStartPoint.y <= lineEndPoint.y) {
  454. maxYLinePoint = lineEndPoint;
  455. }
  456. if (minXLinePoint.x <= rectMinX && rectMinX <= maxXLinePoint.x) {
  457. let m = (maxXLinePoint.y - minXLinePoint.y) / (maxXLinePoint.x - minXLinePoint.x);
  458. let intersectionY = ((rectMinX - minXLinePoint.x) * m) + minXLinePoint.y;
  459. if (minYLinePoint.y <= intersectionY && intersectionY <= maxYLinePoint.y && rectMinY <= intersectionY && intersectionY <= rectMaxY) {
  460. return true;//new Vec2(rectMinX, intersectionY)
  461. }
  462. }
  463. if (minXLinePoint.x <= rectMaxX && rectMaxX <= maxXLinePoint.x) {
  464. let m = (maxXLinePoint.y - minXLinePoint.y) / (maxXLinePoint.x - minXLinePoint.x);
  465. let intersectionY = ((rectMaxX - minXLinePoint.x) * m) + minXLinePoint.y;
  466. if (minYLinePoint.y <= intersectionY && intersectionY <= maxYLinePoint.y && rectMinY <= intersectionY && intersectionY <= rectMaxY) {
  467. return true;//new Vec2(rectMaxX, intersectionY)
  468. }
  469. }
  470. if (minYLinePoint.y <= rectMaxY && rectMaxY <= maxYLinePoint.y) {
  471. let rm = (maxYLinePoint.x - minYLinePoint.x) / (maxYLinePoint.y - minYLinePoint.y);
  472. let intersectionX = ((rectMaxY - minYLinePoint.y) * rm) + minYLinePoint.x;
  473. if (minXLinePoint.x <= intersectionX && intersectionX <= maxXLinePoint.x && rectMinX <= intersectionX && intersectionX <= rectMaxX) {
  474. return true;//new Vec2(intersectionX, rectMaxY)
  475. }
  476. }
  477. if (minYLinePoint.y <= rectMinY && rectMinY <= maxYLinePoint.y) {
  478. let rm = (maxYLinePoint.x - minYLinePoint.x) / (maxYLinePoint.y - minYLinePoint.y);
  479. let intersectionX = ((rectMinY - minYLinePoint.y) * rm) + minYLinePoint.x;
  480. if (minXLinePoint.x <= intersectionX && intersectionX <= maxXLinePoint.x && rectMinX <= intersectionX && intersectionX <= rectMaxX) {
  481. return true;//new Vec2(intersectionX, rectMinY)
  482. }
  483. }
  484. return false
  485. }
  486. }