using Newtonsoft.Json; using NUnit.Framework; using System.Collections.Generic; using UnityEngine; public class SoundTrackManager { public string name { set; get; } public string soundTrack { set; get; } public string description { set; get; } public int speed { set; get; } = 100; public int length { set; get; } = 0; public List soundAction { set; get; } = new List(); public void ImportFromJson(string json) { var data = JsonConvert.DeserializeObject>(json); speed = int.Parse(data["speed"].ToString()); name = data["name"].ToString(); soundTrack = data["sound_track"].ToString(); description = data["description"].ToString(); length = int.Parse(data["length"].ToString()); soundAction.Clear(); SoundAction[] actions = JsonConvert.DeserializeObject(data["action points"].ToString()); foreach (var action in actions) { soundAction.Add(action); } } // 根据音乐时常随机生成 public void GenRandomActions(float actionGap=0.5f) { // 读取音乐,并获取长度 AudioClip audioClip = Resources.Load(soundTrack); float length = audioClip.length; soundAction.Clear(); float timeGap = actionGap; // 计算出两个相邻音符时间间距,对应程序难度 float time = 4f; int combo = 0; // 连续输入音符 while (time < length - 2) { int randomInt = Random.Range(0, 7); if (randomInt < 5) { combo++; time += timeGap; if (randomInt == 0) { SoundAction action = new(time, "tap"); soundAction.Add(action); } if (randomInt == 1) { SoundAction action = new(time, "left"); soundAction.Add(action); } if (randomInt == 2) { SoundAction action = new(time, "right"); soundAction.Add(action); } if (randomInt == 3) { SoundAction action = new(time, "up"); soundAction.Add(action); } if (randomInt == 4) { SoundAction action = new(time, "down"); soundAction.Add(action); } } else if (randomInt == 5) { time += timeGap; if (combo > 0) { combo--; } } else if (randomInt == 6) { time += timeGap * combo / 6; } } Debug.Log("random sound action create successful. Total action #:" + soundAction.Count); } } public class SoundAction { public float time { set; get; } = 0f; public string action { set; get; } = ""; public bool isTapped = false; // 表示当前这个音乐动作是否被播放过 public bool isActive = false; // 表示当前这个音乐动作是否正在场景中激活 public SoundAction(float time, string action) { this.time = time; this.action = action; } }