Role.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import { _decorator, Animation, AnimationClip, 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. }
  88. private _setRoleData(roleData: RoleData) {
  89. this.hp = roleData.hp;
  90. this.atk = roleData.atk;
  91. this.atkLength = roleData.atkLength;
  92. this.moveSpeed = roleData.moveSpeed;
  93. }
  94. //获取精灵帧组
  95. /*
  96. count -> 精灵帧的数量
  97. imgType -> 图片类型(atk、walk、idle、die)
  98. startIdx -> 索引起始数
  99. */
  100. private _getFrames(count: number, frames: SpriteFrame[], imgType: string, startIdx: number) {
  101. for (let i = startIdx; i <= count; i++) {
  102. if (count > 1) {
  103. frames.push(resMgr.getSpriteFrame(imgType + ' (' + i + ')'));
  104. }
  105. else {
  106. frames.push(resMgr.getSpriteFrame(imgType + ' (1)'));
  107. }
  108. }
  109. }
  110. update(deltaTime: number) {
  111. if (this._state === RoleState.Die) return;
  112. //只有游戏结束才能执行后续操作
  113. if(GameInfo.Instance.getIsGameOver()) return;
  114. if (!this.currentTarget) {
  115. this._handleMovement(deltaTime);
  116. this._detectEnemies();
  117. } else {
  118. this._handleAttack(deltaTime);
  119. }
  120. }
  121. //移动
  122. private _handleMovement(dt: number) {
  123. if (this._state !== RoleState.Move) return;
  124. let x = this.node.position.x;
  125. let y = this.node.position.y;
  126. let z = this.node.position.z;
  127. x = x + this.moveSpeed * this.direction * dt
  128. this.node.setPosition(x, y, z);
  129. }
  130. //寻敌
  131. private _detectEnemies() {
  132. //节点不可用,不寻敌
  133. if (!this.node.isValid) return;
  134. //游戏结束,不寻敌
  135. if(GameInfo.Instance.getIsGameOver()) return;
  136. //const startPos = new Vec2(this.node.position.x, this.node.position.y);
  137. const startPos = this.node.position.clone();
  138. const endPos = new Vec2((this.direction * this.atkLength) + this.node.position.x, this.node.position.y);
  139. const results = PhysicsSystem2D.instance.raycast(startPos, endPos);
  140. if (results?.length) {
  141. for (const result of results) {
  142. const target = result.collider.node.getComponent(Role);
  143. if (target && this._isValidTarget(target)) {
  144. this._setTarget(target);
  145. break;
  146. }
  147. }
  148. }
  149. }
  150. //设置攻击目标
  151. private _setTarget(target: Role) {
  152. this.currentTarget = target;
  153. this.playAnimation(RoleState.Attack);
  154. // 使得第一次update就会触发attackTimer >= attackInterval条件
  155. this._attackTimer = this._attackInterval - 0.001;
  156. //监听目标销毁事件
  157. target.node.once(Node.EventType.NODE_DESTROYED, this._onTargetDestroyed, this);
  158. }
  159. //攻击
  160. private _handleAttack(deltaTime: number) {
  161. //目标是否可以攻击
  162. if (!this._validateTarget()) {
  163. this._clearTarget();
  164. return;
  165. }
  166. /*
  167. //立即攻击判断
  168. if (this._attackTimer === 0) {
  169. this._createBullet();
  170. this._attackTimer += deltaTime;
  171. return;
  172. }
  173. //后续间隔攻击
  174. this._attackTimer += deltaTime;
  175. if (this._attackTimer >= this._attackInterval) {
  176. this._createBullet();
  177. this._attackTimer = 0; //重置计时器
  178. }
  179. */
  180. // this._createBullet();
  181. // this.schedule(() => {
  182. // this._createBullet();
  183. // }, this.attackInterval);
  184. }
  185. //目标是否可以攻击 hp大于0 并且 在攻击范围内 -> 可以攻击
  186. private _validateTarget(): boolean {
  187. return !!this.currentTarget?.node?.isValid &&
  188. this.currentTarget.node.getComponent(LifeBar)._curHp > 0 &&
  189. this._getDistanceToTarget() <= this.atkLength;
  190. }
  191. //攻击目标与自身的距离
  192. private _getDistanceToTarget(): number {
  193. return Math.abs(this.node.getWorldPosition().x - this.currentTarget.node.getWorldPosition().x);
  194. }
  195. //销毁目标
  196. private _onTargetDestroyed() {
  197. this._clearTarget();
  198. if (this.node === null) return;
  199. this._detectEnemies();//立即检测新目标
  200. }
  201. //清除目标 关闭触发事件 当前目标置空 设置移动状态 播放移动动画
  202. private _clearTarget() {
  203. this.currentTarget?.node.off(Node.EventType.NODE_DESTROYED, this._onTargetDestroyed, this);
  204. this.currentTarget = null;
  205. this.playAnimation(RoleState.Move);
  206. }
  207. //将各个动画存储起来
  208. private _collectAni() {
  209. this._createClip(RoleState.Move, this._moveFrames, 8);
  210. this._createClip(RoleState.Attack, this._atkFrames, 6);
  211. this._createClip(RoleState.Idle, this._idleFrames, 8);
  212. this._createClip(RoleState.Die, this._dieFrames, 9);
  213. }
  214. //创建动画剪辑 fps越大 速度越快
  215. private _createClip(state: RoleState, frames: SpriteFrame[], fps: number) {
  216. const clip: AnimationClip = AnimationClip.createWithSpriteFrames(frames, fps);
  217. clip.name = RoleState[state];
  218. clip.wrapMode = state === RoleState.Die ?
  219. AnimationClip.WrapMode.Normal :
  220. AnimationClip.WrapMode.Loop;
  221. if (clip.name === 'Attack') {
  222. clip.events = [{
  223. frame: 0.5,
  224. func: "onTriggered",
  225. params: [""] //向func传递的参数
  226. }]
  227. }
  228. this._animation.addClip(clip, clip.name);
  229. this._animations.set(state, clip.name);
  230. }
  231. onTriggered() {
  232. this._createBullet();
  233. }
  234. //设置动画
  235. public playAnimation(state: RoleState) {
  236. if (!this._animation || this._state === state) return;
  237. const clipName = this._animations.get(state);
  238. if (!clipName) return;
  239. //如果当前有动画正在播放,等待其完成后再切换
  240. if (this._animation.getState(String(this._state))?.isPlaying) {
  241. this._animation.once(Animation.EventType.FINISHED, () => {
  242. this._switchState(state, clipName);
  243. });
  244. } else {
  245. this._switchState(state, clipName);
  246. }
  247. }
  248. private _switchState(state: RoleState, clipName: string) {
  249. this._state = state;
  250. //this._animation.stop();
  251. this._animation.play(clipName);
  252. if (state === RoleState.Die) {
  253. this.node.removeAllChildren();
  254. this._animation.once(Animation.EventType.FINISHED, () => {
  255. this.node.destroy();
  256. });
  257. }
  258. }
  259. private _createBullet() {
  260. const isEnemy = this.direction === -1;
  261. this._bullet = this._bulletPool.getBullet(isEnemy);
  262. this._bullet.parent = this.bulletLayer;
  263. this._bullet.setWorldPosition(this.node.getWorldPosition());
  264. const bulletTS = this._bullet.getComponent(Bullet);
  265. bulletTS.reset({
  266. pool: this._bulletPool,
  267. isEnemy: isEnemy,
  268. direction: this.direction,
  269. bulletFrames: this._bulletFrames,
  270. explodeFrames: this._explodeframes,
  271. targetNode: this.currentTarget.node,
  272. atk: this.atk,
  273. })
  274. }
  275. //要求子类实现的碰撞分组和阵营判断方法,确保不同阵营角色可以正确交互
  276. protected _getCollisionGroup(): number {
  277. throw new Error("Method not implemented");
  278. }
  279. protected _isValidTarget(target: Role): boolean {
  280. throw new Error("Method not implemented");
  281. }
  282. }