GamingManager.cs 32 KB

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