Role.ts 11 KB

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