gi.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { Vec2,Node, v2 } from "cc";
  2. export namespace gi {
  3. //让node振动repeat次,振幅amplitude(水平、垂直两方向),频率frequency(ms),time < 0无限振动,time = 0停止振动
  4. //例如:gi.shake(node,5,cc.v2(20,0))振动5次,gi.shake(node,-1)振动无限次,gi.shake(node,0)停止振动
  5. export function shake(node: Node, repeat: number, amplitude?: any, frequency?: number) {
  6. let x = node.position.x;
  7. let y = node.position.y
  8. if (node['amplitude']) {
  9. x -= node['amplitude'].x;
  10. y -= node['amplitude'].y;
  11. node.setPosition(x,y);
  12. clearInterval(node['shakeHandle']);
  13. }
  14. if (repeat === 0) {
  15. delete node['shakeHandle'];
  16. delete node['amplitude'];
  17. delete node['frequency'];
  18. return;
  19. }
  20. repeat = ~~repeat;
  21. if (amplitude) {
  22. node['amplitude'] = amplitude;
  23. } else if (node['amplitude']) {
  24. node['amplitude'].x = -node['amplitude'].x;
  25. node['amplitude'].y = -node['amplitude'].y;
  26. } else return;
  27. node['frequency'] = frequency !== undefined ? Math.max(frequency, 10) : node['frequency'] ?? 50;
  28. x += node['amplitude'].x;
  29. y += node['amplitude'].y;
  30. node.setPosition(x,y);
  31. let step = v2();
  32. if (repeat > 0) {
  33. repeat = Math.max(repeat - 1, 1);
  34. step = v2(-node['amplitude'].x / repeat, -node['amplitude'].y / repeat);
  35. }
  36. node['shakeHandle'] = setInterval(() => {
  37. x -= node['amplitude'].x;
  38. y -= node['amplitude'].y;
  39. node.setPosition(x,y);
  40. if (--repeat === 0) {
  41. clearInterval(node['shakeHandle']);
  42. delete node['shakeHandle'];
  43. delete node['amplitude'];
  44. delete node['frequency'];
  45. return;
  46. }
  47. node['amplitude'].x = -node['amplitude'].x - step.x;
  48. x += node['amplitude'].x;
  49. step.x = -step.x;
  50. node['amplitude'].y = -node['amplitude'].y - step.y;
  51. y += node['amplitude'].y;
  52. step.y = -step.y;
  53. node.setPosition(x,y);
  54. }, node['frequency']);
  55. }
  56. }
  57. window['gi'] = gi;