SightGlass.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { _decorator, Component, Node, UITransform, v3 } from 'cc';
  2. import { DataSystem } from '../core/data/DataSystem';
  3. import { BattleData } from './BattleData';
  4. import { Monster } from './Monster';
  5. const { ccclass, property } = _decorator;
  6. @ccclass('SightGlass')
  7. export class SightGlass extends Component {
  8. @property({ type: Node, tooltip: "瞄准镜" }) sightGlass: Node;
  9. private data: BattleData;
  10. private fouceTarget: Node;
  11. private lastMonsterID: number = -1;
  12. start() {
  13. this.data = DataSystem.getData(BattleData);
  14. }
  15. update(): void {
  16. DataSystem.watch(BattleData, "_monsters") && this.onMonsterChange();
  17. DataSystem.watch(BattleData, "_target") && this.targetChange();
  18. DataSystem.watch(BattleData, "_deleteMonster") && this.deleteMonster();
  19. this.setGlass();
  20. }
  21. /** 当怪物发生变化时 */
  22. private onMonsterChange(): void {
  23. if (this.data._target != -1 && this.lastMonsterID != -1) {
  24. for (let i = 0; i < this.data._monsters.length; i++) {
  25. if (this.lastMonsterID == this.data._monsters[i].data._id) {
  26. this.data._target = i;
  27. return;
  28. }
  29. }
  30. this.data._target = -1;
  31. this.lastMonsterID = -1;
  32. }
  33. }
  34. /**强制目标改变 */
  35. private targetChange(): void {
  36. if (this.data._target != -1) {
  37. this.fouceTarget = this.data._monsters[this.data._target].node;
  38. this.lastMonsterID = this.data._monsters[this.data._target].data._id;
  39. } else {
  40. this.fouceTarget = null;
  41. }
  42. }
  43. /**设置瞄准镜 */
  44. private setGlass(): void {
  45. if (this.fouceTarget) {
  46. this.sightGlass.position = this.fouceTarget.position.clone().add(v3(0, this.fouceTarget.getComponent(UITransform).height * this.fouceTarget.scale.y / 2, 0));
  47. } else {
  48. this.sightGlass.position = v3(1000, 1000, 0);
  49. }
  50. }
  51. /**删除怪物 */
  52. private deleteMonster(): void {
  53. if (this.fouceTarget && (!this.fouceTarget.getComponent(Monster).data || this.data._deleteMonster.indexOf(this.fouceTarget.getComponent(Monster).data._id) != -1)) {
  54. this.data._target = -1;
  55. this.fouceTarget = null;
  56. }
  57. }
  58. }