helper.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export class Helper {
  2. static readonly Epsilon = 1.401298E-45
  3. static readonly Infinity = 1 / 0
  4. static smoothStep(from: number, to: number, t: number) {
  5. t = this.clamp01(t)
  6. t = -2 * t * t * t + 3 * t * t
  7. return to * t + from * (1 - t)
  8. }
  9. static smoothDamp(current: number, target: number, currentVelocity: number, smoothTime: number, maxSpeed: number, deltaTime: number): { velocity: number, position: number } {
  10. smoothTime = Math.max(0.0001, smoothTime)
  11. var num = 2 / smoothTime
  12. var num2 = num * deltaTime
  13. var num3 = 1 / (1 + num2 + 0.48 * num2 * num2 + 0.235 * num2 * num2 * num2)
  14. var value = current - target
  15. var num4 = target
  16. var num5 = maxSpeed * smoothTime
  17. value = this.clamp(value, 0 - num5, num5)
  18. target = current - value
  19. var num6 = (currentVelocity + num * value) * deltaTime
  20. currentVelocity = (currentVelocity - num * num6) * num3
  21. var num7 = target + (value + num6) * num3
  22. if (num4 - current > 0 == num7 > num4) {
  23. num7 = num4
  24. currentVelocity = (num7 - num4) / deltaTime
  25. }
  26. return { velocity: currentVelocity, position: num7 }
  27. }
  28. static clamp01(value: number) {
  29. return this.clamp(value, 0, 1)
  30. }
  31. static clamp(num, min = 0, max = 1) {
  32. return Math.min(Math.max(num, min), max)
  33. }
  34. static sign(f) {
  35. return (f >= 0) ? 1 : (-1)
  36. }
  37. static lerp(a: number, b: number, t: number) {
  38. return a + (b - a) * this.clamp01(t)
  39. }
  40. static approximately(a: number, b: number) {
  41. return Math.abs(b - a) < Math.max(100E-6 * Math.max(Math.abs(a), Math.abs(b)), this.Epsilon * 8)
  42. }
  43. static round(value, n) {
  44. return Math.round(value * Math.pow(10, n)) / Math.pow(10, n)
  45. }
  46. static pingpang(v: number) {
  47. var value = v
  48. value = Math.abs(v)
  49. var integer = Math.trunc(value)
  50. if (integer % 2 == 0) {
  51. value = value - integer
  52. } else {
  53. value = (1 - (value - integer))
  54. }
  55. return value
  56. }
  57. static isNumber(value: any) {
  58. return typeof value == "number" && !isNaN(value)
  59. }
  60. static progress(start: number, end: number, current: number, t: number) {
  61. return current = start + (end - start) * t
  62. }
  63. static getGuid() {
  64. var d = new Date().getTime()
  65. if (window.performance && typeof window.performance.now === "function") {
  66. d += performance.now()
  67. }
  68. var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  69. var r = (d + Math.random() * 16) % 16 | 0; // d是随机种子
  70. d = Math.floor(d / 16)
  71. return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  72. })
  73. return uuid
  74. }
  75. }