Role.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. import { _decorator, Animation, AnimationClip, BoxCollider2D, Component, find, Node, PhysicsSystem2D, SpriteFrame, Vec2, Vec3 } from 'cc';
  2. import { RoleData } from '../../DataItem/ItemData';
  3. import { resMgr } from '../../Frames/ResourcesMgr';
  4. import { Bullet } from './GameScene/Bullet';
  5. import { LifeBar } from './GameScene/LifeBar';
  6. import { BulletPool } from './GameScene/BulletPool';
  7. import { GameInfo } from '../../GameInfo';
  8. const { ccclass, property } = _decorator;
  9. export enum RoleState {
  10. Attack,
  11. Move,
  12. Idle,
  13. Die
  14. }
  15. @ccclass('Role')
  16. export class Role extends Component {
  17. //基础数据
  18. hp: number = null; //血量
  19. atk: number = null; //攻击力
  20. atkLength: number = null; //攻击距离
  21. moveSpeed: number = null; //移速
  22. //向左-1 向右1
  23. direction: number = 1;
  24. //是否停下
  25. isStop: boolean = false;
  26. //攻击目标
  27. targetNode: Node = null;
  28. bulletLayer: Node | null = null;
  29. //战斗系统
  30. private _attackTimer: number = 0;
  31. private _attackInterval: number = 3;//攻击间隔
  32. private currentTarget: Role = null;//当前目标
  33. //子弹
  34. private _bullet: Node | null = null;
  35. private _bulletPool: BulletPool = null;
  36. //动画管理
  37. private _animations: Map<RoleState, string> = new Map();
  38. private _moveFrames: SpriteFrame[] = [];
  39. private _atkFrames: SpriteFrame[] = [];
  40. private _idleFrames: SpriteFrame[] = [];
  41. private _dieFrames: SpriteFrame[] = [];
  42. private _explodeframes: SpriteFrame[] = [];
  43. private _bulletFrames: SpriteFrame[] = [];
  44. private _animation: Animation = null;
  45. //角色数据
  46. private _roleData: RoleData = null;
  47. //状态管理
  48. _state: RoleState = null;
  49. init(name: string, pos: Vec3, roleDatas: RoleData[], dir?: number) {
  50. this._bulletPool = this.node.getComponent(BulletPool);
  51. this._bulletPool.init();
  52. this._animation = this.node.getComponent(Animation) || this.node.addComponent(Animation);
  53. this.direction = dir;
  54. let whichData: number = -1;
  55. for (let i = 0; i < roleDatas.length; i++) {
  56. if (!roleDatas[i]) {
  57. console.log(null)
  58. }
  59. if (roleDatas[i].imgName === name) {
  60. this._roleData = roleDatas[i];
  61. whichData = i;
  62. break;
  63. }
  64. }
  65. if (whichData != -1) {
  66. //获取move精灵帧
  67. this._getFrames(this._roleData.moveCount, this._moveFrames, this._roleData.moveImg, 1);
  68. //attack
  69. this._getFrames(this._roleData.atkCount, this._atkFrames, this._roleData.atkImg, 1);
  70. //idle
  71. this._getFrames(this._roleData.idleCount, this._idleFrames, this._roleData.idleImg, 1)
  72. //die
  73. this._getFrames(this._roleData.dieCount, this._dieFrames, this._roleData.dieImg, 1)
  74. //动画
  75. this._collectAni();
  76. //子弹精灵帧
  77. this._getFrames(this._roleData.bulletCount, this._bulletFrames, this._roleData.bulletImg, 1)
  78. //子弹爆炸精灵帧
  79. this._getFrames(this._roleData.bulletCount, this._explodeframes, this._roleData.bulletExplodeImg, 1)
  80. //设置基础数据
  81. this._setRoleData(this._roleData);
  82. this.playAnimation(RoleState.Move);
  83. }
  84. //位置
  85. this.node.setWorldPosition(pos);
  86. this.bulletLayer = find("Canvas/GameRoot/BulletLayer");
  87. //this._setupPhysics();
  88. }
  89. private _setRoleData(roleData: RoleData) {
  90. this.hp = roleData.hp;
  91. this.atk = roleData.atk;
  92. this.atkLength = roleData.atkLength;
  93. this.moveSpeed = roleData.moveSpeed;
  94. }
  95. // _setupPhysics() {
  96. // //确保有碰撞组件
  97. // const collider2D = this.getComponent(BoxCollider2D) || this.addComponent(BoxCollider2D);
  98. // collider2D.group = this._getCollisionGroup();
  99. // collider2D.apply();
  100. // }
  101. //获取精灵帧组
  102. /*
  103. count -> 精灵帧的数量
  104. imgType -> 图片类型(atk、walk、idle、die)
  105. startIdx -> 索引起始数
  106. */
  107. private _getFrames(count: number, frames: SpriteFrame[], imgType: string, startIdx: number) {
  108. for (let i = startIdx; i <= count; i++) {
  109. if (count > 1) {
  110. frames.push(resMgr.getSpriteFrame(imgType + ' (' + i + ')'));
  111. }
  112. else {
  113. frames.push(resMgr.getSpriteFrame(imgType + ' (1)'));
  114. }
  115. }
  116. }
  117. update(deltaTime: number) {
  118. if (this._state === RoleState.Die) return;
  119. if (!this.currentTarget) {
  120. this._handleMovement(deltaTime);
  121. this._detectEnemies();
  122. } else {
  123. this._handleAttack(deltaTime);
  124. }
  125. }
  126. //移动
  127. private _handleMovement(dt: number) {
  128. if (this._state !== RoleState.Move) return;
  129. let x = this.node.position.x;
  130. let y = this.node.position.y;
  131. let z = this.node.position.z;
  132. x = x + this.moveSpeed * this.direction * dt
  133. this.node.setPosition(x, y, z);
  134. }
  135. //寻敌
  136. private _detectEnemies() {
  137. if (!this.node.isValid) return;
  138. if(GameInfo.Instance.getIsGameOver()) return;
  139. //const startPos = new Vec2(this.node.position.x, this.node.position.y);
  140. const startPos = this.node.position.clone();
  141. const endPos = new Vec2((this.direction * this.atkLength) + this.node.position.x, this.node.position.y);
  142. const results = PhysicsSystem2D.instance.raycast(startPos, endPos);
  143. if (results?.length) {
  144. for (const result of results) {
  145. const target = result.collider.node.getComponent(Role);
  146. if (target && this._isValidTarget(target)) {
  147. this._setTarget(target);
  148. break;
  149. }
  150. }
  151. }
  152. }
  153. //设置攻击目标
  154. private _setTarget(target: Role) {
  155. this.currentTarget = target;
  156. this.playAnimation(RoleState.Attack);
  157. // 使得第一次update就会触发attackTimer >= attackInterval条件
  158. this._attackTimer = this._attackInterval - 0.001;
  159. //监听目标销毁事件
  160. target.node.once(Node.EventType.NODE_DESTROYED, this._onTargetDestroyed, this);
  161. }
  162. //攻击
  163. private _handleAttack(deltaTime: number) {
  164. //目标是否可以攻击
  165. if (!this._validateTarget()) {
  166. this._clearTarget();
  167. return;
  168. }
  169. /*
  170. //立即攻击判断
  171. if (this._attackTimer === 0) {
  172. this._createBullet();
  173. this._attackTimer += deltaTime;
  174. return;
  175. }
  176. //后续间隔攻击
  177. this._attackTimer += deltaTime;
  178. if (this._attackTimer >= this._attackInterval) {
  179. this._createBullet();
  180. this._attackTimer = 0; //重置计时器
  181. }
  182. */
  183. // this._createBullet();
  184. // this.schedule(() => {
  185. // this._createBullet();
  186. // }, this.attackInterval);
  187. }
  188. //目标是否可以攻击 hp大于0 并且 在攻击范围内 -> 可以攻击
  189. private _validateTarget(): boolean {
  190. return !!this.currentTarget?.node?.isValid &&
  191. this.currentTarget.node.getComponent(LifeBar)._curHp > 0 &&
  192. this._getDistanceToTarget() <= this.atkLength;
  193. }
  194. //攻击目标与自身的距离
  195. private _getDistanceToTarget(): number {
  196. return Math.abs(this.node.getWorldPosition().x - this.currentTarget.node.getWorldPosition().x);
  197. }
  198. //销毁目标
  199. private _onTargetDestroyed() {
  200. this._clearTarget();
  201. if (this.node === null) return;
  202. this._detectEnemies();//立即检测新目标
  203. }
  204. //清除目标 关闭触发事件 当前目标置空 设置移动状态 播放移动动画
  205. private _clearTarget() {
  206. this.currentTarget?.node.off(Node.EventType.NODE_DESTROYED, this._onTargetDestroyed, this);
  207. this.currentTarget = null;
  208. this.playAnimation(RoleState.Move);
  209. }
  210. //将各个动画存储起来
  211. private _collectAni() {
  212. // const moveAni: Animation = Tools.createAnimation(this._moveFrames, 8, this.node, AnimationClip.WrapMode.Loop)
  213. // this._animations.set(RoleState.Move, moveAni);
  214. // const atkAni: Animation = Tools.createAnimation(this._atkFrames, 8, this.node, AnimationClip.WrapMode.Loop)
  215. // this._animations.set(RoleState.Attack, atkAni);
  216. // const idleAni: Animation = Tools.createAnimation(this._idleFrames, 8, this.node, AnimationClip.WrapMode.Loop)
  217. // this._animations.set(RoleState.Idle, idleAni);
  218. // const dieAni: Animation = Tools.createAnimation(this._dieFrames, 8, this.node, AnimationClip.WrapMode.Normal)
  219. // this._animations.set(RoleState.Die, dieAni);
  220. this._createClip(RoleState.Move, this._moveFrames, 8);
  221. this._createClip(RoleState.Attack, this._atkFrames, 6);
  222. this._createClip(RoleState.Idle, this._idleFrames, 8);
  223. this._createClip(RoleState.Die, this._dieFrames, 9);
  224. }
  225. //创建动画剪辑 fps越大 速度越快
  226. private _createClip(state: RoleState, frames: SpriteFrame[], fps: number) {
  227. const clip: AnimationClip = AnimationClip.createWithSpriteFrames(frames, fps);
  228. clip.name = RoleState[state];
  229. clip.wrapMode = state === RoleState.Die ?
  230. AnimationClip.WrapMode.Normal :
  231. AnimationClip.WrapMode.Loop;
  232. if (clip.name === 'Attack') {
  233. clip.events = [{
  234. frame: 0.5,
  235. func: "onTriggered",
  236. params: [""] //向func传递的参数
  237. }]
  238. }
  239. this._animation.addClip(clip, clip.name);
  240. this._animations.set(state, clip.name);
  241. }
  242. onTriggered() {
  243. this._createBullet();
  244. }
  245. //设置动画
  246. public playAnimation(state: RoleState) {
  247. if (!this._animation || this._state === state) return;
  248. const clipName = this._animations.get(state);
  249. if (!clipName) return;
  250. //如果当前有动画正在播放,等待其完成后再切换
  251. if (this._animation.getState(String(this._state))?.isPlaying) {
  252. this._animation.once(Animation.EventType.FINISHED, () => {
  253. this._switchState(state, clipName);
  254. });
  255. } else {
  256. this._switchState(state, clipName);
  257. }
  258. }
  259. private _switchState(state: RoleState, clipName: string) {
  260. this._state = state;
  261. this._animation.stop();
  262. this._animation.play(clipName);
  263. if (state === RoleState.Die) {
  264. this.node.removeAllChildren();
  265. this._animation.once(Animation.EventType.FINISHED, () => {
  266. this.node.destroy();
  267. });
  268. }
  269. }
  270. private _createBullet() {
  271. const isEnemy = this.direction === -1;
  272. this._bullet = this._bulletPool.getBullet(isEnemy);
  273. this._bullet.parent = this.bulletLayer;
  274. this._bullet.setWorldPosition(this.node.getWorldPosition());
  275. const bulletTS = this._bullet.getComponent(Bullet);
  276. bulletTS.reset({
  277. pool: this._bulletPool,
  278. isEnemy: isEnemy,
  279. direction: this.direction,
  280. bulletFrames: this._bulletFrames,
  281. explodeFrames: this._explodeframes,
  282. targetNode: this.currentTarget.node,
  283. atk: this.atk,
  284. })
  285. }
  286. //要求子类实现的碰撞分组和阵营判断方法,确保不同阵营角色可以正确交互
  287. protected _getCollisionGroup(): number {
  288. throw new Error("Method not implemented");
  289. }
  290. protected _isValidTarget(target: Role): boolean {
  291. throw new Error("Method not implemented");
  292. }
  293. }