HomeController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 isInteractMode = 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. if (isInteractMode)
  94. {
  95. foreach (var dog in dogsInScene)
  96. {
  97. if (dog.dogState == "interact")
  98. {
  99. dogCam.m_LookAt = dog.gameObject.transform;
  100. dogCam.Priority = 10;
  101. // 单只狗在交互的状态控制代码
  102. if (dog.isMovingToPlayer)
  103. {
  104. dog.MovetoPlayer();
  105. }
  106. if (dog.InteractTimeout()) // 如果交互时间结束,结束交互状态
  107. {
  108. dog.ExitInteract();
  109. isInteractMode = false; // 交互结束,退出交互状态
  110. }
  111. }
  112. }
  113. }
  114. else
  115. {
  116. foreach (var dog in dogsInScene)
  117. {
  118. // 如果在eat drink进程结束前不执行随机场景代码
  119. //if (dog.itemConsumeProgress) // TODO 以后用DogInScene.dogState来判断
  120. if (dog.dogState == "itemConsume")
  121. {
  122. if (dog.isMovingToBowl)
  123. {
  124. dog.MovetoBowl();
  125. }
  126. }
  127. else
  128. {
  129. // 随机动作控制控制
  130. RandomCameraChange();
  131. if (listenBreak) // 如果用户按下说话按键,立刻切换到监听状态
  132. {
  133. dog.Listen();
  134. }
  135. else if (dog.isMoving)
  136. {
  137. dog.RandomMove();
  138. }
  139. else if (randomCheck == dog.randomFactor && !dog.isSleeping) // 当狗自身的随机数和系统随机数相同时候触发。约100秒触发一次。
  140. {
  141. TimeSpan ts = DateTime.Now - dog.animationStartTime;
  142. if (ts.Seconds >= 30) // 如果距离上一个动作超过30秒就可以开始新的动作
  143. {
  144. float r = UnityEngine.Random.Range(0, 1f);
  145. if (r > 0.6) // 随机选择开始动画,或者移动
  146. {
  147. dog.IdleAnimation();
  148. }
  149. else // 狗狗开始步行移动
  150. {
  151. dog.SetMoveSpeed(0);
  152. dog.moveSpeed = 0;
  153. dog.RandomMove();
  154. }
  155. }
  156. }
  157. }
  158. }
  159. }
  160. #endregion
  161. }
  162. }
  163. private void OnDestroy()
  164. {
  165. Debug.Log("Home scene is destoried.");
  166. }
  167. //void AniOrWalk(DogInScene dog) // 狗在普通状态下,随机或播放动画,或移动
  168. //{
  169. //}
  170. // 初始化场景,加载所有的狗,并配置components,添加到dogsInScene List里面去
  171. //void InitialScene()
  172. IEnumerator InitialScene()
  173. {
  174. //yield return null;
  175. //yield return null;
  176. yield return null; // 跳过三帧,初始化最多三只狗
  177. //Debug.Log(isInitialDone);
  178. foreach (var dog in UserProperty.dogs)
  179. {
  180. DogInScene dogInScene = new DogInScene(dog);
  181. float x = UnityEngine.Random.Range(-1f, 1f); // 随机生成位置,考虑到手机评估宽度限制宽度
  182. float z = UnityEngine.Random.Range(-5f, 5f);
  183. float y = UnityEngine.Random.Range(0, 360f);
  184. var initPosition = new Vector3(x, 0, z);
  185. StartCoroutine(DogComponentAdd(dog)); // 加载狗的其他组件
  186. var dogGameObject = GameObject.Find(dog.dog_name);
  187. if (dogGameObject == null)
  188. {
  189. Debug.Log(dog.dog_name + "is not found in Home Controller");
  190. }
  191. dogGameObject.transform.position = initPosition;
  192. dogGameObject.transform.rotation = Quaternion.Euler(0, y, 0);
  193. dogGameObject.transform.localScale = new Vector3(2, 2, 2);
  194. dogInScene.SetGameObject(dogGameObject);
  195. dogsInScene.Add(dogInScene);
  196. }
  197. }
  198. // 加载狗的其他组件
  199. IEnumerator DogComponentAdd(DogProperty dogProperty)
  200. {
  201. // 等待一帧,确保所有 Start() 方法都执行完成
  202. yield return null;
  203. // 第一帧以后开始执行
  204. GameObject dog = GameObject.Find(dogProperty.dog_name);
  205. // 加载指定的Animator controller
  206. Animator animator = dog.GetComponent<Animator>();
  207. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController");
  208. if (dogProperty.breed == "shibaInu") { animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController"); }
  209. animator.runtimeAnimatorController = animatorController;
  210. // 加载Rigidbody
  211. Rigidbody rigidbody = dog.AddComponent<Rigidbody>();
  212. //Rigidbody rigidbody = dog.GetComponent<Rigidbody>();
  213. //rigidbody.isKinematic = true;
  214. rigidbody.mass = 10;
  215. rigidbody.linearDamping = 10;
  216. rigidbody.angularDamping = 10;
  217. //rigidbody.freezeRotation = true;
  218. rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;
  219. rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
  220. rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
  221. // 加载box collider
  222. BoxCollider boxCollider = dog.AddComponent<BoxCollider>();
  223. boxCollider.isTrigger = false;
  224. boxCollider.center = new Vector3(0, 0.25f, 0);
  225. boxCollider.size = new Vector3(0.12f, 0.45f, 0.54f);
  226. //yield return null;
  227. }
  228. // 场景随机切换镜头看向不同的狗
  229. void RandomCameraChange()
  230. {
  231. int delay = 10; // 延迟10秒执行一次
  232. TimeSpan ts = DateTime.Now - lastCameraChange;
  233. if (ts.TotalSeconds < delay) { return; }
  234. int dogCount = dogsInScene.Count;
  235. int r = UnityEngine.Random.Range(0, dogCount + 1);
  236. if (r < dogCount)
  237. {
  238. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  239. dogCam.Priority = 10;
  240. playerCam.Priority = 1;
  241. }
  242. else
  243. {
  244. dogCam.Priority = 1;
  245. playerCam.Priority = 10;
  246. }
  247. lastCameraChange = DateTime.Now;
  248. }
  249. // 检测场景是否初始化完成
  250. bool SceneInitialCheck()
  251. {
  252. bool initDone = true;
  253. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  254. {
  255. foreach (var dog in dogsInScene)
  256. {
  257. if (dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  258. {
  259. initDone = false;
  260. }
  261. }
  262. }
  263. else
  264. {
  265. initDone = false;
  266. }
  267. //Debug.Log("Home scene initial status:"+initDone);
  268. return initDone;
  269. }
  270. // 计算多只狗的中心位置,用于主摄像机瞄准
  271. private Vector3 CenterOfDogs()
  272. {
  273. Vector3 center = Vector3.zero;
  274. foreach (var dog in dogsInScene)
  275. {
  276. center += dog.gameObject.transform.position;
  277. }
  278. center /= dogsInScene.Count;
  279. return center;
  280. }
  281. #region 语音控制区
  282. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  283. public void VoiceCallRequest(string filePath)
  284. {
  285. Debug.Log("Voice Call Post request");
  286. string url = "/api/voice/call/";
  287. WWWForm form = new();
  288. form.AddField("user_id", UserProperty.userId);
  289. // TODO 待后台开发完成后,开启网络通讯功能,目前暂用临时直接赋值
  290. // StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCallCallback));
  291. isInteractMode = true; // 进入交互模式
  292. dogsInScene[0].SetupInteract();
  293. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  294. }
  295. // 语音呼唤上传回调函数
  296. void VoiceCallCallback(string json)
  297. {
  298. Debug.Log("Voice call callback");
  299. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  300. if (data != null && data["status"].ToString() == "success")
  301. {
  302. // 刷新狗的数据
  303. string dogJson = data["dogs"].ToString();
  304. UserProperty.FreshDogInfo(dogJson);
  305. // TODO 根据返回结果设定focusdog
  306. float highestScore = 0;
  307. string highestScoreDogId = "";
  308. var scores = data["scores"].ToString();
  309. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  310. foreach (var score in scoresList)
  311. {
  312. if (score.Value > highestScore)
  313. {
  314. highestScore = score.Value;
  315. highestScoreDogId = score.Key;
  316. }
  317. }
  318. if (highestScore > 60) // 60分以上才可以进入交互模式
  319. {
  320. GameData.focusDog = UserProperty.GetDogIndex(highestScoreDogId);
  321. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  322. foreach (var dog in dogsInScene)
  323. {
  324. if (dog.dogProperty.d_id == highestScoreDogId)
  325. {
  326. dog.SetupInteract();
  327. }
  328. }
  329. }
  330. // focusdog 开启互动模式
  331. HomeController.dogsInScene[GameData.focusDog].dogState = "interact";
  332. HomeController.dogsInScene[GameData.focusDog].SetupInteract();
  333. }
  334. else
  335. {
  336. Debug.Log(data["message"]);
  337. }
  338. }
  339. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  340. public void VoiceCommandRequest(string filePath)
  341. {
  342. Debug.Log("Voice Command Post request");
  343. string url = "/api/voice/command/";
  344. WWWForm form = new();
  345. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  346. form.AddField("user_id", UserProperty.userId);
  347. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  348. }
  349. // 语音呼唤上传回调函数
  350. void VoiceCommandCallback(string json)
  351. {
  352. Debug.Log("Voice call callback");
  353. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  354. if (data != null && data["status"].ToString() == "success")
  355. {
  356. // 刷新狗的数据
  357. string dogJson = data["dogs"].ToString();
  358. UserProperty.FreshDogInfo(dogJson);
  359. }
  360. else
  361. {
  362. Debug.Log(data["message"]);
  363. }
  364. }
  365. // 改变Voice And Menu 菜单形态
  366. public void VoiceButtonOnlySwitch(bool state)
  367. {
  368. // 交互时候关闭其他菜单
  369. var vamUI = GameObject.Find("VoiceAndMenu");
  370. if (vamUI != null)
  371. {
  372. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  373. var voiceController = UIdocument.GetComponent<VoiceController>();
  374. voiceController.isCommandMode = state;
  375. }
  376. }
  377. #endregion
  378. }
  379. public enum ItemGroup
  380. {
  381. food,
  382. water
  383. }