BounceAnimation.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { _decorator, CCFloat, CCInteger, Component, easing, Enum, tween, Vec3 } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. enum AnimationType {
  4. BOUNCE = 0, //上下弹跳
  5. BREATHE = 1 //呼吸动画
  6. }
  7. @ccclass('BounceAnimation')
  8. export class BounceAnimation extends Component {
  9. @property({ type: Enum(AnimationType), tooltip: '动画类型' })
  10. animationType: AnimationType = AnimationType.BOUNCE;
  11. //弹跳动画参数
  12. @property({ type: CCInteger, tooltip: '缓动高度', visible() { return this.animationType === AnimationType.BOUNCE } })
  13. bounceHeight: number = 20;
  14. @property({ type: CCInteger, tooltip: '缓动时间(秒)', visible() { return this.animationType === AnimationType.BOUNCE } })
  15. duration: number = 0.5;
  16. //呼吸动画参数
  17. @property({ type: CCFloat, tooltip: '缩放幅度', visible() { return this.animationType === AnimationType.BREATHE } })
  18. scaleSize: number = 0.05;
  19. @property({ type: CCInteger, tooltip: '呼吸周期(秒)', visible() { return this.animationType === AnimationType.BREATHE } })
  20. breatheDuration: number = 1;
  21. private originalPosition: Vec3 = new Vec3();
  22. private originalScale: Vec3 = new Vec3(); // 新增原始缩放值记录
  23. start() {
  24. this.originalPosition = this.node.position.clone();
  25. this.originalScale = this.node.scale.clone(); // 记录原始缩放值
  26. this.startAnimation();
  27. }
  28. /**
  29. * 开始执行动画
  30. */
  31. public startAnimation() {
  32. const btn_play = this.node;
  33. if(this.animationType === AnimationType.BOUNCE) {
  34. tween(btn_play)
  35. .delay(Math.random())
  36. .to(this.duration,{position: new Vec3(this.originalPosition.x, this.originalPosition.y + this.bounceHeight, this.originalPosition.z)}, { easing: easing.linear }) // 向上缓动
  37. .to(this.duration,{position: new Vec3(this.originalPosition.x, this.originalPosition.y - this.bounceHeight, this.originalPosition.z)}, { easing: easing.linear }) // 向下缓动
  38. .to(this.duration,{position: new Vec3(this.originalPosition.x, this.originalPosition.y, this.originalPosition.z)}, { easing: easing.linear }) // 向下缓动
  39. .union()
  40. .repeatForever() // 无限循环
  41. .start(); // 启动动画
  42. } else if(this.animationType === AnimationType.BREATHE) {
  43. tween(btn_play)
  44. .sequence(
  45. tween().to(this.breatheDuration, {
  46. scale: new Vec3(
  47. this.originalScale.x + this.scaleSize,
  48. this.originalScale.y + this.scaleSize,
  49. 1
  50. )
  51. }),
  52. tween().to(this.breatheDuration, {
  53. scale: this.originalScale
  54. })
  55. )
  56. .repeatForever()
  57. .start();
  58. }
  59. }
  60. }