DBRender.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { _decorator, Component, dragonBones, v3 } from 'cc';
  2. import { DBData } from './DBData';
  3. const { ccclass, requireComponent, property } = _decorator;
  4. /**
  5. * @description 龙骨动画渲染器
  6. * @author 王锡铜、袁浩
  7. */
  8. @ccclass('DBRender')
  9. @requireComponent(DBData)
  10. export class DBRender extends Component {
  11. @property({ tooltip: "动态骨骼名称" })
  12. public dynamicBoneName: string = "chest";
  13. @property({ tooltip: "淡入时间(秒)" })
  14. public fadeInTime: number = 0.05;
  15. @property({ tooltip: "播放次数。 [-1: 使用动画数据默认值, 0: 无限循环播放, [1~N]: 循环播放 N 次]" })
  16. public playTimes: number = 0;
  17. private DBDisplay: dragonBones.ArmatureDisplay;
  18. private armature: dragonBones.Armature;
  19. private dbData: DBData;
  20. private _nowAnimation: string = "";
  21. /**可能需要动态变化的骨骼(例如头部需要看向敌人) */
  22. private _dynamicBone: dragonBones.Bone = null;
  23. onLoad() {
  24. this.DBDisplay = this.getComponent(dragonBones.ArmatureDisplay);
  25. if (!this.DBDisplay) {
  26. console.error(this.node.name + "引用了DBRender组价,但是没有找到dragonBones.ArmatureDisplay组件!!by:DBRender");
  27. return;
  28. }
  29. this.armature = this.DBDisplay.armature();
  30. this.dbData = this.getComponent(DBData);
  31. this._dynamicBone = this.armature.getBone(this.dynamicBoneName);
  32. // let replaceSolt = this.armature.getSlot("weapon_l");
  33. // let targetSlotName = "weapon_r";
  34. // let displayName = this.replaceArmatureDisplay.armature().getSlot(targetSlotName).display.displayData.name;
  35. // let factory = dragonBones.CCFactory.getInstance();
  36. // factory.replaceSlotDisplay(this.replaceArmatureDisplay.getArmatureKey(), this.replaceArmatureDisplay.armatureName, targetSlotName, displayName, replaceSolt);
  37. }
  38. update() {
  39. if (this._nowAnimation != this.dbData.curAnimation) {
  40. this._nowAnimation = this.dbData.curAnimation;
  41. this.armature.animation.fadeIn(this._nowAnimation, this.fadeInTime, this.playTimes);
  42. }
  43. if (this.node.scale.x != this.dbData.direction) this.node.scale = v3(this.dbData.direction, this.node.scale.y, this.node.scale.z);
  44. (this.dbData.targetPos && this._dynamicBone) && this.lookAt();
  45. }
  46. private lookAt(): void {
  47. let radian = 0;
  48. let offsetY = this._dynamicBone.global.y * this.node.getScale().y;
  49. if (this.dbData.direction > 0) {
  50. radian = Math.atan2(this.dbData.targetPos.y - this.node.position.y - offsetY, this.dbData.targetPos.x - this.node.position.x);
  51. } else {
  52. radian = Math.PI - Math.atan2(this.dbData.targetPos.y - this.node.position.y - offsetY, this.dbData.targetPos.x - this.node.position.x);
  53. if (radian > Math.PI) {
  54. radian -= Math.PI * 2;
  55. }
  56. }
  57. this._dynamicBone.offset.rotation = radian;
  58. }
  59. }