GeneratingTarget.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using TMPro;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. using UnityEngine.UI;
  7. using UnityEngine.SceneManagement;
  8. using SmartBowSDK;
  9. using System;
  10. using HyperspaceGame;
  11. using MathNet.Numerics;
  12. public class GeneratingTarget : MonoBehaviour
  13. {
  14. // 最小时间间隔(秒)
  15. float _minTimeBetweenEvents = 1.0f;
  16. public float minTimeBetweenEvents { get { return _minTimeBetweenEvents; } set { _minTimeBetweenEvents = value; } }
  17. float _maxTimeBetweenEvents = 3.0f;// 最大时间间隔(秒)
  18. public float maxTimeBetweenEvents { get { return _maxTimeBetweenEvents; } set { _maxTimeBetweenEvents = value; } }
  19. public GameObject target;
  20. public Transform UI;
  21. public TextMeshProUGUI scoreUI;
  22. public TextMeshProUGUI scoreUI1;
  23. public Text countDownUI;
  24. public TextMeshProUGUI clipsizeUI;
  25. public TextMeshProUGUI hitCountUI;
  26. public TextMeshProUGUI shootRate;
  27. public GameObject GameOver;
  28. public Score scoreCom;
  29. public Score scoreCom1;
  30. public GameObject Miss;
  31. public Image grade;
  32. public Transform tp;
  33. public GameObject bulletNull;//子弹不足UI
  34. public GameObject[] bulletImages;//子弹图片数组
  35. public GameObject SelectLv;
  36. public Image imgSlider;
  37. public Text TopScore;
  38. public Text CurLvTxt;
  39. public Text MaxLvTxt;
  40. public int bulletCount;//子弹数量
  41. public int hitCount;//击中数量
  42. private float rate;//命中率
  43. public Button BtnRestart;
  44. public Button BtnNext;
  45. public Button BtnLast;
  46. int _score;
  47. public bool stop = false;
  48. public int score { get { return _score; }
  49. set {
  50. _score = value;
  51. ShowScore();
  52. }
  53. }
  54. /// <summary>
  55. /// 游戏时间
  56. /// </summary>
  57. private float countDownTime;
  58. int countDownTimeCache;
  59. /// <summary>
  60. /// 子弹数量
  61. /// </summary>
  62. private int clipsize;
  63. const int BulletCount = 15;
  64. /// <summary>
  65. /// 靶子存在最长时间
  66. /// </summary>
  67. float _targetExistenceTimeMax = 5;
  68. public float TargetExistenceTimeMax { get { return _targetExistenceTimeMax; } set { _targetExistenceTimeMax = value; } }
  69. /// <summary>
  70. /// 靶子存在最短时间
  71. /// </summary>
  72. float _targetExistenceTimeMin = 3;
  73. public float TargetExistenceTimeMin { get { return _targetExistenceTimeMin; } set { _targetExistenceTimeMin = value; } }
  74. float _scaleMin = 1.3f;
  75. public float ScaleMin { get { return _scaleMin; } set { _scaleMin = value; } }
  76. float _scaleMax = 1.8f;
  77. public float ScaleMax { get { return _scaleMax; } set { _scaleMax = value; } }
  78. public HyperspaceGame.Font font;
  79. public AudioSource ShootingSound;
  80. public AudioSource gameSatrtSound;
  81. public AudioClip[] gameSatrtClips;
  82. //public GameObject perfect;
  83. //public GameObject gaeat;
  84. //public GameObject good;
  85. //public Image goodImage;
  86. //public Image greatImage;
  87. public static GeneratingTarget gm { get; set; }
  88. public ShootingEvent shootingEvent;
  89. /// <summary>
  90. /// 记录当前射箭是否记录分数
  91. /// </summary>
  92. private bool bAddCountScore { get; set; } = false;
  93. [HideInInspector] public bool getAddCountScore => bAddCountScore;
  94. //分数统计
  95. [HideInInspector] public UserGameAnalyse1 userGameAnalyse1;
  96. public int Index = 0;
  97. private bool unload = false;
  98. /// <summary>
  99. /// 当前难度的配置
  100. /// </summary>
  101. public Level LvCfg = null;
  102. /// <summary>
  103. /// 当前序列的配置
  104. /// </summary>
  105. public Order orderCfg = null;
  106. float nextOrderWaitTime;
  107. int curOrderIdx;
  108. bool canEnterNextOrder = true;
  109. bool isbegin = false;
  110. int tragetLeftNum;
  111. /// <summary>
  112. /// 当前序列
  113. /// </summary>
  114. public int CurOrder = 0;
  115. public static int MaxLevel = 3;
  116. public List<Sprite> ScoreLevel;
  117. [SerializeField]
  118. RectTransform _canvasRectTransform;
  119. private void Awake()
  120. {
  121. gm = this;
  122. var scene = SceneManager.GetActiveScene();
  123. if(scene.name == "Hyperspace01")
  124. Index = 0;
  125. else if (scene.name == "Hyperspace02")
  126. Index = 1;
  127. else if(scene.name == "Hyperspace03")
  128. Index = 2;
  129. //初始化关卡配置
  130. LvCfg = Config.levels[Index];
  131. countDownTime = LvCfg.TotalTime;
  132. curOrderIdx = 0;
  133. UpdateCountDown(LvCfg.TotalTime);
  134. CurLvTxt.text = $"{Index + 1}";
  135. MaxLvTxt.text = $"/<color=#0F92D4>{MaxLevel}</color>";
  136. shootingEvent = FindObjectOfType<ShootingEvent>();
  137. scoreCom.gameObject.SetActive(false);
  138. scoreCom1.gameObject.SetActive(false);
  139. Miss.SetActive(false);
  140. stop = false;
  141. imgSlider.fillAmount = 1;
  142. ShowScore();
  143. bulletNull.SetActive(false);
  144. BtnRestart.onClick.AddListener(OnRestart);
  145. BtnNext.onClick.AddListener(OnBtnNext);
  146. BtnNext.gameObject.SetActive(Index + 1 < MaxLevel);
  147. BtnLast.onClick.AddListener(OnBtnLast);
  148. BtnLast.gameObject.SetActive(true);
  149. GameOver.SetActive(false);
  150. CreateUIManager();
  151. CreateTargetObject2D();
  152. }
  153. public void OnRestart()
  154. {
  155. Restart(Index);
  156. }
  157. public void OnBtnNext()
  158. {
  159. Restart(Index + 1);
  160. }
  161. public void OnBtnLast()
  162. {
  163. //Restart(Index - 1);
  164. gm = null;
  165. onUploadScore();
  166. ////结束游戏页面
  167. //userGameAnalyse1.UploadData(true);
  168. //userGameAnalyse1.onResetOverlayData();
  169. //SceneManager.LoadScene("Home", LoadSceneMode.Single);
  170. //结束游戏页面
  171. userGameAnalyse1.showResultView(() =>
  172. {
  173. SceneManager.LoadScene("Home", LoadSceneMode.Single);
  174. });
  175. }
  176. void Start()
  177. {
  178. if (ShootCheck.ins.bluetoothDeviceStatus == BluetoothDeviceStatus.MagazineLoading)
  179. OnLoading();
  180. else
  181. OnSeparation();
  182. //Screen.SetResolution(1280, 720, false); // 设置分辨率为1920x1080,‌并设置为全屏模式
  183. Invoke("GameStart", 4);
  184. Game1();
  185. Invoke("Game2", 1);
  186. Invoke("Game3", 2);
  187. var canvases = FindObjectsByType<Canvas>(FindObjectsSortMode.InstanceID);
  188. foreach (var canvas in canvases)
  189. {
  190. if (canvas.name == "Canvas")
  191. {
  192. _canvasRectTransform = canvas.GetComponent<RectTransform>();
  193. break;
  194. }
  195. }
  196. //靶子默认状态
  197. var show = UIManager._ins.GetArrowBtnState();
  198. var arrow = shootingEvent.GetComponent<Image>();
  199. var color = arrow.color;
  200. if (show)
  201. color.a = 1;
  202. else
  203. color.a = 0;
  204. arrow.color = color;
  205. UIManager._ins.ShowQuit();
  206. }
  207. public void OpenSelectLevel()
  208. {
  209. SelectLv.SetActive(true);
  210. }
  211. public Vector2 GetCanvasSize()
  212. {
  213. return _canvasRectTransform.sizeDelta;
  214. }
  215. void Game1()
  216. {
  217. gameSatrtSound.clip = gameSatrtClips[0];
  218. gameSatrtSound.Play();
  219. }
  220. void Game2()
  221. {
  222. gameSatrtSound.clip = gameSatrtClips[1];
  223. gameSatrtSound.Play();
  224. }
  225. void Game3()
  226. {
  227. gameSatrtSound.clip = gameSatrtClips[2];
  228. gameSatrtSound.Play();
  229. }
  230. void GameStart()
  231. {
  232. isbegin = true;
  233. }
  234. private float reloadTime = 0;
  235. private void Reload(bool delay = false)
  236. {
  237. if (delay)
  238. {
  239. reloadTime = 3f;
  240. }
  241. else
  242. {
  243. clipsize = BulletCount;
  244. bulletCount -= font.Clip;
  245. bulletCount += clipsize;
  246. font.Clip = clipsize;
  247. bulletNull.SetActive(false);
  248. for (int i = 0; i < bulletImages.Length; i++)
  249. {
  250. bulletImages[i].SetActive(true);
  251. }
  252. }
  253. }
  254. public bool Reloading()
  255. {
  256. return unload;
  257. //return reloadTime > 0;
  258. }
  259. float _lastShootTime = 0;
  260. /// <summary>
  261. /// 射击
  262. /// </summary>
  263. /// <param name="bAddCount">是否是有效射箭</param>
  264. public void Shooting(bool bAddCount = false)
  265. {
  266. //加个间隔
  267. if (Time.realtimeSinceStartup - _lastShootTime < 0.5f) return;
  268. _lastShootTime = Time.realtimeSinceStartup;
  269. bAddCountScore = bAddCount;
  270. DoShoot();
  271. }
  272. private void DoShoot()
  273. {
  274. if (shootingEvent.ShootUIBtn())
  275. return;
  276. if (unload || clipsize <= 0)
  277. {
  278. Debug.Log("卸了弹夹 或者 没子弹了!");
  279. //没有子弹的声音
  280. //ShootingSound.Play();
  281. bulletImages[0].SetActive(false);
  282. bulletNull.SetActive(true);
  283. return;
  284. }
  285. else
  286. //正常发射的声音
  287. ShootingSound.Play();
  288. clipsize--;
  289. if (clipsize <= 0)
  290. {
  291. //Reload(true);//不自动装弹
  292. }
  293. font.Clip = clipsize;
  294. bulletImages[clipsize].SetActive(false);
  295. shootingEvent.OnShooting();
  296. }
  297. private void Update()
  298. {
  299. //if (reloadTime > 0)
  300. //{
  301. // reloadTime -= Time.deltaTime;
  302. // if (reloadTime <= 0)
  303. // Reload();
  304. //}
  305. #if UNITY_EDITOR
  306. if (Input.GetMouseButtonDown(0))
  307. {
  308. shootingEvent.OnPositionUpdate(Input.mousePosition);
  309. Shooting(true);
  310. }
  311. if (Input.GetKeyDown(KeyCode.W))
  312. {
  313. countDownTime = 0;
  314. }
  315. if (Input.GetKeyDown(KeyCode.R))
  316. {
  317. UIManager._ins.Reload();
  318. }
  319. #endif
  320. if (isbegin)
  321. {
  322. if (canEnterNextOrder)//靶子全消失了 开始走序列休息时间
  323. {
  324. if (nextOrderWaitTime <= 0)
  325. {
  326. //开始下一序列
  327. TriggerRandomEvent();
  328. }
  329. nextOrderWaitTime -= Time.deltaTime;
  330. }
  331. //游戏倒计时
  332. if (countDownTime <= 0)
  333. {
  334. //游戏时间到了 结束
  335. GameEnd();
  336. }
  337. else
  338. {
  339. countDownTime -= Time.deltaTime;
  340. var timeInt = Mathf.CeilToInt(countDownTime);
  341. if(timeInt != countDownTimeCache)
  342. {
  343. countDownTimeCache = timeInt;
  344. UpdateCountDown(countDownTimeCache);
  345. }
  346. imgSlider.fillAmount = countDownTime / (float)LvCfg.TotalTime;
  347. }
  348. if (curMoveCtrl != null && curMoveCtrl is IUpdate)
  349. {
  350. (curMoveCtrl as IUpdate).Update();
  351. }
  352. }
  353. }
  354. private void UpdateCountDown(int value)
  355. {
  356. countDownUI.text = $"{value}";
  357. }
  358. private void GameEnd()
  359. {
  360. stop = true;
  361. GameOver.SetActive(true);
  362. GameOverGrade(score);
  363. isbegin = false;
  364. countDownTimeCache = 0;
  365. //游戏结束上传分数
  366. onUploadScore();
  367. }
  368. /// <summary>
  369. /// 下一轮
  370. /// </summary>
  371. void TriggerRandomEvent()
  372. {
  373. canEnterNextOrder = false;
  374. Debug.Log($"新一轮创建 curOrderIdx={curOrderIdx}");
  375. if (LvCfg.orders.Length > curOrderIdx)
  376. {
  377. orderCfg = LvCfg.orders[curOrderIdx];
  378. CreateTargets();
  379. curOrderIdx++;
  380. }
  381. else
  382. GameEnd();
  383. }
  384. Dictionary<MoveType, Move> movesCtrl = new Dictionary<MoveType, Move>()
  385. {
  386. [MoveType.Stay] = new Stay(),
  387. [MoveType.VET] = new VET(),
  388. [MoveType.ROT] = new ROT(),
  389. [MoveType.W] = new W(),
  390. [MoveType.W2] = new W2(),
  391. [MoveType.RelativeHor] = new RelativeHor(),
  392. [MoveType.RelativeVet] = new RelativeVet(),
  393. [MoveType.HOR] = new HOR(),
  394. [MoveType.Diagonal] = new Diagonal(),
  395. [MoveType.LeftToRight] = new LeftToRight(),
  396. [MoveType.RightToLeft] = new RightToLeft(),
  397. };
  398. private Move curMoveCtrl;
  399. /// <summary>
  400. /// 创建当前轮靶子
  401. /// </summary>
  402. private void CreateTargets()
  403. {
  404. var createCount = orderCfg.Big + orderCfg.Middle + orderCfg.Small;
  405. Debug.Log($"创建数量 Big={orderCfg.Big} Middle={orderCfg.Middle} Small={orderCfg.Small}");
  406. tragetLeftNum = createCount;
  407. List<SpineAnimationLoader> gos = new List<SpineAnimationLoader>();
  408. for (int i = 0; i < createCount; i++)
  409. {
  410. var go = Instantiate(target, tp);
  411. var targetIns = go.GetComponent<SpineAnimationLoader>();
  412. if(i < orderCfg.Big)
  413. targetIns.Init(0.8f * 0.732f, orderCfg, OnTargetDestory);
  414. else if (i < orderCfg.Big + orderCfg.Middle)
  415. targetIns.Init(0.5f * 0.692f, orderCfg, OnTargetDestory);
  416. else
  417. targetIns.Init(0.3f * 0.733f, orderCfg, OnTargetDestory);
  418. go.SetActive(true);
  419. gos.Add(targetIns);
  420. }
  421. movesCtrl.TryGetValue(orderCfg.MoveType, out curMoveCtrl);
  422. if (curMoveCtrl == null)
  423. curMoveCtrl = movesCtrl[MoveType.Stay];
  424. curMoveCtrl.SetGo(gos);
  425. }
  426. /// <summary>
  427. /// 靶子被射击或者到时间销毁
  428. /// </summary>
  429. private void OnTargetDestory()
  430. {
  431. tragetLeftNum--;
  432. if (tragetLeftNum <= 0)
  433. {
  434. curMoveCtrl = null;
  435. Debug.Log("当前轮结束");
  436. canEnterNextOrder = true;
  437. //重置休息时间
  438. nextOrderWaitTime = orderCfg.WaitTime;
  439. }
  440. }
  441. public void ShowScore()
  442. {
  443. //font.Text = score;
  444. TopScore.text = score.ToString().PadLeft(3, '0');
  445. }
  446. public Score scoreSprite;
  447. public void ShowScoreCom(int score, Vector3 pos, Vector2 scorepos, Transform tf, int posIdx)
  448. {
  449. Debug.Log($"得分 score{score}");
  450. if (score >= 6)
  451. {
  452. var go = GameObject.Instantiate(scoreCom, pos, Quaternion.identity, _canvasRectTransform);
  453. go.gameObject.SetActive(true);
  454. go.transform.localScale = Vector3.one * 0.55f;
  455. go.ShowScore(score, scorepos);
  456. }
  457. else
  458. {
  459. var go = GameObject.Instantiate(scoreCom1, tf.position, Quaternion.identity, _canvasRectTransform);
  460. go.gameObject.SetActive(true);
  461. var halfRadius = 547f * 0.5f;
  462. var offest = tf.localScale.x * halfRadius + 80f;
  463. var x = (posIdx == 1 || posIdx == 2) ? offest : -offest;
  464. var y = (posIdx == 1 || posIdx == 4) ? offest : -offest;
  465. go.ShowScore(score, new Vector3(x, y, 0));
  466. }
  467. }
  468. public void ShowMiss(Vector3 position)
  469. {
  470. if (stop)
  471. return;
  472. var go = GameObject.Instantiate(Miss, position, Quaternion.identity, _canvasRectTransform);
  473. go.AddComponent<CountDown>();
  474. go.SetActive(true);
  475. }
  476. public void GameOverGrade(int score)
  477. {
  478. hitCountUI.text = hitCount.ToString();
  479. var bulletUse = bulletCount - font.Clip;
  480. clipsizeUI.text = bulletUse.ToString();
  481. float rate = 0;
  482. if (hitCount != 0)
  483. rate = (float)hitCount / (float)bulletUse;
  484. if(rate == 0)
  485. {
  486. rate = 0;
  487. }
  488. shootRate.text = string.Format("{0:P0}", rate);
  489. font.Text = score;
  490. var maxScore = 0;
  491. foreach (var item in LvCfg.orders)
  492. {
  493. maxScore += item.Big + item.Middle + item.Small;
  494. }
  495. maxScore *= 10;
  496. var percent = (float)score / (float)maxScore * 100f;
  497. Debug.Log($"得分比例:{percent} score={score} maxScore={maxScore}");
  498. var index = Mathf.CeilToInt(percent / 10) - 1;
  499. grade.sprite = ScoreLevel[index];
  500. }
  501. public void Restart(int index)
  502. {
  503. string name = "";
  504. if (index == 0)
  505. name = "Hyperspace01";
  506. else if (index == 1)
  507. name = "Hyperspace02";
  508. else if (index == 2)
  509. name = "Hyperspace03";
  510. SceneManager.LoadScene(name);
  511. }
  512. //public void SetTarget(int index)
  513. //{
  514. // goodImage.sprite = font.sprites[index];
  515. // good.SetActive(true);
  516. //}
  517. //public void SetGreat(int index)
  518. //{
  519. // greatImage.sprite = font.sprites[index];
  520. // gaeat.SetActive(true);
  521. //}
  522. /// <summary>
  523. /// 弹夹分离
  524. /// </summary>
  525. public void OnSeparation()
  526. {
  527. unload = true;
  528. clipsize = 0;
  529. bulletCount -= font.Clip;
  530. font.Clip = clipsize;
  531. }
  532. /// <summary>
  533. /// 弹夹上膛
  534. /// </summary>
  535. public void OnLoading()
  536. {
  537. unload = false;
  538. Reload();
  539. }
  540. #region 新增 UIManager 和 TargetObject2D
  541. private GameObject uiManagerInstance;
  542. private GameObject targetObject2D;
  543. // 动态加载并生成 UIManager
  544. public void CreateUIManager()
  545. {
  546. GameObject uiManagerPrefab = Resources.Load<GameObject>("UIManager"); // 从 Resources 中加载 UIManager 预制
  547. uiManagerInstance = Instantiate(uiManagerPrefab); // 实例化 UIManager
  548. //管理分数上传
  549. userGameAnalyse1 = UserGameAnalyse1.CreateWhenGameStartAndReturn(16);
  550. }
  551. //校准靶子
  552. public void CreateTargetObject2D() {
  553. GameObject targetObject2DPrefab = Resources.Load<GameObject>("TargetObject2D");
  554. targetObject2D = Instantiate(targetObject2DPrefab, UI);
  555. }
  556. // 销毁 UIManager 实例
  557. public void DestroyUIManager()
  558. {
  559. if (UIManager._ins != null)
  560. {
  561. Destroy(UIManager._ins.gameObject); // 销毁 UIManager 实例
  562. uiManagerInstance = null;
  563. }
  564. }
  565. /// <summary>
  566. /// 射击次数
  567. /// </summary>
  568. /// <param name="count"></param>
  569. public void onShootCount(int count)
  570. {
  571. userGameAnalyse1.changeShootingCount(count);
  572. }
  573. /// <summary>
  574. /// 上传分数到服务器
  575. /// </summary>
  576. public void onUploadScore()
  577. {
  578. if (_score > 0)
  579. {
  580. Debug.Log("上传的积分为:" + _score);
  581. RankComp.Instance.uploadSinglePlayerGameRes(_score);
  582. _score = 0;
  583. }
  584. }
  585. #endregion
  586. }