GamingManager.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. using o0.Num;
  2. using o0.Wave.RealTime.Old;
  3. using Org.BouncyCastle.Security;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.WebSockets;
  8. using TMPro;
  9. using UnityEngine;
  10. using UnityEngine.UI;
  11. public enum EndGameReason
  12. {
  13. UserExit,
  14. GameOver,
  15. }
  16. public class GamingManager : MonoBehaviour
  17. {
  18. private SmartBowManager bowManager;
  19. private AudioManager audioManager;
  20. [SerializeField] private AudioSource BowFireAudio;
  21. [SerializeField] private AudioSource LooseLifeAudio;
  22. [SerializeField] private GameObject FruitPrefab;
  23. [SerializeField] private GameObject ArrowPrefab;
  24. [SerializeField] private GameObject BulletPrefab;
  25. [SerializeField] private GameObject ComboTextPrefab;
  26. [SerializeField] private GameObject CriticalTextPrefab;
  27. [SerializeField] private GameObject AddLifeTextPrefab;
  28. [SerializeField] private GameObject GamingUIContainer;
  29. [SerializeField] private Image AimingCross_img;
  30. [SerializeField] private GameObject Resume_btn;
  31. [SerializeField] private GameObject Pause_btn;
  32. [SerializeField] private GameObject Exit_btn;
  33. [SerializeField] private Image Life_0_img;
  34. [SerializeField] private Image Life_1_img;
  35. [SerializeField] private Image Life_2_img;
  36. [SerializeField] private TextMeshProUGUI ScoreText;
  37. [SerializeField] private CannonController Cannon;
  38. [SerializeField] private GameObject FullscreenClearBubble;
  39. [SerializeField] private int StartScores;
  40. private int uploadScore;//需要上传的分数
  41. [SerializeField] private float AimingCrossPosMultiplier = 1f;
  42. [SerializeField] private Camera Cam;
  43. //子弹部分
  44. [SerializeField] private BulletManager bulletManager;
  45. //是否是子弹初始的状态,
  46. public bool isBulletStatus { get; set; } = false;
  47. public const float ArrowSpeedMultiplier = 8.0f;
  48. public const float GravityMultiplier = 2.5f;
  49. private Quaternion CurrentRotation;
  50. private int Scores;
  51. private int Combos;
  52. private int Life;
  53. private bool bGameStarted;
  54. private bool bGamePaused;
  55. // FrozenBanana related variables
  56. private bool bFreeze;
  57. private bool bFreezing;
  58. private float FreezeTimeEclipsed;
  59. // ComboPomegarante related variables
  60. private bool bEnterComboTime;
  61. private bool bComboTime;
  62. private float ComboTimeEclipsed;
  63. FruitBehavior ActiveComboPomegarante;
  64. List<Vector3> FruitVelocityCache_Linear = new List<Vector3>();
  65. List<Vector3> FruitVelocityCache_Angular = new List<Vector3>();
  66. private float MakeNewWaveCountdown;
  67. private List<GameObject> FruitsInField = new List<GameObject>();
  68. private List<FruitType> FruitsPendingSpawn = new List<FruitType>();
  69. private float TimeSinceLastFruitSpawn = 0f;
  70. public delegate void GameEndDelegate(EndGameReason reason, int scores);
  71. public event GameEndDelegate OnGameEnd;
  72. private int FruitWaves = 0;
  73. private Vector2 ScreenMidPoint;
  74. private float FireCooldownTime_Current = 0f;
  75. private const float FireCooldownTime = 0.5f;
  76. UserGameAnalyse1 userGameAnalyse1;
  77. //射箭状态下
  78. private bool bAddCountScore = false;
  79. private void Awake()
  80. {
  81. audioManager = gameObject.GetComponent<AudioManager>();
  82. Debug.Assert(audioManager);
  83. bowManager = gameObject.GetComponent<SmartBowManager>();
  84. Debug.Assert(bowManager);
  85. Debug.Assert(Cannon);
  86. ScreenMidPoint = new Vector2(Screen.width / 2, Screen.height / 2);
  87. //枪模式连接的情况下需要判断子弹
  88. isBulletStatus = BluetoothAim.ins && BluetoothAim.ins.isMainConnectToGun();
  89. if (!isBulletStatus)
  90. {
  91. bulletManager.gameObject.SetActive(false);
  92. }
  93. }
  94. // Start is called before the first frame update
  95. void Start()
  96. {
  97. // byte[] dataToDecrypt = { 0x5A, 0xD4, 0x80, 0xA2, 0xB3, 0x03, 0x5D };
  98. // byte[] dataToDecrypt = { 0x5A, 0x76, 0xD1, 0x02, 0xEB, 0x8E, 0x5D };
  99. // Decryptor.GetResponseStr(dataToDecrypt);
  100. Resume_btn.GetComponentInChildren<Button>().onClick.AddListener(ResumeGame);
  101. Pause_btn.GetComponentInChildren<Button>().onClick.AddListener(PauseGame);
  102. Exit_btn.GetComponentInChildren<Button>().onClick.AddListener(ExitGame);
  103. if (ShootCheck.ins) {
  104. ShootCheck.ins.OnGameShoot += SmartBowFireArrow;
  105. ShootCheck.ins.OnGameUpdateTheMagazine += UpdateTheMagazine;
  106. }
  107. AimingCross_img.gameObject.SetActive(false);
  108. Resume_btn.gameObject.SetActive(false);
  109. ShowGamingUI(false);
  110. Physics.gravity = new Vector3(0.0f, -9.8f * GravityMultiplier, 0.0f);
  111. // Audio track start point correction only
  112. BowFireAudio.timeSamples = 3000;
  113. // Play background music
  114. AudioSource backgroundMusic = gameObject.GetComponent<AudioSource>();
  115. backgroundMusic.clip = audioManager.GetBackgroundMusic();
  116. if (UserSettings.ins.openBGM)
  117. backgroundMusic.Play();
  118. else
  119. backgroundMusic.Stop();
  120. userGameAnalyse1 = UserGameAnalyse1.CreateWhenGameStartAndReturn(15);
  121. }
  122. private void OnDestroy()
  123. {
  124. if (ShootCheck.ins)
  125. {
  126. ShootCheck.ins.OnGameShoot -= SmartBowFireArrow;
  127. ShootCheck.ins.OnGameUpdateTheMagazine -= UpdateTheMagazine;
  128. }
  129. //InfraredDemo.running
  130. //if (!AimHandler.ins.bRuning9Axis()) InfraredDemo.infraredCameraHelper.OnPositionUpdate -= UpdateCrossHairPosition;
  131. if (AimHandler.ins)
  132. {
  133. if (AimHandler.ins.bRuning9Axis())
  134. {
  135. if(CameraToLook.ins)CameraToLook.ins.onParseRotation -= UpdateRotation;
  136. }
  137. else
  138. {
  139. InfraredDemo.infraredCameraHelper.OnPositionUpdate -= UpdateCrossHairPosition;
  140. }
  141. }
  142. }
  143. // Update is called once per frame
  144. void Update()
  145. {
  146. if (FireCooldownTime_Current > 0f)
  147. {
  148. FireCooldownTime_Current = Mathf.Clamp(FireCooldownTime_Current - Time.deltaTime, 0f, FireCooldownTime);
  149. }
  150. if (bGameStarted && !bGamePaused)
  151. {
  152. // listen to mouse firing arrow
  153. if (Input.GetMouseButtonDown(0) && BowCamera.isTouchMode)
  154. {
  155. AimingCross_img.gameObject.GetComponent<RectTransform>().position = Input.mousePosition;
  156. MouseFireArrow(Input.mousePosition);
  157. }
  158. if (FruitsPendingSpawn.Count > 0)
  159. {
  160. if (TimeSinceLastFruitSpawn > GamingValues.SpawnFruitInterval)
  161. {
  162. if (!Cannon.IsFireAnimating())
  163. {
  164. Cannon.TriggerShot();
  165. // Skip reseting fire interval when this is the last pending fruit
  166. // since we need it to fire immediately when firing the first fruit of a new wave
  167. if (FruitsPendingSpawn.Count == 1)
  168. {
  169. TimeSinceLastFruitSpawn = 0f;
  170. }
  171. }
  172. else
  173. {
  174. // do nothing ,wait for cannon fire animation to finish
  175. }
  176. }
  177. else
  178. {
  179. TimeSinceLastFruitSpawn += Time.deltaTime;
  180. }
  181. }
  182. else // No pending spawning fruit
  183. {
  184. if (FruitsInField.Count == 0)
  185. {
  186. if (MakeNewWaveCountdown > 0)
  187. {
  188. MakeNewWaveCountdown -= Time.deltaTime;
  189. }
  190. else
  191. {
  192. MakeFruitsWave();
  193. MakeNewWaveCountdown = GamingValues.MakeNewWaveCountdown;
  194. }
  195. }
  196. }
  197. // update aiming cross position
  198. if (BowCamera.isTouchMode == false && AimHandler.ins.bRuning9Axis())//!InfraredDemo.running
  199. {
  200. Vector3 raw_screen_pos = Cam.WorldToScreenPoint(Cam.transform.position + (CurrentRotation * Vector3.forward));
  201. float dist_to_mid_x = (raw_screen_pos.x - ScreenMidPoint.x) * AimingCrossPosMultiplier;
  202. float dist_to_mid_y = (raw_screen_pos.y - ScreenMidPoint.y) * AimingCrossPosMultiplier;
  203. Vector3 scrren_pos = new Vector3(Mathf.Clamp((dist_to_mid_x + ScreenMidPoint.x), 0f, 2 * ScreenMidPoint.x), Mathf.Clamp((dist_to_mid_y + ScreenMidPoint.y), 0f, 2 * ScreenMidPoint.y), 1f);
  204. AimingCross_img.gameObject.GetComponent<RectTransform>().position = scrren_pos;
  205. }
  206. // Freeze functionality
  207. if (bFreeze)
  208. {
  209. Time.timeScale = 0.5f;
  210. bFreezing = true;
  211. bFreeze = false;
  212. foreach (var fruit in FruitsInField)
  213. {
  214. fruit.GetComponent<FruitBehavior>().Frost();
  215. }
  216. }
  217. if (bFreezing)
  218. {
  219. // Freeze visual effect
  220. float freeze_alpha;
  221. if (FreezeTimeEclipsed < 0.1f)
  222. {
  223. freeze_alpha = Mathf.Lerp(0f, 0.5f, FreezeTimeEclipsed / 0.1f);
  224. }
  225. else
  226. {
  227. freeze_alpha = Mathf.Lerp(0.5f, 0f, (FreezeTimeEclipsed - 0.1f) / (GamingValues.FreezeTime - 0.1f));
  228. }
  229. //MeshRenderer renderer = IceCube.GetComponent<MeshRenderer>();
  230. //renderer.material.SetFloat("_Cutoff", freeze_alpha);
  231. Cam.GetComponent<FrostEffect>().FrostAmount = freeze_alpha;
  232. FreezeTimeEclipsed += (Time.deltaTime / Time.timeScale); // deltaTime is scaled by timeScale, divide it by timeScale will fix it
  233. if (FreezeTimeEclipsed >= GamingValues.FreezeTime)
  234. {
  235. Time.timeScale = 1.0f;
  236. FreezeTimeEclipsed = 0f;
  237. bFreezing = false;
  238. foreach (var fruit in FruitsInField)
  239. {
  240. fruit.GetComponent<FruitBehavior>().UnFrost();
  241. }
  242. }
  243. }
  244. // ComboTime functionality
  245. if (bEnterComboTime)
  246. {
  247. bComboTime = true;
  248. bEnterComboTime = false;
  249. ComboTimeEclipsed = 0f;
  250. }
  251. if (bComboTime)
  252. {
  253. ComboTimeEclipsed += Time.deltaTime;
  254. if (ComboTimeEclipsed > GamingValues.ComboHitTime)
  255. {
  256. bComboTime = false;
  257. ComboTimeEclipsed = 0f;
  258. foreach (var f in FruitsInField)
  259. {
  260. FruitBehavior fr = f.GetComponent<FruitBehavior>();
  261. fr.bMoveAlongTrajectory = true;
  262. }
  263. FruitVelocityCache_Linear.Clear();
  264. FruitVelocityCache_Angular.Clear();
  265. DestroyFruit(ActiveComboPomegarante);
  266. ActiveComboPomegarante = null;
  267. }
  268. else
  269. {
  270. foreach (var f in FruitsInField)
  271. {
  272. FruitBehavior fr = f.GetComponent<FruitBehavior>();
  273. fr.bMoveAlongTrajectory = false;
  274. }
  275. }
  276. }
  277. }
  278. }
  279. public void StartGame()
  280. {
  281. Debug.Assert(FruitsInField.Count == 0);
  282. //InfraredDemo.running
  283. if (AimHandler.ins) {
  284. if (AimHandler.ins.bRuning9Axis())
  285. {
  286. CameraToLook.ins.onParseRotation += UpdateRotation;
  287. }
  288. else
  289. {
  290. InfraredDemo.infraredCameraHelper.OnPositionUpdate += UpdateCrossHairPosition;
  291. }
  292. }
  293. Scores = StartScores;
  294. uploadScore = Scores;
  295. ScoreText.text = "Scores : " + Scores;
  296. Combos = 0;
  297. MakeNewWaveCountdown = GamingValues.MakeNewWaveCountdown;
  298. Life = GamingValues.LifeCount;
  299. UpdateLife(false);
  300. bGameStarted = true;
  301. //if (true/*bowManager.IsSmartBowConnected()*/)
  302. //{
  303. // AimingCross_img.gameObject.SetActive(true);
  304. //}
  305. AimingCross_img.gameObject.SetActive(true);
  306. this.GetComponent<OverallLogics>().SetCrosshairOutLight();
  307. ShowGamingUI(true);
  308. GamingValues.ResetPomegranateSpawnedCount();
  309. Cannon.OnCannonFire += SpawnAFruit;
  310. FruitWaves = 0;
  311. //打水果的子弹,在新开一局游戏时,要更新为满弹的状态
  312. UpdateTheMagazine();
  313. }
  314. public void PauseGame()
  315. {
  316. bGamePaused = true;
  317. AimingCross_img.gameObject.SetActive(false);
  318. Pause_btn.gameObject.SetActive(false);
  319. Resume_btn.gameObject.SetActive(true);
  320. Time.timeScale = 0f;
  321. }
  322. public void ResumeGame()
  323. {
  324. bGamePaused = false;
  325. AimingCross_img.gameObject.SetActive(true);
  326. Pause_btn.gameObject.SetActive(true);
  327. Resume_btn.gameObject.SetActive(false);
  328. Time.timeScale = 1f;
  329. }
  330. public bool IsGameStarted()
  331. {
  332. return bGameStarted;
  333. }
  334. public bool IsGamePaused()
  335. {
  336. return bGamePaused;
  337. }
  338. private void MakeFruitsWave()
  339. {
  340. // Reset Normal fruit unique funcionality
  341. FruitTypeList fruit_list = GetComponent<FruitTypeList>();
  342. Debug.Assert(fruit_list != null);
  343. fruit_list.ResetUniqueNormalIndex();
  344. Debug.Assert(FruitsPendingSpawn.Count == 0);
  345. if (FruitWaves < 5)
  346. {
  347. switch (FruitWaves)
  348. {
  349. case 0:
  350. FruitsPendingSpawn.Add(FruitType.Normal);
  351. break;
  352. case 1:
  353. FruitsPendingSpawn.Add(FruitType.Normal);
  354. FruitsPendingSpawn.Add(FruitType.Bomb);
  355. break;
  356. case 2:
  357. FruitsPendingSpawn.Add(FruitType.Normal);
  358. FruitsPendingSpawn.Add(FruitType.Normal);
  359. break;
  360. case 3:
  361. FruitsPendingSpawn.Add(FruitType.Normal);
  362. FruitsPendingSpawn.Add(FruitType.Normal);
  363. FruitsPendingSpawn.Add(FruitType.Normal);
  364. FruitsPendingSpawn.Add(FruitType.FrozenBanana);
  365. break;
  366. case 4:
  367. FruitsPendingSpawn.Add(FruitType.Normal);
  368. FruitsPendingSpawn.Add(FruitType.Normal);
  369. FruitsPendingSpawn.Add(FruitType.Normal);
  370. FruitsPendingSpawn.Add(FruitType.Normal);
  371. FruitsPendingSpawn.Add(FruitType.RainbowApple);
  372. break;
  373. default:
  374. break;
  375. }
  376. }
  377. else
  378. {
  379. int normal_fruit_count = GamingValues.GetSpawnNum(Scores);
  380. bool bContain_bomb = GamingValues.DoesSpawnBomb(Scores);
  381. bool doesSpawnPome = GamingValues.DoesSpawnComboPomegranate(Scores);
  382. // if spawn FrozenBanana or RainbowApple, 0 - no spawn, 1 - frozen banana, 2 - rainbow apple
  383. int doesSpawnSpecial = 0;
  384. int specialAddition = 0;
  385. if (normal_fruit_count == 3)
  386. {
  387. specialAddition++;
  388. doesSpawnSpecial = 1;
  389. }
  390. else if (normal_fruit_count >= 4)
  391. {
  392. specialAddition++;
  393. doesSpawnSpecial = 2;
  394. }
  395. else
  396. {
  397. doesSpawnSpecial = 0;
  398. }
  399. if (doesSpawnPome)
  400. {
  401. specialAddition++;
  402. }
  403. for (int i = 0; i < normal_fruit_count + specialAddition; i++)
  404. {
  405. if (i == 0) // for the first fruit, spawn bomb if a bomb is included
  406. {
  407. FruitsPendingSpawn.Add(bContain_bomb ? FruitType.Bomb : FruitType.Normal);
  408. }
  409. else if (i == 1 && doesSpawnPome) // for the second, we see if a combo pomegranate is included, since if there is one, the minimum count of fruits is 2
  410. {
  411. FruitsPendingSpawn.Add(FruitType.ComboPomegranate);
  412. }
  413. else if (i == 2 && doesSpawnSpecial > 0) // the third one is last chance for special fruits, check for frozen banana and rainbow apple, they do not appear at the same time, and if there is one, the minimum count must be above 3
  414. {
  415. FruitsPendingSpawn.Add(doesSpawnSpecial == 1 ? FruitType.FrozenBanana : FruitType.RainbowApple);
  416. }
  417. else // all special fruits spawning posibility is checked when spawning the first 3 fruits, the rest must be normal
  418. {
  419. FruitsPendingSpawn.Add(FruitType.Normal);
  420. }
  421. }
  422. }
  423. FruitWaves++;
  424. }
  425. private void SpawnAFruit()
  426. {
  427. float speed_x = Random.Range(-100f, 100f);
  428. float speed_y = Random.Range(350f, 450f);
  429. Debug.Assert(FruitsPendingSpawn.Count > 0);
  430. GameObject newFruit = Instantiate(FruitPrefab, Cannon.GetFiringPoint(), Quaternion.identity);
  431. FruitBehavior fb = newFruit.GetComponent<FruitBehavior>();
  432. // Get a random target position with a small random range along x axis and lower half y axis
  433. Vector3 target = Cam.transform.position + new Vector3(Random.Range(-7f, 7f), Random.Range(-10f, -2f), 0f);
  434. float fruit_lifetime = GamingValues.GetFruitLifetime(FruitWaves, Scores);
  435. fb.Init(FruitsPendingSpawn[0], this, Cannon.GetFiringPoint(), target, fruit_lifetime);
  436. FruitsPendingSpawn.RemoveAt(0);
  437. fb.OnArrive += AFruitArrived;
  438. fb.OnHitEvent += OnFruitHit;
  439. FruitsInField.Add(newFruit);
  440. }
  441. private void AFruitArrived(FruitBehavior fb)
  442. {
  443. if (fb.GetFruitType() != FruitType.Bomb)
  444. {
  445. if (UpdateLife(true))
  446. {
  447. DelayEndGame(EndGameReason.GameOver, 2f);
  448. }
  449. FruitsInField.Remove(fb.gameObject);
  450. DestroyFruit(fb);
  451. SpawnStain(fb.JuiceStain, fb.gameObject.transform.position);
  452. }
  453. else
  454. {
  455. fb.gameObject.transform.position = new Vector3(0f, 0f, 10f);
  456. DestroyFruit(fb);
  457. DelayEndGame(EndGameReason.GameOver, 2f);
  458. }
  459. }
  460. private void EndGame(EndGameReason reason)
  461. {
  462. Cannon.ResetPos();
  463. Cannon.OnCannonFire -= SpawnAFruit;
  464. //CameraToLook.ins.onParseRotation -= UpdateRotation;
  465. //if (InfraredDemo.running) InfraredDemo.infraredCameraHelper.OnPositionUpdate -= UpdateCrossHairPosition;
  466. if (AimHandler.ins)
  467. {
  468. if (AimHandler.ins.bRuning9Axis())
  469. {
  470. CameraToLook.ins.onParseRotation -= UpdateRotation;
  471. }
  472. else
  473. {
  474. InfraredDemo.infraredCameraHelper.OnPositionUpdate -= UpdateCrossHairPosition;
  475. }
  476. }
  477. // clear all fruits in the field
  478. foreach (var fruit in FruitsInField)
  479. {
  480. Destroy(fruit);
  481. }
  482. FruitsInField.Clear();
  483. if (IsGamePaused())
  484. {
  485. ResumeGame();
  486. }
  487. bGameStarted = false;
  488. ShowGamingUI(false);
  489. //水果上传分数
  490. onUploadScore();
  491. OnGameEnd.Invoke(reason, Scores);
  492. }
  493. //水果上传分数到服务器
  494. void onUploadScore() {
  495. if (uploadScore > 0)
  496. {
  497. Debug.Log("水果游戏上传的积分为:" + uploadScore);
  498. RankComp.Instance.uploadSinglePlayerGameRes(uploadScore);
  499. uploadScore = 0;
  500. }
  501. }
  502. /**
  503. * 点击结束按钮再触发
  504. */
  505. public void onShowResultView() {
  506. onUploadScore();
  507. //结束游戏页面
  508. userGameAnalyse1.showResultView(()=> {
  509. UnityEngine.SceneManagement.SceneManager.LoadScene("Home", UnityEngine.SceneManagement.LoadSceneMode.Single);
  510. });
  511. }
  512. private void DelayEndGame(EndGameReason reason, float wait_secs)
  513. {
  514. StartCoroutine(DelayEndGame_CR(reason, wait_secs));
  515. }
  516. private IEnumerator DelayEndGame_CR(EndGameReason reason, float wait_secs)
  517. {
  518. yield return new WaitForSeconds(wait_secs);
  519. EndGame(reason);
  520. }
  521. public static void DelayDestroy(MonoBehaviour excutor, GameObject to_destroy, float wait_secs)
  522. {
  523. excutor.StartCoroutine(DelayDestroy_CR(to_destroy, wait_secs));
  524. }
  525. private static IEnumerator DelayDestroy_CR(GameObject to_destroy, float wait_secs)
  526. {
  527. yield return new WaitForSeconds(wait_secs);
  528. if (to_destroy)
  529. Destroy(to_destroy);
  530. }
  531. public void ExitGame()
  532. {
  533. EndGame(EndGameReason.UserExit);
  534. }
  535. float maxDistance = 200f; // 最大检测距离
  536. [SerializeField] LayerMask hitLayers; // 碰撞检测的层
  537. /// <summary>
  538. /// Gun 模式下:射击的射线检测
  539. /// </summary>
  540. /// <param name="arrowBehavior"></param>
  541. /// <param name="spawnPos"></param>
  542. /// <param name="_direction"></param>
  543. /// <param name="_bulletSpeed"></param>
  544. void CheckCollision(ArrowBehavior arrowBehavior, Vector3 spawnPos, Vector3 _direction, int _bulletSpeed)
  545. {
  546. // 可视化射线
  547. Debug.DrawRay(spawnPos, _direction * maxDistance, Color.red, 2.0f);
  548. RaycastHit[] hits = Physics.RaycastAll(spawnPos, _direction, maxDistance, hitLayers);
  549. // 遍历所有击中的物体
  550. foreach (RaycastHit hit in hits)
  551. {
  552. //Debug.Log("Hit: " + hit.collider.gameObject.name);
  553. if (hit.collider.CompareTag("StaticCollisionScene"))
  554. {
  555. // 计算飞行时间
  556. float distance = hit.distance;
  557. float flightTime = distance / _bulletSpeed;
  558. // 生成弹坑
  559. // 处理碰撞
  560. // 延时生成弹坑图片
  561. StartCoroutine(CreateBulletHole(arrowBehavior, hit, flightTime));
  562. // Debug.Log("hit.transform.tag1 :" + hit.transform.tag);
  563. }
  564. //这里暂时忽略了水果运动和子弹位置,子弹位置速度快。
  565. if (hit.collider.CompareTag("Fruit"))
  566. {
  567. // Debug.Log("hit.transform.tag2 :" + hit.transform.tag);
  568. //Debug.Log("hit.transform.name :" + hit.transform.name);
  569. //处理水果分数
  570. FruitBehavior fruitBehavior = hit.transform.gameObject.GetComponent<FruitBehavior>();
  571. fruitBehavior.OnHitCollision(hit.collider, arrowBehavior);
  572. }
  573. }
  574. //if (Input.GetKeyDown(KeyCode.Alpha1))
  575. //{
  576. // UnityEditor.EditorApplication.isPaused = true;
  577. //}
  578. //if (Input.GetKeyDown(KeyCode.Alpha2))
  579. //{
  580. // UnityEditor.EditorApplication.isPaused = false;
  581. //}
  582. }
  583. IEnumerator CreateBulletHole(ArrowBehavior arrowBehavior,RaycastHit hit, float delay)
  584. {
  585. // 等待飞行时间
  586. yield return new WaitForSeconds(delay);
  587. // 在碰撞点生成弹坑预制体
  588. arrowBehavior.CreateBulletHole(hit.point, hit.normal, hit.transform);
  589. //Debug.Log("Hit object2: " + hit.collider.name);
  590. }
  591. private void FireArrow(float speed, Vector3 dir,bool bAddCount = false)
  592. {
  593. bAddCountScore = bAddCount;
  594. if (bGameStarted && !bGamePaused && FireCooldownTime_Current == 0f)
  595. {
  596. FireCooldownTime_Current = FireCooldownTime;
  597. //枪模式连接的情况下需要判断子弹
  598. if (isBulletStatus)
  599. {
  600. if (bulletManager.bulletZeroNotDelete()) return;
  601. //发射消耗子弹
  602. bulletManager.FireBullet();
  603. }
  604. Vector3 spawnPos = Cam.transform.position + dir;
  605. GameObject arrow = Instantiate(GlobalData.MyDeviceMode == DeviceMode.Archery? ArrowPrefab: BulletPrefab, spawnPos, Quaternion.FromToRotation(-Vector3.right, dir));
  606. if (GlobalData.MyDeviceMode == DeviceMode.Archery)
  607. {
  608. arrow.GetComponent<ArrowBehavior>().Init(speed, dir, true,true);
  609. BowFireAudio.clip = audioManager.GetRandomSound(SoundCategory.ArrowFire);
  610. if (UserSettings.ins.openEffect) BowFireAudio.Play();
  611. }
  612. else {
  613. //目前只有gun类型
  614. ArrowBehavior _arrowBehavior = arrow.GetComponent<ArrowBehavior>();
  615. int _bulletSpeed = 800;
  616. _arrowBehavior.Init(_bulletSpeed, dir.normalized, true, false);
  617. BowFireAudio.clip = audioManager.GetRandomSound(SoundCategory.GunFire);
  618. if (UserSettings.ins.openEffect) BowFireAudio.Play();
  619. CheckCollision(_arrowBehavior,spawnPos, dir.normalized , _bulletSpeed);
  620. //UnityEditor.EditorApplication.isPaused = true;
  621. }
  622. arrow.GetComponent<ArrowBehavior>().OnMissShoot += MissShoot;
  623. //统计射箭次数
  624. if(bAddCount)
  625. userGameAnalyse1.changeShootingCount(1);
  626. }
  627. }
  628. /// <summary>
  629. /// 手枪子弹刷新
  630. /// </summary>
  631. private void UpdateTheMagazine() {
  632. BulletManager.RemoveBulletExternally();
  633. bulletManager.ResetBullets();
  634. }
  635. private void SmartBowFireArrow(float speed)
  636. {
  637. if (Time.time == 0) return;
  638. if (IsGameStarted())
  639. {
  640. if (IsGamePaused()) // if game is paused, fire the smart bow will resume game
  641. {
  642. ResumeGame();
  643. }
  644. else // If game is started and not paused, shoot a arrow
  645. {
  646. Vector3 screenPoint = AimingCross_img.GetComponent<RectTransform>().position;
  647. screenPoint.z = 1;
  648. Vector3 direction = Cam.ScreenToWorldPoint(screenPoint);
  649. FireArrow(speed * ArrowSpeedMultiplier, direction , true);
  650. }
  651. }
  652. else
  653. {
  654. gameObject.GetComponent<OverallLogics>().StartGame();
  655. }
  656. }
  657. private void UpdateRotation(Quaternion q)
  658. {
  659. CurrentRotation = q;
  660. }
  661. private void UpdateCrossHairPosition(Vector2 position)
  662. {
  663. if (AimingCross_img) AimingCross_img.transform.position = position;
  664. }
  665. private void MouseFireArrow(Vector3 screenPos)
  666. {
  667. Vector3 worldPos = Cam.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, 10.0f));
  668. FireArrow(20.0f, worldPos - Cam.transform.position);
  669. }
  670. private void OnFruitHit(FruitBehavior fb, Vector3 hitPoint, bool bCritical)
  671. {
  672. Combos++;
  673. // if this is a ComboPomegranate, ignore critical and combo hit, only gain 1 score per hit
  674. if (fb.GetFruitType() == FruitType.ComboPomegranate)
  675. {
  676. if (GainScore(1))
  677. {
  678. UpdateLife(false);
  679. }
  680. }
  681. else if (bCritical)
  682. {
  683. if (GainScore(10))
  684. {
  685. UpdateLife(false);
  686. }
  687. // display a critical text
  688. GameObject critical = Instantiate(CriticalTextPrefab, GamingUIContainer.transform);
  689. critical.transform.position = Cam.WorldToScreenPoint(hitPoint);
  690. }
  691. else if (Combos > 1) // This combo section handles combo scores addition, text displaying is handled after
  692. {
  693. if (GainScore(5))
  694. {
  695. UpdateLife(false);
  696. }
  697. }
  698. else // A very bland hit, no critical, no combo
  699. {
  700. if (GainScore(5))
  701. {
  702. UpdateLife(false);
  703. }
  704. }
  705. if (Combos > 1) // This combo section handles combo text display
  706. {
  707. // display a combo text
  708. GameObject combo = Instantiate(ComboTextPrefab, GamingUIContainer.transform);
  709. combo.GetComponent<ComboTextBehavior>().SetComboNumber(Combos);
  710. }
  711. if (fb.GetFruitType() == FruitType.FrozenBanana)
  712. {
  713. // enter freeze state
  714. bFreeze = true;
  715. FreezeTimeEclipsed = 0.0f;
  716. DestroyFruit(fb);
  717. }
  718. else if (fb.GetFruitType() == FruitType.ComboPomegranate)
  719. {
  720. ComboPomegaranteBehavior cpb = fb.gameObject.GetComponent<ComboPomegaranteBehavior>();
  721. if (cpb.GetHitCount() == 0)
  722. {
  723. bEnterComboTime = true;
  724. ActiveComboPomegarante = fb;
  725. foreach (var f in FruitsInField)
  726. {
  727. FruitVelocityCache_Linear.Add(f.gameObject.GetComponent<Rigidbody>().velocity);
  728. FruitVelocityCache_Angular.Add(f.gameObject.GetComponent<Rigidbody>().angularVelocity);
  729. }
  730. }
  731. cpb.Hit();
  732. if (cpb.GetHitCount() >= GamingValues.ComboHitLimit)
  733. {
  734. bComboTime = false;
  735. DestroyFruit(fb);
  736. ActiveComboPomegarante = null;
  737. ComboTimeEclipsed = 0f;
  738. foreach (var f in FruitsInField)
  739. {
  740. FruitBehavior fr = f.GetComponent<FruitBehavior>();
  741. fr.bMoveAlongTrajectory = true;
  742. }
  743. }
  744. else
  745. {
  746. // do nothing
  747. }
  748. }
  749. else if (fb.GetFruitType() == FruitType.RainbowApple)
  750. {
  751. Instantiate(FullscreenClearBubble, fb.gameObject.transform.position, Quaternion.identity);
  752. DestroyFruit(fb);
  753. }
  754. else
  755. {
  756. DestroyFruit(fb);
  757. }
  758. }
  759. /// <summary>
  760. /// Gain some scores
  761. /// </summary>
  762. /// <returns> If exceeded another 100 scores, return true, for life recovering test </returns>
  763. private bool GainScore(int score)
  764. {
  765. int last_scores = Scores;
  766. //射箭状态下添加分数
  767. if (bAddCountScore) {
  768. Scores += score;
  769. uploadScore += score;
  770. }
  771. ScoreText.text = "Scores : " + Scores; // update socres display
  772. return ((Scores / 100) == (last_scores / 100) + 1);
  773. }
  774. /// <summary>
  775. /// Add or substract life point by 1
  776. /// </summary>
  777. /// <param name="bDecrease">true for decrease, false for add</param>
  778. /// <returns>return true if life reaches 0</returns>
  779. private bool UpdateLife(bool bDecrease)
  780. {
  781. if (bDecrease)
  782. {
  783. Life--;
  784. if (Life < 0)
  785. {
  786. Life = 0;
  787. }
  788. if (UserSettings.ins.openEffect) LooseLifeAudio.Play();
  789. }
  790. else
  791. {
  792. if (Life < 3)
  793. {
  794. Life++;
  795. GameObject addLife = Instantiate(AddLifeTextPrefab, GamingUIContainer.transform);
  796. }
  797. }
  798. switch (Life)
  799. {
  800. case 0:
  801. Life_0_img.gameObject.SetActive(true);
  802. Life_1_img.gameObject.SetActive(true);
  803. Life_2_img.gameObject.SetActive(true);
  804. return true;
  805. case 1:
  806. Life_0_img.gameObject.SetActive(true);
  807. Life_1_img.gameObject.SetActive(true);
  808. Life_2_img.gameObject.SetActive(false);
  809. return false;
  810. case 2:
  811. Life_0_img.gameObject.SetActive(true);
  812. Life_1_img.gameObject.SetActive(false);
  813. Life_2_img.gameObject.SetActive(false);
  814. return false;
  815. case 3:
  816. Life_0_img.gameObject.SetActive(false);
  817. Life_1_img.gameObject.SetActive(false);
  818. Life_2_img.gameObject.SetActive(false);
  819. return false;
  820. default:
  821. return false;
  822. }
  823. }
  824. private void MissShoot()
  825. {
  826. Combos = 0;
  827. }
  828. private void ShowGamingUI(bool b)
  829. {
  830. GamingUIContainer.SetActive(b);
  831. }
  832. public void DestroyFruit(FruitBehavior fb)
  833. {
  834. FruitsInField.Remove(fb.gameObject);
  835. fb.SmashEffect();
  836. }
  837. public AudioManager GetAudioManager()
  838. {
  839. return audioManager;
  840. }
  841. public void SpawnStain(Sprite stain, Vector3 position3d_ws)
  842. {
  843. GameObject stain_go = Instantiate(new GameObject(), GamingUIContainer.transform);
  844. stain_go.AddComponent<Image>().sprite = stain;
  845. stain_go.transform.position = Cam.WorldToScreenPoint(position3d_ws);
  846. stain_go.transform.localScale = Vector3.one * 8f;
  847. stain_go.AddComponent<StainBehaviour>();
  848. }
  849. }