Role.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. import { BulletPool } from './GameScene/BulletPool';
  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 = true;
  26. //攻击目标
  27. targetNode: Node = null;
  28. //战斗系统
  29. private _attackTimer: number = 0;
  30. private _attackInterval: number = 3;//攻击间隔
  31. private currentTarget: Role | null = null;//当前目标
  32. //子弹
  33. private _bullet: Node | null = null;
  34. private _bulletLayer: 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. protected 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 + 100;
  93. this.moveSpeed = roleData.moveSpeed;
  94. }
  95. private _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. this.stop();
  135. }
  136. //寻敌
  137. private _detectEnemies() {
  138. if (!this.node.isValid) 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.hp > 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. stop() {
  211. }
  212. //将各个动画存储起来
  213. private _collectAni() {
  214. // const moveAni: Animation = Tools.createAnimation(this._moveFrames, 8, this.node, AnimationClip.WrapMode.Loop)
  215. // this._animations.set(RoleState.Move, moveAni);
  216. // const atkAni: Animation = Tools.createAnimation(this._atkFrames, 8, this.node, AnimationClip.WrapMode.Loop)
  217. // this._animations.set(RoleState.Attack, atkAni);
  218. // const idleAni: Animation = Tools.createAnimation(this._idleFrames, 8, this.node, AnimationClip.WrapMode.Loop)
  219. // this._animations.set(RoleState.Idle, idleAni);
  220. // const dieAni: Animation = Tools.createAnimation(this._dieFrames, 8, this.node, AnimationClip.WrapMode.Normal)
  221. // this._animations.set(RoleState.Die, dieAni);
  222. this._createClip(RoleState.Move, this._moveFrames, 8);
  223. this._createClip(RoleState.Attack, this._atkFrames, 8);
  224. this._createClip(RoleState.Idle, this._idleFrames, 8);
  225. this._createClip(RoleState.Die, this._dieFrames, 9);
  226. }
  227. //创建动画剪辑 fps越大 速度越快
  228. private _createClip(state: RoleState, frames: SpriteFrame[], fps: number) {
  229. const clip: AnimationClip = AnimationClip.createWithSpriteFrames(frames, fps);
  230. clip.name = RoleState[state];
  231. clip.wrapMode = state === RoleState.Die ?
  232. AnimationClip.WrapMode.Normal :
  233. AnimationClip.WrapMode.Loop;
  234. if(clip.name === 'Attack'){
  235. clip.events = [{
  236. frame: 0.5,
  237. func: "onTriggered",
  238. params: ["a"] //向func传递的参数
  239. }]
  240. }
  241. this._animation.addClip(clip, clip.name);
  242. this._animations.set(state, clip.name);
  243. }
  244. onTriggered(){
  245. this._createBullet();
  246. }
  247. //设置动画
  248. public playAnimation(state: RoleState) {
  249. if (!this._animation || this._state === state) return;
  250. const clipName = this._animations.get(state);
  251. if (!clipName) return;
  252. this._state = state;
  253. this._animation.stop();
  254. this._animation.play(clipName);
  255. if (state === RoleState.Die) {
  256. this.node.removeAllChildren();
  257. this._animation.once(Animation.EventType.FINISHED, () => {
  258. this.node.destroy();
  259. });
  260. }
  261. // if (this._animations === null) {
  262. // Error("No found" + state);
  263. // return;
  264. // }
  265. // if (this._state === state) return;
  266. // this._state = state;
  267. // this._animations.get(state).play();
  268. // if (state === RoleState.Die) {
  269. // this._animations.get(state).once(Animation.EventType.FINISHED, () => {
  270. // this.node.destroy();
  271. // })
  272. // }
  273. // this._animations.forEach((anim, key) => {
  274. // if(key === state){
  275. // anim.play();
  276. // if(key === RoleState.Die){
  277. // anim.once(Animation.EventType.FINISHED,()=>{
  278. // this.node.destroy();
  279. // })
  280. // }
  281. // }
  282. // //key === state ? anim.play() : anim.stop();
  283. // })
  284. }
  285. //判断是否攻击
  286. // getEnemiesAhead(parent: Node) {
  287. // for (const node of parent.children) {
  288. // const enemyY = node.getWorldPosition().y;
  289. // const enemyX = node.getWorldPosition().x;
  290. // const y = this.node.getWorldPosition().y;
  291. // const x = this.node.getWorldPosition().x;
  292. // if (enemyY === y) {
  293. // const distance = Math.abs(enemyX - x);
  294. // if (distance <= this.atkLength) {
  295. // //开始攻击
  296. // this.isAttacking = true;
  297. // //设置攻击目标
  298. // this.targetNode = node;
  299. // //停止移动
  300. // this.isStop = true;
  301. // //开始开火
  302. // this.isFire = true;
  303. // this.attack(this.targetNode, this.isFire);
  304. // break;
  305. // }
  306. // }
  307. // }
  308. // }
  309. // attack(targetNode: Node, isFire: boolean) {
  310. // if (!targetNode) return;
  311. // const targetNodeTS = targetNode.getComponent(Role);
  312. // if (isFire && targetNodeTS.hp > 0) {
  313. // this._createBullet();
  314. // this.schedule(() => {
  315. // this._createBullet();
  316. // }, 3)
  317. // }
  318. // }
  319. //创建子弹
  320. private _createBullet() {
  321. // if (this.direction === -1) {
  322. // this._bullet = instantiate(resMgr.getPrefab("BulletEnemy"));
  323. // } else if (this.direction === 1) {
  324. // this._bullet = instantiate(resMgr.getPrefab("Bullet"));
  325. // }
  326. const isEnemy = this.direction === -1;
  327. this._bullet = this._bulletPool.getBullet(isEnemy);
  328. this._bullet.parent = this._bulletLayer;
  329. this._bullet.setWorldPosition(this.node.getWorldPosition());
  330. const bulletTS = this._bullet.getComponent(Bullet);
  331. bulletTS.reset({
  332. pool: this._bulletPool,
  333. isEnemy: isEnemy,
  334. direction: this.direction,
  335. bulletFrames: this._bulletFrames,
  336. explodeFrames: this._explodeframes,
  337. targetNode: this.currentTarget.node,
  338. atk: this.atk,
  339. })
  340. // bulletTS.direction = this.direction;
  341. // bulletTS.bulletFrames = this._bulletFrames;
  342. // bulletTS.explodeframes = this._explodeframes;
  343. // bulletTS.targetNode = this.currentTarget.node;
  344. // bulletTS.atk = this.atk;
  345. }
  346. //要求子类实现的碰撞分组和阵营判断方法,确保不同阵营角色可以正确交互
  347. protected _getCollisionGroup(): number {
  348. throw new Error("Method not implemented");
  349. }
  350. protected _isValidTarget(target: Role): boolean {
  351. throw new Error("Method not implemented");
  352. }
  353. }