HomeController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using Cinemachine;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using Unity.Collections.LowLevel.Unsafe;
  7. using Unity.VisualScripting;
  8. using UnityEngine;
  9. using UnityEngine.Animations;
  10. using UnityEngine.Rendering.PostProcessing;
  11. using UnityEngine.SceneManagement;
  12. /* 本代码控制室内场景
  13. * 控制宠物在Home场景动画
  14. * !!!特别注意:Dog Initializer 必须挂载在同一个组件下,并且必须在本组价下方。确保比本组件先执行
  15. * 主要调节参数在FixedUpdate代码段里面
  16. * 提示用户注册
  17. */
  18. public class HomeController : MonoBehaviour
  19. {
  20. public static HomeController Instance;
  21. public static List<DogInScene> dogsInScene = new List<DogInScene>();
  22. public static bool listenBreak = false; // 当按下说话按键后,所有狗停止行动,立刻切换到监听状态。
  23. public static CinemachineVirtualCamera playerCam, dogCam;
  24. public static DateTime lastCameraChange;
  25. private bool isSleepChecked = false; // 用于检测第一次睡眠检测是否执行完成
  26. // Start is called once before the first execution of Update after the MonoBehaviour is created
  27. private GameObject centerOfDogs;
  28. //private bool isInteract = false; // 是否在交互状态
  29. private void Awake()
  30. {
  31. if (Instance == null)
  32. {
  33. Instance = this;
  34. //DontDestroyOnLoad(gameObject); // 必须关掉否则会导致原场景destroy不能执行
  35. }
  36. else
  37. {
  38. Destroy(gameObject);
  39. }
  40. }
  41. void Start()
  42. {
  43. dogsInScene.Clear(); // dogsInScene 是静态,每次启动要清空
  44. lastCameraChange = DateTime.Now;
  45. playerCam = GameObject.Find("VCam Player").GetComponent<CinemachineVirtualCamera>();
  46. dogCam = GameObject.Find("VCam Dog").GetComponent<CinemachineVirtualCamera>();
  47. centerOfDogs= GameObject.Find("CenterOfDogs");
  48. //InitialScene();
  49. StartCoroutine(InitialScene());
  50. }
  51. // Update is called once per frame
  52. void FixedUpdate()
  53. {
  54. if (SceneInitialCheck()) // 确保狗读取成功后执行代码
  55. {
  56. // 计算多只狗的中心位置,用于主摄像机瞄准
  57. centerOfDogs.transform.position = CenterOfDogs();
  58. if (!isSleepChecked) // 每次启动检测只进行一次是否进入睡眠
  59. {
  60. // 判断是否在睡觉时间
  61. DateTime dateTime = DateTime.Now;
  62. foreach (var dog in dogsInScene)
  63. {
  64. if (dateTime.Hour >= 22 || dateTime.Hour <= 5) // 深夜模式,狗默认在睡觉状态
  65. {
  66. dog.Sleep();
  67. }
  68. else if (dog.dogProperty.stamina <= 10) { dog.Sleep(); } // 狗体力太低了,进入睡觉模式
  69. else
  70. {
  71. dog.IdleAnimation();
  72. }
  73. }
  74. isSleepChecked = true;
  75. }
  76. #region 场景动画主循环
  77. // 检测狗是否被撞翻,如果是,立刻翻回来
  78. foreach (var dog in dogsInScene)
  79. {
  80. Quaternion curRotation = dog.gameObject.transform.rotation;
  81. if (curRotation.x != 0)
  82. {
  83. curRotation.x = 0;
  84. }
  85. if (curRotation.z != 0)
  86. {
  87. curRotation.z = 0;
  88. }
  89. dog.gameObject.transform.rotation = curRotation;
  90. }
  91. // 生成一个数据数用于随机开启动画,如果和狗的randomFactor相同就开启动画
  92. int randomCheck = UnityEngine.Random.Range(0, 51);
  93. foreach (var dog in dogsInScene)
  94. {
  95. // 如果在eat drink进程结束前不执行随机场景代码
  96. //if (dog.itemConsumeProgress) // TODO 以后用DogInScene.dogState来判断
  97. if (dog.dogState == "itemConsume")
  98. {
  99. if (dog.isMovingToBowl)
  100. {
  101. dog.MovetoBowl();
  102. }
  103. }
  104. else if (dog.dogState == "interact")
  105. {
  106. // 单只狗在交互的状态控制代码
  107. if (dog.isMovingToBowl)
  108. {
  109. dog.MovetoBowl();
  110. }
  111. if (dog.InteractTimeout()) // 如果交互时间结束,结束交互状态
  112. {
  113. dog.ExitInteract();
  114. }
  115. }
  116. else
  117. {
  118. // 随机动作控制控制
  119. RandomCameraChange();
  120. if (listenBreak) // 如果用户按下说话按键,立刻切换到监听状态
  121. {
  122. dog.Listen();
  123. }
  124. else if (dog.isMoving)
  125. {
  126. dog.RandomMove();
  127. }
  128. else if (randomCheck == dog.randomFactor && !dog.isSleeping) // 当狗自身的随机数和系统随机数相同时候触发。约100秒触发一次。
  129. {
  130. TimeSpan ts = DateTime.Now - dog.animationStartTime;
  131. if (ts.Seconds >= 30) // 如果距离上一个动作超过30秒就可以开始新的动作
  132. {
  133. float r = UnityEngine.Random.Range(0, 1f);
  134. if (r > 0.6) // 随机选择开始动画,或者移动
  135. {
  136. dog.IdleAnimation();
  137. }
  138. else // 狗狗开始步行移动
  139. {
  140. dog.SetMoveSpeed(0);
  141. dog.moveSpeed = 0;
  142. dog.RandomMove();
  143. }
  144. }
  145. }
  146. }
  147. }
  148. #endregion
  149. }
  150. }
  151. private void OnDestroy()
  152. {
  153. Debug.Log("Home scene is destoried.");
  154. }
  155. //void AniOrWalk(DogInScene dog) // 狗在普通状态下,随机或播放动画,或移动
  156. //{
  157. //}
  158. // 初始化场景,加载所有的狗,并配置components,添加到dogsInScene List里面去
  159. //void InitialScene()
  160. IEnumerator InitialScene()
  161. {
  162. //yield return null;
  163. //yield return null;
  164. yield return null; // 跳过三帧,初始化最多三只狗
  165. //Debug.Log(isInitialDone);
  166. foreach (var dog in UserProperty.dogs)
  167. {
  168. DogInScene dogInScene = new DogInScene(dog);
  169. float x = UnityEngine.Random.Range(-1f, 1f); // 随机生成位置,考虑到手机评估宽度限制宽度
  170. float z = UnityEngine.Random.Range(-5f, 5f);
  171. float y = UnityEngine.Random.Range(0, 360f);
  172. var initPosition = new Vector3(x, 0, z);
  173. StartCoroutine(DogComponentAdd(dog)); // 加载狗的其他组件
  174. var dogGameObject = GameObject.Find(dog.dog_name);
  175. if (dogGameObject == null)
  176. {
  177. Debug.Log(dog.dog_name + "is not found in Home Controller");
  178. }
  179. dogGameObject.transform.position = initPosition;
  180. dogGameObject.transform.rotation = Quaternion.Euler(0, y, 0);
  181. dogGameObject.transform.localScale = new Vector3(2, 2, 2);
  182. dogInScene.SetGameObject(dogGameObject);
  183. dogsInScene.Add(dogInScene);
  184. }
  185. }
  186. // 加载狗的其他组件
  187. IEnumerator DogComponentAdd(DogProperty dogProperty)
  188. {
  189. // 等待一帧,确保所有 Start() 方法都执行完成
  190. yield return null;
  191. // 第一帧以后开始执行
  192. GameObject dog = GameObject.Find(dogProperty.dog_name);
  193. // 加载指定的Animator controller
  194. Animator animator = dog.GetComponent<Animator>();
  195. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController");
  196. if (dogProperty.breed == "shibaInu") { animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController"); }
  197. animator.runtimeAnimatorController = animatorController;
  198. // 加载Rigidbody
  199. Rigidbody rigidbody = dog.AddComponent<Rigidbody>();
  200. //Rigidbody rigidbody = dog.GetComponent<Rigidbody>();
  201. //rigidbody.isKinematic = true;
  202. rigidbody.mass = 10;
  203. rigidbody.linearDamping = 10;
  204. rigidbody.angularDamping = 10;
  205. //rigidbody.freezeRotation = true;
  206. rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;
  207. rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
  208. rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
  209. // 加载box collider
  210. BoxCollider boxCollider = dog.AddComponent<BoxCollider>();
  211. boxCollider.isTrigger = false;
  212. boxCollider.center = new Vector3(0, 0.25f, 0);
  213. boxCollider.size = new Vector3(0.12f, 0.45f, 0.54f);
  214. //yield return null;
  215. }
  216. // 场景随机切换镜头看向不同的狗
  217. void RandomCameraChange()
  218. {
  219. int delay = 10; // 延迟10秒执行一次
  220. TimeSpan ts = DateTime.Now - lastCameraChange;
  221. if (ts.TotalSeconds < delay) {return;}
  222. int dogCount = dogsInScene.Count;
  223. int r = UnityEngine.Random.Range(0, dogCount+1);
  224. if (r < dogCount)
  225. {
  226. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  227. dogCam.Priority = 10;
  228. playerCam.Priority = 1;
  229. }
  230. else
  231. {
  232. dogCam.Priority = 1;
  233. playerCam.Priority = 10;
  234. }
  235. lastCameraChange = DateTime.Now;
  236. }
  237. // 检测场景是否初始化完成
  238. bool SceneInitialCheck()
  239. {
  240. bool initDone = true;
  241. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  242. {
  243. foreach (var dog in dogsInScene)
  244. {
  245. if(dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  246. {
  247. initDone = false;
  248. }
  249. }
  250. }
  251. else
  252. {
  253. initDone=false;
  254. }
  255. //Debug.Log("Home scene initial status:"+initDone);
  256. return initDone;
  257. }
  258. // 计算多只狗的中心位置,用于主摄像机瞄准
  259. private Vector3 CenterOfDogs()
  260. {
  261. Vector3 center = Vector3.zero;
  262. foreach (var dog in dogsInScene)
  263. {
  264. center += dog.gameObject.transform.position;
  265. }
  266. center /= dogsInScene.Count;
  267. return center;
  268. }
  269. #region 语音控制区
  270. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  271. public void VoiceCallRequest(string filePath)
  272. {
  273. Debug.Log("Voice Call Post request");
  274. string url = "/api/voice/call/";
  275. WWWForm form = new();
  276. form.AddField("user_id", UserProperty.userId);
  277. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCallCallback));
  278. }
  279. // 语音呼唤上传回调函数
  280. void VoiceCallCallback(string json)
  281. {
  282. Debug.Log("Voice call callback");
  283. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  284. if (data != null && data["status"].ToString() == "success")
  285. {
  286. // 刷新狗的数据
  287. string dogJson = data["dogs"].ToString();
  288. UserProperty.FreshDogInfo(dogJson);
  289. // TODO 根据返回结果设定focusdog
  290. // focusdog 开启互动模式
  291. HomeController.dogsInScene[GameData.focusDog].dogState = "interact";
  292. HomeController.dogsInScene[GameData.focusDog].SetupInteract();
  293. }
  294. else
  295. {
  296. Debug.Log(data["message"]);
  297. }
  298. }
  299. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  300. public void VoiceCommandRequest(string filePath)
  301. {
  302. Debug.Log("Voice Command Post request");
  303. string url = "/api/voice/command/";
  304. WWWForm form = new();
  305. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  306. form.AddField("user_id", UserProperty.userId);
  307. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  308. }
  309. // 语音呼唤上传回调函数
  310. void VoiceCommandCallback(string json)
  311. {
  312. Debug.Log("Voice call callback");
  313. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  314. if (data != null && data["status"].ToString() == "success")
  315. {
  316. // 刷新狗的数据
  317. string dogJson = data["dogs"].ToString();
  318. UserProperty.FreshDogInfo(dogJson);
  319. }
  320. else
  321. {
  322. Debug.Log(data["message"]);
  323. }
  324. }
  325. // 改变Voice And Menu 菜单形态
  326. public void VoiceButtonSwitch(bool state)
  327. {
  328. // 交互时候关闭其他菜单
  329. var vamUI = GameObject.Find("VoiceAndMenu");
  330. if (vamUI != null)
  331. {
  332. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  333. var voiceController = UIdocument.GetComponent<VoiceController>();
  334. voiceController.isCommandMode = state;
  335. }
  336. }
  337. #endregion
  338. }
  339. //
  340. public enum ItemGroup
  341. {
  342. food,
  343. water
  344. }