SoundGameController.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.InputSystem;
  6. /* * WalkDogs 场景挂载在2D Player上
  7. * SoundGameController.cs
  8. * Author: 2023-10-12
  9. * Description: 音乐游戏控制器
  10. * 1. 读取音轨数据
  11. * 2. 创建音符
  12. * 3. 检测音符点击
  13. */
  14. public class SoundGameController : MonoBehaviour
  15. {
  16. SoundTrackManager soundTrackManager = new();
  17. GameObject notePrefabSwipe, notePrefabTap;
  18. GameObject Leaves;
  19. float gameStartTime;
  20. float GameEndTime;
  21. // 游戏得分统计
  22. int score, combo, maxCombo, NGCombo, perfectCount, goodCount, poorCount, missCount, totalCount;
  23. // 游戏数据
  24. string currentDogState = "walking"; // 是否有狗在跑
  25. // TapOrSwipe 触控检测
  26. Vector2 pressDownPosition = new Vector2(0, 0);
  27. Vector2 pressUpPosition = new Vector2(0, 0);
  28. float pressDownTime = 0f;
  29. float pressUpTime = 0f;
  30. // Start is called once before the first execution of Update after the MonoBehaviour is created
  31. void Start()
  32. {
  33. TextAsset soundTrackJson = Resources.Load<TextAsset>("WalkDogs/SoundTrack/track_1");
  34. if (soundTrackJson != null)
  35. {
  36. string soundTrackString = soundTrackJson.text;
  37. soundTrackManager.ImportFromJson(soundTrackString);
  38. soundTrackManager.GenRandomActions();
  39. // soundTrackManager.speed = 4;
  40. }
  41. notePrefabSwipe = Resources.Load<GameObject>("WalkDogs/Note/NoteSwipe");
  42. notePrefabTap = Resources.Load<GameObject>("WalkDogs/Note/NoteTap");
  43. StartCoroutine(PlaySoundGame());
  44. StartCoroutine(DogComponentInstaller());
  45. Leaves = GameObject.Find("Leaves_orange");
  46. StartCoroutine(DogMovementController());
  47. }
  48. // Update is called once per frame
  49. void Update()
  50. {
  51. DogStatusUpdate();
  52. // UpdateAndShowScoreUI();
  53. }
  54. IEnumerator DogComponentInstaller()
  55. {
  56. yield return null;
  57. // 找到所有标签为 "dog" 的 GameObject
  58. GameObject[] dogObjects = GameObject.FindGameObjectsWithTag("dog");
  59. foreach (GameObject dog in dogObjects)
  60. {
  61. // 加载指定的Animator controller
  62. Animator animator = dog.GetComponent<Animator>();
  63. DogProperty dogProperty = new DogProperty();
  64. foreach (var dogProp in UserProperty.dogs)
  65. {
  66. if (dogProp.dog_name == dog.name)
  67. {
  68. dogProperty = dogProp;
  69. break;
  70. }
  71. }
  72. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>(DogBreedController.GetDogAnimationController(dogProperty.breed, "walk_dog"));
  73. animator.runtimeAnimatorController = animatorController;
  74. // 加载Rigidbody
  75. Rigidbody rigidbody = dog.AddComponent<Rigidbody>();
  76. //rigidbody.isKinematic = true;
  77. rigidbody.mass = 10;
  78. rigidbody.linearDamping = 10;
  79. rigidbody.angularDamping = 10;
  80. //rigidbody.freezeRotation = true;
  81. rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;
  82. rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
  83. rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
  84. // 加载box collider
  85. BoxCollider boxCollider = dog.AddComponent<BoxCollider>();
  86. boxCollider.isTrigger = false;
  87. boxCollider.center = new Vector3(0, 0.25f, 0);
  88. boxCollider.size = new Vector3(0.2f, 0.5f, 0.6f);
  89. }
  90. }
  91. IEnumerator PlaySoundGame()
  92. {
  93. // 加载背景
  94. List<string> backgroundList = new List<string>
  95. {
  96. "WalkDogs/Background/bg_1",
  97. "WalkDogs/Background/bg_2",
  98. "WalkDogs/Background/bg_3",
  99. "WalkDogs/Background/bg_4",
  100. };
  101. var Background = GameObject.Find("Background");
  102. MeshRenderer backgroundMeshRenderer = Background.GetComponent<MeshRenderer>();
  103. float lastBackgroundTime;
  104. // 加载音乐
  105. AudioClip audioClip = Resources.Load<AudioClip>(soundTrackManager.soundTrack);
  106. AudioSource audioSource = gameObject.AddComponent<AudioSource>();
  107. audioSource.clip = audioClip;
  108. yield return new WaitForSeconds(2f); // 等待音频加载完成
  109. audioSource.Play();
  110. gameStartTime = Time.time;
  111. GameEndTime = gameStartTime + soundTrackManager.length;
  112. lastBackgroundTime = gameStartTime;
  113. while (Time.time < GameEndTime)
  114. {
  115. // 每隔15秒切换一次背景
  116. if (Time.time - lastBackgroundTime > 15f)
  117. {
  118. lastBackgroundTime = Time.time;
  119. int randomIndex = UnityEngine.Random.Range(0, backgroundList.Count);
  120. string backgroundPath = backgroundList[randomIndex];
  121. Material myMaterial = Resources.Load<Material>(backgroundPath);
  122. if (myMaterial != null)
  123. {
  124. backgroundMeshRenderer.material = myMaterial;
  125. // Debug.Log("Background changed to: " + backgroundPath);
  126. }
  127. else
  128. {
  129. Debug.LogWarning("Background material not found: " + backgroundPath);
  130. }
  131. }
  132. // 用于提前n秒创建音符
  133. foreach (var note in soundTrackManager.soundAction)
  134. {
  135. if (!note.isActive && Time.time >= (gameStartTime + note.time - GameData.noteStartLeadTime))
  136. {
  137. note.isActive = true;
  138. CreateNote(note.time, note.action, soundTrackManager.soundAction.IndexOf(note).ToString());
  139. continue;
  140. }
  141. }
  142. // 检测音符是否超时未被点击
  143. foreach (var note in soundTrackManager.soundAction)
  144. {
  145. float TapTimeDeadline = note.time + gameStartTime + 0.35f; // 计算点击事件超时
  146. if (note.isActive && !note.isTapped && Time.time > TapTimeDeadline)
  147. {
  148. note.isTapped = true;
  149. missCount++;
  150. NGCombo++;
  151. combo = 0; // 重置连击
  152. // Debug.Log("Miss!" + Time.time + " Tap time deadline: " + TapTimeDeadline + " total miss:" + missCount);
  153. // Debug.Log("index of note:" + soundTrackManager.soundAction.IndexOf(note));
  154. break;
  155. }
  156. }
  157. // 检测游戏是否结束并统计分数
  158. totalCount = perfectCount + goodCount + poorCount + missCount;
  159. if (totalCount == soundTrackManager.soundAction.Count)
  160. {
  161. GameEndTime = Time.time;
  162. Debug.Log("Game Over!");
  163. Debug.Log($"Perfect: {perfectCount}, Good: {goodCount}, Poor: {poorCount}, Miss: {missCount}");
  164. Debug.Log($"Total Count: {totalCount}");
  165. Debug.Log($"Score: {score}");
  166. Debug.Log($"Combo: {combo}");
  167. Debug.Log($"Max Combo: {maxCombo}");
  168. // 结束游戏
  169. UpdateAndShowScoreUI();
  170. break; // 跳出 while 循环
  171. }
  172. // 当NGCombo大于5时,播放音效提示
  173. if (NGCombo > 5)
  174. {
  175. SoundGameEffectController.Instance.PlaySoundEffect(0);
  176. NGCombo = 0;
  177. }
  178. yield return new WaitForSeconds(0.01f);
  179. }
  180. yield return null;
  181. }
  182. private void CreateNote(float hitTime, string action, string noteName)
  183. {
  184. GameObject note;
  185. if (action == "tap")
  186. {
  187. note = Instantiate(notePrefabTap);
  188. // Debug.Log("Create Tap Note: " + noteName);
  189. // Debug.Log("Hit Time: " + hitTime + ", Action: " + action);
  190. // Debug.Log("Create Time: " + Time.time);
  191. }
  192. else
  193. {
  194. note = Instantiate(notePrefabSwipe);
  195. // Debug.Log("Create Tap Note: " + noteName);
  196. // Debug.Log("Hit Time: " + hitTime + ", Action: " + action);
  197. // Debug.Log("Create Time: " + Time.time);
  198. }
  199. note.gameObject.name = "note_" + noteName;
  200. NoteController noteController = note.GetComponent<NoteController>();
  201. noteController.speed = soundTrackManager.speed;
  202. noteController.hitTime = hitTime;
  203. noteController.action = action;
  204. }
  205. // 触控检测,检测通过按下和和抬起的触控点位置计算点击或者上下左右滑动
  206. public void TapOrSwipe(InputAction.CallbackContext context)
  207. {
  208. if (context.phase == InputActionPhase.Started)
  209. {
  210. pressDownPosition = Pointer.current.position.ReadValue();
  211. pressDownTime = Time.time;
  212. return;
  213. }
  214. if (context.phase == InputActionPhase.Canceled)
  215. {
  216. pressUpPosition = Pointer.current.position.ReadValue();
  217. pressUpTime = Time.time;
  218. float deltaX = pressUpPosition.x - pressDownPosition.x;
  219. float deltaY = pressUpPosition.y - pressDownPosition.y;
  220. float distance = Mathf.Sqrt(deltaX * deltaX + deltaY * deltaY);
  221. // Debug.Log($"deltaX: {deltaX}, deltaY: {deltaY}, distance: {distance}");
  222. float timeDelta = pressUpTime - pressDownTime;
  223. string action;
  224. if (timeDelta > 0.2f)
  225. {
  226. return;
  227. }
  228. else
  229. {
  230. if (distance < 20f)
  231. {
  232. action = "tap";
  233. }
  234. else
  235. {
  236. if (Mathf.Abs(deltaX) > Mathf.Abs(deltaY))
  237. {
  238. if (deltaX > 0)
  239. {
  240. action = "right";
  241. }
  242. else
  243. {
  244. action = "left";
  245. }
  246. }
  247. else
  248. {
  249. if (deltaY > 0)
  250. {
  251. action = "up";
  252. }
  253. else
  254. {
  255. action = "down";
  256. }
  257. }
  258. }
  259. }
  260. TouchResponse touchResponse = new TouchResponse(action, pressUpTime);
  261. // Debug.Log($"TouchResponse: {touchResponse.action}, {touchResponse.time}");
  262. // 检测点击的音符
  263. ScoreCheck(touchResponse);
  264. }
  265. return;
  266. }
  267. private void ScoreCheck(TouchResponse touchResponse)
  268. {
  269. if (touchResponse != null)
  270. {
  271. foreach (var note in soundTrackManager.soundAction)
  272. {
  273. float TapTimeDelta = Mathf.Abs(touchResponse.time - (note.time + gameStartTime)); // 计算点击时间和音符时间的差值
  274. if (note.isActive && !note.isTapped && TapTimeDelta < 0.3f)
  275. {
  276. note.isTapped = true;
  277. if (touchResponse.action == note.action)
  278. {
  279. if (TapTimeDelta < 0.1f)
  280. {
  281. score += 100;
  282. combo++;
  283. if (combo > maxCombo)
  284. {
  285. maxCombo = combo;
  286. }
  287. perfectCount++;
  288. NGCombo = 0;
  289. // Debug.Log("Perfect!" + Time.time + " total perfect:" + perfectCount);
  290. string noteName = soundTrackManager.soundAction.IndexOf(note).ToString();
  291. DestroyNote(noteName);
  292. }
  293. else if (TapTimeDelta < 0.2f)
  294. {
  295. score += 30;
  296. combo = 0;
  297. goodCount++;
  298. NGCombo = 0;
  299. // Debug.Log("Good!" + Time.time + " total good:" + goodCount);
  300. string noteName = soundTrackManager.soundAction.IndexOf(note).ToString();
  301. DestroyNote(noteName);
  302. }
  303. else
  304. {
  305. score += 10;
  306. combo = 0;
  307. poorCount++;
  308. NGCombo++;
  309. // Debug.Log("Poor!" + Time.time + " total poor:" + poorCount);
  310. }
  311. }
  312. else
  313. {
  314. combo = 0;
  315. missCount++;
  316. NGCombo++;
  317. // Debug.Log("Wrong!" + Time.time + " total miss:" + missCount);
  318. }
  319. // Debug.Log("index of note:" + soundTrackManager.soundAction.IndexOf(note));
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. private void DestroyNote(string noteName)
  326. {
  327. GameObject note = GameObject.Find("note_" + noteName);
  328. if (note != null)
  329. {
  330. Destroy(note);
  331. }
  332. else
  333. {
  334. Debug.Log("Note not found: " + noteName);
  335. }
  336. }
  337. // 设置狗的状态
  338. private void DogStatusUpdate()
  339. {
  340. GameObject[] dogObjects = GameObject.FindGameObjectsWithTag("dog");
  341. Debug.Log("combo:" + combo);
  342. // combo = 5; // 这里是为了测试用,实际应该从游戏逻辑中获取当前连击数
  343. if (combo >= 5 && combo < 10)
  344. {
  345. currentDogState = "running";
  346. foreach (GameObject dog in dogObjects)
  347. {
  348. Animator animator = dog.GetComponent<Animator>();
  349. if (animator != null)
  350. {
  351. animator.SetTrigger("run");
  352. SetLeavesParticleSpeed(5.0f, 10.0f); // 设置leaves粒子效果的Start Speed 和 Rate over Time
  353. // animator.Play("Run");
  354. }
  355. }
  356. }
  357. else if (combo >= 10)
  358. {
  359. currentDogState = "fastRunning";
  360. foreach (GameObject dog in dogObjects)
  361. {
  362. Animator animator = dog.GetComponent<Animator>();
  363. if (animator != null)
  364. {
  365. animator.SetTrigger("fastRun");
  366. SetLeavesParticleSpeed(10.0f, 20.0f); // 设置leaves粒子效果的Start Speed 和 Rate over Time
  367. // animator.Play("Fast Run");
  368. }
  369. }
  370. }
  371. else if (combo == 0)
  372. {
  373. if (currentDogState == "running" || currentDogState == "fastRunning")
  374. {
  375. currentDogState = "walking";
  376. foreach (GameObject dog in dogObjects)
  377. {
  378. Animator animator = dog.GetComponent<Animator>();
  379. if (animator != null)
  380. {
  381. // animator.Play("Walk");
  382. animator.SetTrigger("walk");
  383. SetLeavesParticleSpeed(2.0f, 5.0f); // 设置leaves粒子效果的Start Speed 和 Rate over Time
  384. }
  385. }
  386. }
  387. }
  388. }
  389. // 设置leaves粒子效果的Start Speed 和 Rate over Time
  390. public void SetLeavesParticleSpeed(float speed, float rate)
  391. {
  392. if (Leaves != null)
  393. {
  394. ParticleSystem particleSystem = Leaves.GetComponent<ParticleSystem>();
  395. if (particleSystem != null)
  396. {
  397. var main = particleSystem.main;
  398. main.startSpeed = speed;
  399. var emission = particleSystem.emission;
  400. emission.rateOverTime = rate;
  401. }
  402. else
  403. {
  404. Debug.LogWarning("ParticleSystem not found on Leaves object.");
  405. }
  406. }
  407. else
  408. {
  409. Debug.LogWarning("Leaves object not found.");
  410. }
  411. }
  412. // 协程控制场景里面所有的狗静止或者在x:-0.5到0.5之间, z:-6到-7之间随机移动
  413. IEnumerator DogMovementController()
  414. {
  415. while (true)
  416. {
  417. GameObject[] dogObjects = GameObject.FindGameObjectsWithTag("dog");
  418. foreach (GameObject dog in dogObjects)
  419. {
  420. // 让狗在x:-0.5到0.5之间, z:-6到-7之间随机移动
  421. float randomX = UnityEngine.Random.Range(-0.5f, 0.5f);
  422. float randomZ = UnityEngine.Random.Range(-7f, -6f);
  423. // dog.transform.Translate(new Vector3(randomX, -0.5f, randomZ) * Time.deltaTime);
  424. var position = new Vector3(randomX, dog.transform.position.y, randomZ);
  425. Debug.Log($"Dog {dog.name} moving to position: {position}");
  426. StartCoroutine(DogMoveToPosition(dog, position, 0.5f));
  427. }
  428. yield return new WaitForSeconds(5f); // 每5秒更新一次位置
  429. }
  430. }
  431. // 协程控制场景里面的狗按照指定速度移动到指定的位置
  432. IEnumerator DogMoveToPosition(GameObject dog, Vector3 targetPosition, float speed = 0.5f)
  433. {
  434. while (Vector3.Distance(dog.transform.position, targetPosition) > 0.1f)
  435. {
  436. dog.transform.position = Vector3.MoveTowards(dog.transform.position, targetPosition, speed * Time.deltaTime);
  437. yield return null;
  438. }
  439. }
  440. private void UpdateAndShowScoreUI()
  441. {
  442. // 更新分数显示逻辑
  443. // 这里可以添加代码来更新UI上的分数显示
  444. // 例如:scoreLabel.text = "Score: " + score;
  445. var UI = GameObject.Find("UI");
  446. var scorePanel = UI.transform.Find("ScorePanel").gameObject;
  447. scorePanel.SetActive(true);
  448. var walkDogsScoreController = scorePanel.transform.Find("UIDocument").GetComponent<WalkDogsScoreController>();
  449. walkDogsScoreController.score = score;
  450. walkDogsScoreController.maxCombo = maxCombo;
  451. walkDogsScoreController.perfect = perfectCount;
  452. walkDogsScoreController.good = goodCount;
  453. walkDogsScoreController.poor = poorCount;
  454. walkDogsScoreController.miss = missCount;
  455. walkDogsScoreController.ShowScore();
  456. }
  457. }
  458. public class TouchResponse
  459. {
  460. public string action = ""; // 触控动作 up, down, left, right, tap, none(表示无效)
  461. public float time;
  462. public TouchResponse(string action, float time)
  463. {
  464. this.action = action;
  465. this.time = time;
  466. }
  467. }