Role.ts 13 KB

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