LevelContainer.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import { _decorator, Component, Prefab, Sprite, SpriteFrame, instantiate, Node, Vec3, assetManager, AssetManager, resources, randomRangeInt, randomRange, UITransform, Vec2, input, Input, Camera, find, Size } from "cc";
  2. import FindItem, { ItemState } from "./FindItem";
  3. import { LayerMgr } from "../../script/Manager/LayerMgr";
  4. import { CCFloat } from "cc";
  5. import EventMgr from "../../script/Manager/EventMgr";
  6. import { Difficulty, Skin, SuperFind } from "../../script/Manager/LocalDataMgr";
  7. import { BundleName } from "../../script/Config/EnumCfg";
  8. import { AudioManager } from "../../script/Manager/AudioMgr";
  9. const { ccclass, property } = _decorator;
  10. // 关卡模式枚举
  11. export enum LevelMode {
  12. EDIT, // 编辑模式
  13. NORMAL // 正常选择模式
  14. }
  15. @ccclass('LevelContainer')
  16. export class LevelContainer extends Component {
  17. @property({ type: Node, tooltip: '遮罩' })
  18. mask: Node = null;
  19. @property({ type: Sprite, tooltip: '背景图' })
  20. lvlBg: Sprite = null;
  21. @property({ type: Prefab, tooltip: '物品预制体' })
  22. findItemPrefab: Prefab = null;
  23. @property({ type: CCFloat, tooltip: '最小缩放比例' })
  24. minScale: number = 0.1;
  25. @property({ type: CCFloat, tooltip: '最大缩放比例' })
  26. maxScale: number = 1.5;
  27. @property({ type: Node, tooltip: '物品容器' })
  28. itemContainer: Node = null;
  29. _findItems: FindItem[] = [];
  30. _currentMode: LevelMode = LevelMode.NORMAL;
  31. _totalItems: number = 0;
  32. _foundItems: number = 0;
  33. _onLevelComplete: Function = null;
  34. _bgPath: string = "";
  35. _itemSpinePaths: string[] = [];
  36. _itemcnt: number = 0;
  37. _itemScales: number[] = [];
  38. _defaultScales: number[] = [1.18, 1.16, 1.14, 0.3976, 0.3690, 0.3029,
  39. 0.0667, 0.0766, 0.0531, 0.0716];
  40. _canTouch: boolean = true;
  41. _camera: Camera = null;
  42. start() {
  43. // LayerMgr.instance.loadBundle("editor", () => {
  44. // this.genLvlContent("image/bg1", ["prefab/spine/spine01"], 10);
  45. // });
  46. try {
  47. this._camera = find("Canvas/Camera").getComponent(Camera);
  48. } catch (error) {
  49. console.error("超级找茬未找到相机组件");
  50. }
  51. this.addResetListener()
  52. input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
  53. }
  54. onTouchStart()
  55. {
  56. input.getAllTouches().forEach(touch => {
  57. for(let i = 0; i < this._findItems.length; i++)
  58. {
  59. const item = this._findItems[i];
  60. let itemPos = item.node.getWorldPosition();
  61. let screenPos = touch.getLocation();
  62. let touchWorldPos = this._camera.screenToWorld(new Vec3(screenPos.x, screenPos.y, 0));
  63. if(Vec3.squaredDistance(itemPos, touchWorldPos) > 10000)
  64. {
  65. this.touchItemFail(touchWorldPos);
  66. }
  67. }
  68. })
  69. }
  70. /**
  71. * 切换编辑模式
  72. * @param isEdit 是否为编辑模式
  73. */
  74. swtichEditMode(isEdit: boolean) {
  75. this._currentMode = isEdit ? LevelMode.EDIT : LevelMode.NORMAL;
  76. // 更新所有物品的状态
  77. this._findItems.forEach(item => {
  78. if (isEdit) {
  79. item.enterEditMode();
  80. } else {
  81. item.exitEditMode();
  82. }
  83. });
  84. // 重置找到的物品计数
  85. if (!isEdit) {
  86. this._foundItems = 0;
  87. }
  88. }
  89. /**
  90. * 生成关卡内容
  91. * @param bgPath 背景图路径
  92. * @param Items 物品预制体路径数组
  93. * @param itemcnt 物品数量
  94. * @param itemScales 物品缩放数组,为空时随机缩放
  95. */
  96. public genLvlContent(bgPath: string, itemSpinePaths: string[], itemcnt: number, itemScales: number[] = null) {
  97. // 清空现有物品
  98. this.clearItems();
  99. this._bgPath = bgPath;
  100. this._totalItems = itemcnt;
  101. this._itemSpinePaths = itemSpinePaths;
  102. this._itemcnt = itemcnt;
  103. this._itemScales = itemScales || this._defaultScales;
  104. // 加载背景图
  105. this.loadSprite(bgPath, (spriteFrame: SpriteFrame) => {
  106. console.log("loadSprite", bgPath, spriteFrame);
  107. if (this.lvlBg && spriteFrame) {
  108. this.lvlBg.spriteFrame = spriteFrame;
  109. }
  110. });
  111. var randomIndex = itemSpinePaths.indexOf(Skin.skinData._lastSelectSpinePath);
  112. // console.log("物品数量", itemcnt,"物品缩放数组长度",Difficulty.difficutyData.scales.length,"动画路径长度",itemSpinePaths.length);
  113. // 生成物品
  114. for (let i = 0; i < itemcnt; i++) {
  115. // 随机选择一个物品
  116. randomIndex = Skin.skinData.singleSelect == "true" && Skin.skinData.selectedSkinList.length > 0?randomIndex: randomRangeInt(0, itemSpinePaths.length);
  117. console.log("皮肤路径", itemSpinePaths,"索引",randomIndex,"last",Skin.skinData._lastSelectSpinePath);
  118. this.createItem(itemSpinePaths[randomIndex], Difficulty.difficutyData.scales[i]);
  119. }
  120. }
  121. /**
  122. * 创建物品
  123. * @param itemPrefab 物品预制体
  124. * @param scale 缩放值,null时随机缩放
  125. */
  126. private createItem(itemPrefabPath: string, scale: number | null) {
  127. // console.log("当前spine路径", itemPrefabPath);
  128. const itemNode = instantiate(this.findItemPrefab);
  129. itemNode.parent = this.itemContainer || this.node;
  130. const findItem = itemNode.getComponent(FindItem);
  131. if (findItem) {
  132. var size = this.mask.getComponent(UITransform).contentSize;
  133. // 设置缩放
  134. const finalScale = scale !== null ? scale : randomRange(this.minScale, this.maxScale);
  135. // 设置随机位置, 不要出边框
  136. var itemSize = itemNode.getComponent(UITransform).contentSize;
  137. var w = itemSize.width * finalScale;
  138. var h = itemSize.height * finalScale;
  139. // 随机,并尽量不要重叠
  140. let tryCount = 0;
  141. let maxTry = 50;
  142. let pos: Vec3;
  143. let overlap = false;
  144. do {
  145. overlap = false;
  146. const randomX = randomRange(-size.width / 2 + w / 2, size.width / 2 - w / 2);
  147. const randomY = randomRange(-size.height / 2 + h / 2, size.height / 2 - h / 2);
  148. pos = new Vec3(randomX, randomY, 0);
  149. // 检查与已放置物品是否重叠
  150. for (let other of this._findItems) {
  151. let otherPos = other.node.getPosition();
  152. let otherScale = other.node.scale.x;
  153. let otherSize = other.node.getComponent(UITransform).contentSize;
  154. let otherW = otherSize.width * otherScale;
  155. let otherH = otherSize.height * otherScale;
  156. // 简单的AABB重叠检测
  157. if (
  158. Math.abs(pos.x - otherPos.x) < (w + otherW) / 2 &&
  159. Math.abs(pos.y - otherPos.y) < (h + otherH) / 2
  160. ) {
  161. overlap = true;
  162. break;
  163. }
  164. }
  165. tryCount++;
  166. } while (overlap && tryCount < maxTry);
  167. itemNode.setPosition(pos);
  168. findItem.setData({
  169. position: itemNode.getPosition(),
  170. scale: finalScale
  171. });
  172. // 添加spine内容
  173. this.loadPrefab(itemPrefabPath, (prefab: Prefab) => {
  174. findItem.addSpineContentByPrefab(prefab);
  175. });
  176. // 设置状态
  177. findItem.setState(this._currentMode === LevelMode.EDIT ? ItemState.EDIT : ItemState.NORMAL);
  178. // 添加到物品列表
  179. this._findItems.push(findItem);
  180. // 监听物品状态变化
  181. this.setupItemListeners(findItem);
  182. }
  183. }
  184. /**
  185. * 设置物品监听器
  186. * @param findItem 物品组件
  187. */
  188. private setupItemListeners(findItem: FindItem) {
  189. // 监听物品点击事件
  190. findItem.node.on("itemFound", () => {
  191. if (this._currentMode === LevelMode.NORMAL) {
  192. this._foundItems++;
  193. AudioManager.instance.playBundleAudio("right")
  194. // console.log("itemFound", this._foundItems, this._totalItems);
  195. // 检查是否所有物品都被找到
  196. if (this._foundItems >= this._totalItems) {
  197. this.onLevelComplete();
  198. }
  199. }
  200. });
  201. }
  202. touchItemFail(worldPos: Vec3) {
  203. if (this._canTouch == false) return
  204. this._canTouch = false
  205. this.scheduleOnce(() => {
  206. this._canTouch = true
  207. }, 0.1)
  208. LayerMgr.instance.ShowPrefab(BundleName.hall, "prefab/x", (node: Node) => {
  209. this.itemContainer.addChild(node)
  210. AudioManager.instance.playBundleAudio("wrong")
  211. node.setWorldPosition(worldPos)
  212. this.scheduleOnce(() => {
  213. node?.destroy()
  214. }, 0.3)
  215. })
  216. }
  217. /**
  218. * 关卡完成回调
  219. */
  220. private onLevelComplete() {
  221. if (this._onLevelComplete) {
  222. this._onLevelComplete();
  223. }
  224. EventMgr.ins.dispatchEvent("win")
  225. // 可以在这里添加完成动画或音效
  226. console.log("关卡完成!所有物品都已找到");
  227. }
  228. /**
  229. * 清空所有物品
  230. */
  231. private clearItems() {
  232. // this._findItems.forEach(item => {
  233. // if (item && item.node) {
  234. // item.node.destroy();
  235. // }
  236. // });
  237. let count = this._findItems.length;
  238. for(let i = 0; i < count; i++)
  239. {
  240. const item = this._findItems.pop();
  241. if (item && item.node) {
  242. item.node.destroy();
  243. }
  244. }
  245. this._findItems = [];
  246. this._foundItems = 0;
  247. this._totalItems = 0;
  248. }
  249. /**
  250. * 设置关卡完成回调
  251. * @param callback 完成回调函数
  252. */
  253. public setLevelCompleteCallback(callback: Function) {
  254. this._onLevelComplete = callback;
  255. }
  256. /**
  257. * 显示提示(高亮未找到的物品)
  258. */
  259. public showHint() {
  260. this._findItems.forEach(item => {
  261. if (item.getState() === ItemState.NORMAL) {
  262. item.showHint();
  263. }
  264. });
  265. }
  266. public showOneHint()
  267. {
  268. for(let i = 0; i < this._findItems.length; i++)
  269. {
  270. if(this._findItems[i].getState() === ItemState.NORMAL)
  271. {
  272. this._findItems[i].showHint()
  273. break
  274. }
  275. }
  276. }
  277. public reset() {
  278. this.clearItems();
  279. this.swtichEditMode(false);
  280. this.genLvlContent(this._bgPath, this._itemSpinePaths, this._itemcnt, this._itemScales);
  281. }
  282. /**
  283. * 获取关卡数据(用于保存)
  284. */
  285. public getLevelData() {
  286. return {
  287. items: this._findItems.map(item => item.getData()),
  288. totalItems: this._totalItems
  289. };
  290. }
  291. /**
  292. * 加载精灵图片
  293. * @param path 图片路径
  294. * @param callback 回调函数
  295. */
  296. /**
  297. * 加载精灵图片
  298. * @param path 图片路径
  299. * @param callback 回调函数
  300. */
  301. loadSprite(path: string, callback: (spriteFrame: SpriteFrame) => void) {
  302. LayerMgr.instance.loadSprite("editor", path, (spriteFrame: SpriteFrame) => {
  303. if (this.lvlBg && spriteFrame) {
  304. this.lvlBg.spriteFrame = spriteFrame;
  305. // 获取Mask的尺寸
  306. const maskSize = this.mask.getComponent(UITransform).contentSize;
  307. // 获取原始图片尺寸
  308. const originalSize = spriteFrame.originalSize;
  309. // 计算缩放比例
  310. const scaleRatio = maskSize.width / originalSize.width;
  311. // 设置背景图尺寸
  312. this.lvlBg.node.getComponent(UITransform).contentSize = new Size(
  313. maskSize.width,
  314. originalSize.height * scaleRatio
  315. );
  316. // 确保背景图填满整个Mask区域
  317. this.lvlBg.node.setScale(1, 1);
  318. // 调用原始回调
  319. if (callback) {
  320. callback(spriteFrame);
  321. }
  322. }
  323. });
  324. }
  325. prefabMap: Map<string, Prefab> = new Map();
  326. /**
  327. * 加载预制体
  328. * @param path 预制体路径
  329. * @param callback 回调函数
  330. */
  331. loadPrefab(path: string, callback: (prefab: Prefab) => void) {
  332. if (this.prefabMap.has(path)) {
  333. callback(this.prefabMap.get(path));
  334. return;
  335. }
  336. LayerMgr.instance.loadPrefab("editor", path, (prefab: Prefab) => {
  337. this.prefabMap.set(path, prefab);
  338. callback(prefab);
  339. });
  340. }
  341. addResetListener()
  342. {
  343. EventMgr.ins.addEventListener("regenerate",this.updateLevel,this)
  344. }
  345. showOrHideScale(isShow: boolean)
  346. {
  347. for(let i = 0; i < this._findItems.length; i++)
  348. {
  349. this._findItems[i].showOrHideScale(isShow)
  350. }
  351. }
  352. //获取上一关的
  353. lastLevel() {
  354. SuperFind.lastLevel()
  355. this.updateLevel()
  356. EventMgr.ins.dispatchEvent("restart")
  357. }
  358. nextLevel()
  359. {
  360. SuperFind.nextLevel()
  361. this.updateLevel()
  362. EventMgr.ins.dispatchEvent("restart")
  363. }
  364. updateLevel()
  365. {
  366. this.clearItems();
  367. this.swtichEditMode(false);
  368. this.genLvlContent(SuperFind.superFindData.imgPath, Skin.getSelectSkinPath(), Difficulty.difficutyData.difficutyCount, this._itemScales);
  369. }
  370. win()
  371. {
  372. }
  373. }