Tree.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { _decorator, Component, Node, Animation} from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('Tree')
  4. export class Tree extends Component {
  5. public animationComp: Animation | null = null;
  6. start() {
  7. // 获取当前节点上的 Animation 组件
  8. this.animationComp = this.node.getComponent(Animation);
  9. if (!this.animationComp) {
  10. console.error("当前节点没有 Animation 组件!");
  11. return;
  12. }
  13. else
  14. {
  15. console.log("Animation Loaded");
  16. }
  17. }
  18. update(deltaTime: number) {
  19. }
  20. public shakeAni()
  21. {
  22. // 示例:根据动画名称获取剪辑并播放
  23. const targetClipName = "Shake"; // 替换为你的动画剪辑名称
  24. const targetClip = this.getClipByName(targetClipName);
  25. if (targetClip) {
  26. console.log(`Found anim clip:${targetClipName},start play`);
  27. this.animationComp.play(targetClipName); // 直接用名称播放,或用剪辑实例播放
  28. // 也可以通过剪辑实例获取更多信息,例如时长
  29. console.log(`Duration:${targetClip.duration} second`);
  30. } else {
  31. console.error(`Not found ${targetClipName} ani clip!`);
  32. }
  33. }
  34. /**
  35. * 根据动画剪辑名称,从当前节点的 Animation 组件中查找剪辑
  36. * @param clipName 动画剪辑的名称(区分大小写)
  37. * @returns 找到的 AnimationClip 实例,或 null
  38. */
  39. private getClipByName(clipName: string): AnimationClip | null {
  40. if (!this.animationComp) return null;
  41. // 遍历 Animation 组件的 clips 数组
  42. for (const clip of this.animationComp.clips) {
  43. if (clip.name === clipName) {
  44. return clip;
  45. }
  46. }
  47. return null;
  48. }
  49. }