SoundGameController.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using System.Collections;
  2. using UnityEngine;
  3. using UnityEngine.InputSystem;
  4. /* * WalkDogs 场景挂载在2D Player上
  5. * SoundGameController.cs
  6. * Author: 2023-10-12
  7. * Description: 音乐游戏控制器
  8. * 1. 读取音轨数据
  9. * 2. 创建音符
  10. * 3. 检测音符点击
  11. */
  12. public class SoundGameController : MonoBehaviour
  13. {
  14. SoundTrackManager soundTrackManager = new();
  15. GameObject notePrefabSwipe, notePrefabTap;
  16. float gameStartTime;
  17. float GameEndTime;
  18. // 游戏得分统计
  19. int score, combo, maxCombo, NGCombo, perfectCount, goodCount, poorCount, missCount, totalCount;
  20. // TapOrSwipe 触控检测
  21. Vector2 pressDownPosition = new Vector2(0, 0);
  22. Vector2 pressUpPosition = new Vector2(0, 0);
  23. float pressDownTime = 0f;
  24. float pressUpTime = 0f;
  25. // Start is called once before the first execution of Update after the MonoBehaviour is created
  26. void Start()
  27. {
  28. TextAsset soundTrackJson = Resources.Load<TextAsset>("WalkDogs/SoundTrack/track_1");
  29. if (soundTrackJson != null)
  30. {
  31. string soundTrackString = soundTrackJson.text;
  32. soundTrackManager.ImportFromJson(soundTrackString);
  33. soundTrackManager.GenRandomActions();
  34. // soundTrackManager.speed = 4;
  35. }
  36. notePrefabSwipe = Resources.Load<GameObject>("WalkDogs/Note/NoteSwipe");
  37. notePrefabTap = Resources.Load<GameObject>("WalkDogs/Note/NoteTap");
  38. StartCoroutine(PlaySoundGame());
  39. }
  40. // Update is called once per frame
  41. void Update()
  42. {
  43. }
  44. IEnumerator PlaySoundGame()
  45. {
  46. // 加载音乐
  47. AudioClip audioClip = Resources.Load<AudioClip>(soundTrackManager.soundTrack);
  48. AudioSource audioSource = gameObject.AddComponent<AudioSource>();
  49. audioSource.clip = audioClip;
  50. audioSource.Play();
  51. gameStartTime = Time.time;
  52. GameEndTime = gameStartTime + soundTrackManager.length;
  53. while (Time.time < GameEndTime)
  54. {
  55. // 用于提前n秒创建音符
  56. foreach (var note in soundTrackManager.soundAction)
  57. {
  58. if (!note.isActive && Time.time >= (note.time - GameData.noteStartLeadTime))
  59. {
  60. note.isActive = true;
  61. CreateNote(note.time, note.action, soundTrackManager.soundAction.IndexOf(note).ToString());
  62. continue;
  63. }
  64. }
  65. // 检测音符是否超时未被点击
  66. foreach (var note in soundTrackManager.soundAction)
  67. {
  68. float TapTimeDeadline = note.time + gameStartTime + 0.35f; // 计算点击事件超时
  69. if (note.isActive && !note.isTapped && Time.time > TapTimeDeadline)
  70. {
  71. note.isTapped = true;
  72. missCount++;
  73. NGCombo++;
  74. Debug.Log("Miss!" + Time.time + " Tap time deadline: " + TapTimeDeadline + " total miss:" + missCount);
  75. Debug.Log("index of note:" + soundTrackManager.soundAction.IndexOf(note));
  76. break;
  77. }
  78. }
  79. // 检测游戏是否结束并统计分数
  80. totalCount = perfectCount + goodCount + poorCount + missCount;
  81. if (totalCount == soundTrackManager.soundAction.Count)
  82. {
  83. GameEndTime = Time.time;
  84. Debug.Log("Game Over!");
  85. Debug.Log($"Perfect: {perfectCount}, Good: {goodCount}, Poor: {poorCount}, Miss: {missCount}");
  86. Debug.Log($"Total Count: {totalCount}");
  87. Debug.Log($"Score: {score}");
  88. Debug.Log($"Combo: {combo}");
  89. Debug.Log($"Max Combo: {maxCombo}");
  90. // 结束游戏
  91. break; // 跳出 while 循环
  92. }
  93. // 当NGCombo大于5时,播放音效提示
  94. if (NGCombo > 5)
  95. {
  96. SoundGameEffectController.Instance.PlaySoundEffect(0);
  97. NGCombo = 0;
  98. }
  99. yield return new WaitForSeconds(0.01f);
  100. }
  101. yield return null;
  102. }
  103. private void CreateNote(float hitTime, string action, string noteName)
  104. {
  105. GameObject note;
  106. if (action == "tap")
  107. {
  108. note = Instantiate(notePrefabTap);
  109. }
  110. else
  111. {
  112. note = Instantiate(notePrefabSwipe);
  113. }
  114. note.gameObject.name = "note_" + noteName;
  115. NoteController noteController = note.GetComponent<NoteController>();
  116. noteController.speed = soundTrackManager.speed;
  117. noteController.hitTime = hitTime;
  118. noteController.action = action;
  119. }
  120. // 触控检测,检测通过按下和和抬起的触控点位置计算点击或者上下左右滑动
  121. public void TapOrSwipe(InputAction.CallbackContext context)
  122. {
  123. if (context.phase == InputActionPhase.Started)
  124. {
  125. pressDownPosition = Pointer.current.position.ReadValue();
  126. pressDownTime = Time.time;
  127. return;
  128. }
  129. if (context.phase == InputActionPhase.Canceled)
  130. {
  131. pressUpPosition = Pointer.current.position.ReadValue();
  132. pressUpTime = Time.time;
  133. float deltaX = pressUpPosition.x - pressDownPosition.x;
  134. float deltaY = pressUpPosition.y - pressDownPosition.y;
  135. float distance = Mathf.Sqrt(deltaX * deltaX + deltaY * deltaY);
  136. // Debug.Log($"deltaX: {deltaX}, deltaY: {deltaY}, distance: {distance}");
  137. float timeDelta = pressUpTime - pressDownTime;
  138. string action;
  139. if (timeDelta > 0.2f)
  140. {
  141. return;
  142. }
  143. else
  144. {
  145. if (distance < 20f)
  146. {
  147. action = "tap";
  148. }
  149. else
  150. {
  151. if (Mathf.Abs(deltaX) > Mathf.Abs(deltaY))
  152. {
  153. if (deltaX > 0)
  154. {
  155. action = "right";
  156. }
  157. else
  158. {
  159. action = "left";
  160. }
  161. }
  162. else
  163. {
  164. if (deltaY > 0)
  165. {
  166. action = "up";
  167. }
  168. else
  169. {
  170. action = "down";
  171. }
  172. }
  173. }
  174. }
  175. TouchResponse touchResponse = new TouchResponse(action, pressUpTime);
  176. // Debug.Log($"TouchResponse: {touchResponse.action}, {touchResponse.time}");
  177. // 检测点击的音符
  178. ScoreCheck(touchResponse);
  179. }
  180. return;
  181. }
  182. private void ScoreCheck(TouchResponse touchResponse)
  183. {
  184. if (touchResponse != null)
  185. {
  186. foreach (var note in soundTrackManager.soundAction)
  187. {
  188. float TapTimeDelta = Mathf.Abs(touchResponse.time - (note.time + gameStartTime)); // 计算点击时间和音符时间的差值
  189. if (note.isActive && !note.isTapped && TapTimeDelta < 0.3f)
  190. {
  191. note.isTapped = true;
  192. if (touchResponse.action == note.action)
  193. {
  194. if (TapTimeDelta < 0.1f)
  195. {
  196. score += 100;
  197. combo++;
  198. if (combo > maxCombo)
  199. {
  200. maxCombo = combo;
  201. }
  202. perfectCount++;
  203. NGCombo = 0;
  204. Debug.Log("Perfect!" + Time.time + " total perfect:" + perfectCount);
  205. string noteName = soundTrackManager.soundAction.IndexOf(note).ToString();
  206. DestroyNote(noteName);
  207. }
  208. else if (TapTimeDelta < 0.2f)
  209. {
  210. score += 30;
  211. combo = 0;
  212. goodCount++;
  213. NGCombo = 0;
  214. Debug.Log("Good!" + Time.time + " total good:" + goodCount);
  215. string noteName = soundTrackManager.soundAction.IndexOf(note).ToString();
  216. DestroyNote(noteName);
  217. }
  218. else
  219. {
  220. score += 10;
  221. combo = 0;
  222. poorCount++;
  223. NGCombo++;
  224. Debug.Log("Poor!" + Time.time + " total poor:" + poorCount);
  225. }
  226. }
  227. else
  228. {
  229. combo = 0;
  230. missCount++;
  231. NGCombo++;
  232. Debug.Log("Wrong!" + Time.time + " total miss:" + missCount);
  233. }
  234. Debug.Log("index of note:" + soundTrackManager.soundAction.IndexOf(note));
  235. break;
  236. }
  237. }
  238. }
  239. }
  240. private void DestroyNote(string noteName)
  241. {
  242. GameObject note = GameObject.Find("note_" + noteName);
  243. if (note != null)
  244. {
  245. Destroy(note);
  246. }
  247. else
  248. {
  249. Debug.Log("Note not found: " + noteName);
  250. }
  251. }
  252. }
  253. public class TouchResponse
  254. {
  255. public string action = ""; // 触控动作 up, down, left, right, tap, none(表示无效)
  256. public float time;
  257. public TouchResponse(string action, float time)
  258. {
  259. this.action = action;
  260. this.time = time;
  261. }
  262. }