HomeController.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. using Cinemachine;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. using UnityEngine.InputSystem;
  8. /* 本代码控制室内场景
  9. * 控制宠物在Home场景动画
  10. * !!!特别注意:Dog Initializer 必须挂载在同一个组件下,并且必须在本组价下方。确保比本组件先执行
  11. * 主要调节参数在FixedUpdate代码段里面
  12. * 提示用户注册
  13. * SetDogsIsTrigger 正常模式下为true。交互模式和进食模式下为false。
  14. */
  15. public class HomeController : MonoBehaviour
  16. {
  17. public static HomeController Instance;
  18. public static List<DogInScene> dogsInScene = new List<DogInScene>();
  19. public static bool listenBreak = false; // 当按下说话按键后,所有狗停止行动,立刻切换到监听状态。
  20. public static CinemachineVirtualCamera playerCam, dogCam;
  21. public static DateTime lastCameraChange;
  22. private bool isSleepChecked = false; // 用于检测第一次睡眠检测是否执行完成
  23. // Start is called once before the first execution of Update after the MonoBehaviour is created
  24. private GameObject centerOfDogs;
  25. private SceneMode sceneMode = SceneMode.NORMAL; // 当前场景处在的模式
  26. //private bool isInteractMode = false; // 场景是否在交互状态
  27. private Vector2 previousPointerPosition = Vector2.zero; // 前一帧鼠标位置
  28. private GameObject interactDog; // 交互的狗
  29. float interactTime = 0f; // 交互时间
  30. //private bool isTrainingMode = false; // 是否在训练状态
  31. private string trainingContent = String.Empty; // 训练内容 _xx 对于language.json 0x开始提示 1x成功提示 2x失败提示
  32. private int totalTrainingTimes = 2; // 训练总次数
  33. private int currentTrainingTimes = 0; // 当前训练次数
  34. private string trainingDogId = ""; // 训练的狗id
  35. private bool isTrainingMsgShowed_1 = false; // 第一条是否已经显示训练提示
  36. private bool isTrainingMsgShowed_2 = false; // 第二条是否已经显示训练提示
  37. private bool isTrainingAnimationPlayed = false; // 训练动画是否已经播放
  38. public bool isHideBowlRunning = false; // 是否正在运行隐藏碗的协程
  39. private void Awake()
  40. {
  41. if (Instance == null)
  42. {
  43. Instance = this;
  44. //DontDestroyOnLoad(gameObject); // 必须关掉否则会导致原场景destroy不能执行
  45. }
  46. else
  47. {
  48. Destroy(gameObject);
  49. }
  50. }
  51. void Start()
  52. {
  53. Time.timeScale = 1; // 确保时间流逝正常
  54. dogsInScene.Clear(); // dogsInScene 是静态,每次启动要清空
  55. lastCameraChange = DateTime.Now;
  56. playerCam = GameObject.Find("VCam Player").GetComponent<CinemachineVirtualCamera>();
  57. dogCam = GameObject.Find("VCam Dog").GetComponent<CinemachineVirtualCamera>();
  58. centerOfDogs = GameObject.Find("CenterOfDogs");
  59. //InitialScene();
  60. StartCoroutine(InitialScene());
  61. }
  62. // Update is called once per frame
  63. void FixedUpdate()
  64. {
  65. if (SceneInitialCheck()) // 确保狗读取成功后执行代码
  66. {
  67. // 计算多只狗的中心位置,用于主摄像机瞄准
  68. centerOfDogs.transform.position = CenterOfDogs();
  69. if (!isSleepChecked) // 每次启动检测只进行一次是否进入睡眠
  70. {
  71. // 判断是否在睡觉时间
  72. DateTime dateTime = DateTime.Now;
  73. foreach (var dog in dogsInScene)
  74. {
  75. if (dateTime.Hour >= 22 || dateTime.Hour <= 5) // 深夜模式,狗默认在睡觉状态
  76. {
  77. dog.Sleep();
  78. }
  79. else if (dog.dogProperty.stamina <= 10) { dog.Sleep(); } // 狗体力太低了,进入睡觉模式
  80. else
  81. {
  82. dog.IdleAnimation();
  83. }
  84. }
  85. isSleepChecked = true;
  86. }
  87. #region 场景动画主循环
  88. // 检测狗是否被撞翻,如果是,立刻翻回来
  89. foreach (var dog in dogsInScene)
  90. {
  91. Quaternion curRotation = dog.gameObject.transform.rotation;
  92. if (curRotation.x != 0)
  93. {
  94. curRotation.x = 0;
  95. }
  96. if (curRotation.z != 0)
  97. {
  98. curRotation.z = 0;
  99. }
  100. dog.gameObject.transform.rotation = curRotation;
  101. }
  102. // 生成一个数据数用于随机开启动画,如果和狗的randomFactor相同就开启动画
  103. int sceneRandomFactor = UnityEngine.Random.Range(0, 51);
  104. // 检测是否有狗没有通过voiceCall训练,如果有,立刻进入训练模式
  105. if (sceneMode == SceneMode.NORMAL) // 这段代码用于在NORMAL场景下检测是否有狗进入训练模式
  106. {
  107. trainingContent = String.Empty;
  108. foreach (var dog in dogsInScene)
  109. {
  110. if (trainingContent != String.Empty) { break; } // 如果已经有狗进入训练模式,跳出循环
  111. if (!dog.dogProperty.voiceCallEnable)
  112. {
  113. trainingContent = "voiceCall";
  114. }
  115. if (trainingContent != String.Empty)
  116. {
  117. sceneMode = SceneMode.TRAINING;
  118. dog.RemoveZzzParticle();
  119. trainingDogId = dog.dogProperty.d_id;
  120. totalTrainingTimes = 2;
  121. currentTrainingTimes = 0;
  122. GameData.focusDog = dogsInScene.IndexOf(dog);
  123. //GameData.focusDog = UserProperty.GetDogIndexById(dog.dogProperty.d_id);
  124. dogsInScene[GameData.focusDog].SetupInteract();
  125. interactDog = dogsInScene[GameData.focusDog].gameObject;
  126. // GameData.isVoiceTrainingToday = true;
  127. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  128. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  129. }
  130. }
  131. foreach (var dog in dogsInScene)
  132. {
  133. if (trainingContent != String.Empty) { break; } // 如果已经有狗进入训练模式,跳出循环
  134. if (dog.dogProperty.voiceCallEnable && !GameData.isVoiceTrainingToday)
  135. {
  136. if (dog.dogProperty.voiceCall >= 40 && dog.dogProperty.CommandTrainingPhase() < 4)
  137. {
  138. // 当狗的voiceCall大于等于40,进入第一阶段指令训练模式
  139. int random = UnityEngine.Random.Range(0, 100);
  140. if (GameTool.IntBetween(0, 25, random) && !dog.dogProperty.commandSit)
  141. {
  142. trainingContent = "commandSit";
  143. }
  144. else if (GameTool.IntBetween(25, 50, random) && !dog.dogProperty.commandStand)
  145. {
  146. trainingContent = "commandStand";
  147. }
  148. else if (GameTool.IntBetween(50, 75, random) && !dog.dogProperty.commandBark)
  149. {
  150. trainingContent = "commandBark";
  151. }
  152. else if (GameTool.IntBetween(75, 100, random) && !dog.dogProperty.commandLieDown)
  153. {
  154. trainingContent = "commandLieDown";
  155. }
  156. else
  157. {
  158. // GameData.isVoiceTrainingToday = true;
  159. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  160. }
  161. }
  162. else if (dog.dogProperty.voiceCommand >= 40 && dog.dogProperty.CommandTrainingPhase() >= 4)
  163. {
  164. // 当狗的voiceCommand大于等于40并且完成第一阶段所有训练,进入第二阶段指令训练模式
  165. int random = UnityEngine.Random.Range(0, 100);
  166. if (GameTool.IntBetween(0, 20, random) && !dog.dogProperty.commandShake)
  167. {
  168. trainingContent = "commandShake";
  169. }
  170. else if (GameTool.IntBetween(20, 40, random) && !dog.dogProperty.commandTouch)
  171. {
  172. trainingContent = "commandTouch";
  173. }
  174. else if (GameTool.IntBetween(40, 60, random) && !dog.dogProperty.commandDeath)
  175. {
  176. trainingContent = "commandDeath";
  177. }
  178. else if (GameTool.IntBetween(60, 80, random) && !dog.dogProperty.commandTurnL)
  179. {
  180. trainingContent = "commandTurnL";
  181. }
  182. else if (GameTool.IntBetween(80, 100, random) && !dog.dogProperty.commandTurnR)
  183. {
  184. trainingContent = "commandTurnR";
  185. }
  186. }
  187. }
  188. if (trainingContent != String.Empty)
  189. {
  190. sceneMode = SceneMode.TRAINING;
  191. dog.RemoveZzzParticle();
  192. trainingDogId = dog.dogProperty.d_id;
  193. totalTrainingTimes = 2;
  194. currentTrainingTimes = 0;
  195. GameData.focusDog = dogsInScene.IndexOf(dog);
  196. //GameData.focusDog = UserProperty.GetDogIndexById(dog.dogProperty.d_id);
  197. dogsInScene[GameData.focusDog].SetupInteract();
  198. interactDog = dogsInScene[GameData.focusDog].gameObject;
  199. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  200. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  201. }
  202. }
  203. }
  204. if (this.sceneMode == SceneMode.TRAINING) // 这段代码控制场景进入训练模式
  205. {
  206. foreach (var dog in dogsInScene)
  207. {
  208. if (dog.dogState == DogState.INTERACT || dog.dogState == DogState.TRAINING)
  209. {
  210. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  211. dogCam.Priority = 10;
  212. // 单只狗在交互的状态控制代码
  213. if (dog.isMovingToPlayer)
  214. {
  215. dog.MovetoPlayer();
  216. }
  217. else
  218. {
  219. // 开始训练时让狗播放动画
  220. if (trainingContent != "voiceCall" && !isTrainingAnimationPlayed)
  221. {
  222. string command = trainingContent.Substring(7);
  223. dog.animator.SetTrigger(command);
  224. dog.animator.SetBool(command + "_status", true);
  225. isTrainingAnimationPlayed = true;
  226. }
  227. // 狗完成移动后,开始进入正式训练交互模式
  228. dog.dogState = DogState.TRAINING;
  229. if (!isTrainingMsgShowed_1 && !isTrainingMsgShowed_2 && currentTrainingTimes == 0)
  230. {
  231. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_00", EnviromentSetting.languageCode });
  232. if (msg.Contains("<<dog_name>>"))
  233. {
  234. msg = msg.Replace("<<dog_name>>", dog.dogProperty.dog_name);
  235. }
  236. MessageBoxController.ShowMessage(msg);
  237. var BGM = GameObject.Find("BGM");
  238. if (BGM != null)
  239. {
  240. FadeBGM(BGM.GetComponent<AudioSource>(), false);
  241. }
  242. isTrainingMsgShowed_1 = true;
  243. }
  244. else if (!isTrainingMsgShowed_2 && isTrainingMsgShowed_1 && currentTrainingTimes == 1)
  245. {
  246. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_01", EnviromentSetting.languageCode });
  247. if (msg.Contains("<<dog_name>>"))
  248. {
  249. msg = msg.Replace("<<dog_name>>", dog.dogProperty.dog_name);
  250. }
  251. MessageBoxController.ShowMessage(msg);
  252. isTrainingMsgShowed_2 = true;
  253. }
  254. }
  255. }
  256. else
  257. {
  258. // 暂时将其他非训练状态的狗game object隐藏
  259. //dog.gameObject.SetActive(false);
  260. }
  261. }
  262. }
  263. else if (sceneMode == SceneMode.INACTIVE) // 这段代码控制场景在交互模式
  264. {
  265. foreach (var dog in dogsInScene)
  266. {
  267. if (dog.dogState == DogState.INTERACT)
  268. {
  269. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  270. dogCam.Priority = 10;
  271. // 单只狗在交互的状态控制代码
  272. if (dog.isMovingToPlayer)
  273. {
  274. dog.MovetoPlayer();
  275. }
  276. else if (dog.InteractTimeout()) // 如果交互时间结束,结束交互状态
  277. {
  278. dog.ExitInteract();
  279. sceneMode = SceneMode.NORMAL; // 交互结束,退出交互状态
  280. //isInteractMode = false; // 交互结束,退出交互状态
  281. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  282. }
  283. else
  284. {
  285. PointerOnDog(); // 检测是否点击在狗上
  286. }
  287. }
  288. }
  289. }
  290. else
  291. {
  292. // 普通场景下的控制代码
  293. foreach (var dog in dogsInScene)
  294. {
  295. // 如果在eat drink进程结束前不执行随机场景代码
  296. // 恢复因为交互,训练模式隐藏的狗
  297. //if (dog.gameObject.activeSelf == false)
  298. //{
  299. // dog.gameObject.SetActive(true);
  300. //}
  301. if (dog.dogState == DogState.ITEM_CONSUME)
  302. {
  303. if (dog.isMovingToBowl)
  304. {
  305. dog.MovetoBowl();
  306. }
  307. }
  308. else
  309. {
  310. // 随机动作控制控制
  311. RandomCameraChange();
  312. if (listenBreak) // 如果用户按下说话按键,立刻切换到监听状态
  313. {
  314. dog.Listen();
  315. // StartCoroutine(dog.RotationToPlayerAndListen());
  316. }
  317. else if (dog.isMoving)
  318. {
  319. dog.RandomMove();
  320. }
  321. else if (sceneRandomFactor == dog.randomFactor && !dog.isSleeping) // 当狗自身的随机数和系统随机数相同时候触发。约100秒触发一次。
  322. {
  323. TimeSpan ts = DateTime.Now - dog.animationStartTime;
  324. if (ts.Seconds >= 30) // 如果距离上一个动作超过30秒就可以开始新的动作
  325. {
  326. float r = UnityEngine.Random.Range(0, 1f);
  327. if (r > 0.6) // 随机选择开始动画,或者移动
  328. {
  329. dog.IdleAnimation();
  330. }
  331. else // 狗狗开始步行移动
  332. {
  333. dog.SetMoveSpeed(0);
  334. dog.moveSpeed = 0;
  335. dog.RandomMove();
  336. }
  337. }
  338. }
  339. }
  340. }
  341. }
  342. #endregion
  343. }
  344. }
  345. private void OnDestroy()
  346. {
  347. Debug.Log("Home scene is destoried.");
  348. }
  349. IEnumerator InitialScene()
  350. {
  351. yield return null; // 跳过三帧,初始化最多三只狗
  352. //Debug.Log(isInitialDone);
  353. foreach (var dog in UserProperty.dogs)
  354. {
  355. DogInScene dogInScene = new DogInScene(dog);
  356. float x = UnityEngine.Random.Range(-1f, 1f); // 随机生成位置,考虑到手机评估宽度限制宽度
  357. float z = UnityEngine.Random.Range(0f, 5f); // 随机生成位置,考虑且保持和用户距离
  358. float y = UnityEngine.Random.Range(90f, 270f); // 随机生成朝向,且面向用户
  359. var initPosition = new Vector3(x, 0, z);
  360. StartCoroutine(DogComponentInstaller(dog)); // 加载狗的其他组件
  361. var dogGameObject = GameObject.Find(dog.dog_name);
  362. if (dogGameObject == null)
  363. {
  364. Debug.Log(dog.dog_name + "is not found in Home Controller");
  365. }
  366. dogGameObject.transform.position = initPosition;
  367. dogGameObject.transform.rotation = Quaternion.Euler(0, y, 0);
  368. dogGameObject.transform.localScale = new Vector3(2, 2, 2);
  369. dogInScene.SetGameObject(dogGameObject);
  370. dogsInScene.Add(dogInScene);
  371. }
  372. }
  373. // 加载狗的其他组件
  374. IEnumerator DogComponentInstaller(DogProperty dogProperty)
  375. {
  376. // 等待一帧,确保所有 Start() 方法都执行完成
  377. yield return null;
  378. // 第一帧以后开始执行
  379. GameObject dog = GameObject.Find(dogProperty.dog_name);
  380. // 加载指定的Animator controller
  381. Animator animator = dog.GetComponent<Animator>();
  382. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController");
  383. if (dogProperty.breed == "shibaInu") { animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController"); }
  384. animator.runtimeAnimatorController = animatorController;
  385. // 加载Rigidbody
  386. Rigidbody rigidbody = dog.AddComponent<Rigidbody>();
  387. //rigidbody.isKinematic = true;
  388. rigidbody.mass = 10;
  389. rigidbody.linearDamping = 10;
  390. rigidbody.angularDamping = 10;
  391. //rigidbody.freezeRotation = true;
  392. rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;
  393. rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
  394. rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
  395. // 加载box collider
  396. BoxCollider boxCollider = dog.AddComponent<BoxCollider>();
  397. // boxCollider.isTrigger = false;
  398. boxCollider.center = new Vector3(0, 0.25f, 0);
  399. boxCollider.size = new Vector3(0.12f, 0.45f, 0.54f);
  400. boxCollider.isTrigger = true;
  401. // 加载Particle Question Mark
  402. ParticleSystem questionMarkParticle = Resources.Load<ParticleSystem>("Home/Particle_QuestionMark");
  403. questionMarkParticle = Instantiate(questionMarkParticle);
  404. questionMarkParticle.name = "QuestionMarkParticle";
  405. questionMarkParticle.transform.SetParent(dog.transform);
  406. questionMarkParticle.transform.localPosition = new Vector3(0, 0.6f, 0.4f);
  407. questionMarkParticle.transform.localRotation = Quaternion.Euler(-90, 0, 0);
  408. ParticleSystem ps = questionMarkParticle.GetComponent<ParticleSystem>();
  409. ps.Stop();
  410. // 加载sleep particle
  411. ParticleSystem zzzParticle = Resources.Load<ParticleSystem>("Home/Particle_Z");
  412. zzzParticle = Instantiate(zzzParticle);
  413. zzzParticle.name = "zzzParticle";
  414. zzzParticle.transform.SetParent(dog.gameObject.transform);
  415. zzzParticle.transform.localPosition = new Vector3(0.05f, 0.2f, 0.2f);
  416. zzzParticle.transform.localRotation = Quaternion.Euler(-90, 0, 0);
  417. zzzParticle.gameObject.SetActive(false); // 默认关闭
  418. // 添加DogCollisionController
  419. DogCollisionController dogCollisionController = dog.AddComponent<DogCollisionController>();
  420. //yield return null;
  421. }
  422. #region 语音控制区
  423. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  424. public void VoiceCallRequest(string filePath)
  425. {
  426. Debug.Log("Voice Call Post request");
  427. string url = "/api/voice/call/";
  428. WWWForm form = new();
  429. form.AddField("user_id", UserProperty.userId);
  430. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCallCallback));
  431. }
  432. // 语音呼唤上传回调函数
  433. void VoiceCallCallback(string json)
  434. {
  435. Debug.Log("Voice call callback");
  436. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  437. if (data != null && data["status"].ToString() == "success")
  438. {
  439. // 刷新狗的数据
  440. string dogJson = data["dogs"].ToString();
  441. UserProperty.RefreshDogInfo(dogJson);
  442. // TODO 根据返回结果设定focusdog
  443. float highestScore = 0;
  444. string highestScoreDogId = String.Empty;
  445. var scores = data["call Score MFCC"].ToString();
  446. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  447. foreach (var score in scoresList)
  448. {
  449. // 根据狗的数量度修正得分。计算方式为狗的voiceCall属性值/1000
  450. int dogIndex = UserProperty.GetDogIndexById(score.Key);
  451. if (dogIndex < 0)
  452. {
  453. continue;
  454. }
  455. float scoreFactor = UserProperty.dogs[dogIndex].voiceCall / 1000f;
  456. float adjScore = score.Value + scoreFactor;
  457. if (adjScore > 1)
  458. {
  459. adjScore = 1;
  460. }
  461. if (adjScore > highestScore)
  462. {
  463. highestScore = adjScore;
  464. highestScoreDogId = score.Key;
  465. }
  466. }
  467. if (highestScore >= EnviromentSetting.voiceRecognitionScore) // 60分以上才可以进入交互模式
  468. {
  469. GameData.focusDog = UserProperty.GetDogIndexById(highestScoreDogId);
  470. sceneMode = SceneMode.INACTIVE; // 交互模式
  471. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  472. foreach (var dog in dogsInScene)
  473. {
  474. if (dog.dogProperty.d_id == highestScoreDogId)
  475. {
  476. // if (GameTool.Random100Check(dog.dogProperty.voiceCall))
  477. // {
  478. // dog.SetupInteract();
  479. interactDog = dog.gameObject;
  480. // focusdog 开启互动模式
  481. // HomeController.dogsInScene[GameData.focusDog].dogState = DogState.INTERACT;
  482. HomeController.dogsInScene[GameData.focusDog].SetupInteract();
  483. // 其他狗进入隐藏模式(先保留代码)
  484. //foreach (var otherDog in dogsInScene)
  485. //{
  486. // if (otherDog.dogProperty.d_id != highestScoreDogId)
  487. // {
  488. // otherDog.gameObject.SetActive(false);
  489. // }
  490. //}
  491. }
  492. }
  493. HomeSoundEffectController.Instance.PlaySoundEffect(5);
  494. }
  495. else
  496. {
  497. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  498. }
  499. }
  500. else
  501. {
  502. Debug.Log(data["message"]);
  503. }
  504. }
  505. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  506. public void VoiceCommandRequest(string filePath)
  507. {
  508. //Debug.Log("Voice Command Post request");
  509. if (sceneMode == SceneMode.INACTIVE)
  510. {
  511. Debug.Log("Voice Command Post request");
  512. string url = "/api/voice/command/";
  513. WWWForm form = new();
  514. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  515. form.AddField("user_id", UserProperty.userId);
  516. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  517. // 打印时间
  518. Debug.Log("Voice command training request at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  519. }
  520. else if (sceneMode == SceneMode.TRAINING)
  521. {
  522. //Debug.Log("current times before ++:" + this.currentTrainingTimes.ToString());
  523. this.currentTrainingTimes++;
  524. string url = "/api/voice/training/";
  525. WWWForm form = new();
  526. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  527. form.AddField("user_id", UserProperty.userId);
  528. form.AddField("voice_type", trainingContent);
  529. form.AddField("current_times", this.currentTrainingTimes);
  530. //Debug.Log("current times after ++:" + this.currentTrainingTimes.ToString());
  531. form.AddField("total_times", totalTrainingTimes);
  532. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  533. }
  534. }
  535. // 语音呼唤上传回调函数
  536. void VoiceCommandCallback(string json)
  537. {
  538. // 打印返回时间
  539. Debug.Log("Voice command callback at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  540. if (sceneMode == SceneMode.INACTIVE)
  541. {
  542. Debug.Log("Voice command callback");
  543. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  544. if (data != null && data["status"].ToString() == "success")
  545. {
  546. // 刷新狗的数据
  547. string dogJson = data["dogs"].ToString();
  548. UserProperty.RefreshDogInfo(dogJson);
  549. // 找到得分最高的指令
  550. float highestScore = 0;
  551. string highestScoreCommand = "";
  552. string scores = data["commandScoreMFCC"].ToString();
  553. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  554. foreach (var score in scoresList)
  555. {
  556. if (score.Value > highestScore)
  557. {
  558. highestScore = score.Value;
  559. highestScoreCommand = score.Key;
  560. }
  561. }
  562. // 根据狗的voiceCommand属性值修正得分。计算方式为狗的voiceCommand属性值/1000
  563. highestScore += UserProperty.dogs[GameData.focusDog].voiceCommand / 1000f;
  564. if (highestScore > 1)
  565. {
  566. highestScore = 1;
  567. }
  568. Debug.Log("Highest score:" + highestScore.ToString());
  569. Debug.Log("Highest command:" + highestScoreCommand);
  570. dogsInScene[GameData.focusDog].ResetAnimationStatus(); // 重置狗的动画状态
  571. if (highestScore >= EnviromentSetting.voiceRecognitionScore)
  572. {
  573. string animationTrigger = highestScoreCommand.Substring(7);
  574. string animationBool = animationTrigger + "_status";
  575. var animator = dogsInScene[GameData.focusDog].gameObject.GetComponent<Animator>();
  576. if (highestScoreCommand == "commandBark")
  577. {
  578. DogBarkController.Instance.PlayDogBarkWithDelay(3); // 狗叫相应一下
  579. }
  580. else
  581. {
  582. HomeSoundEffectController.Instance.PlaySoundEffect(5);
  583. }
  584. //animator.SetTrigger(animationTrigger);
  585. animator.Play(animationTrigger);
  586. string[] noStatusCommand = { "turnL", "turnR" };
  587. if (Array.IndexOf(noStatusCommand, animationTrigger) < 0)
  588. {
  589. animator.SetBool(animationBool, true);
  590. Debug.Log(animationBool + " is " + animator.GetBool(animationBool));
  591. }
  592. else
  593. {
  594. // turnL 和 turnR 动画不需要设置状态
  595. }
  596. // animator.SetBool(animationBool, true);
  597. // 交互动画执行一段时间后停止
  598. dogsInScene[GameData.focusDog].interactAnimationStartTime = DateTime.Now;
  599. StartCoroutine(dogsInScene[GameData.focusDog].InteractAnimationCountDown());
  600. }
  601. else
  602. {
  603. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  604. dogsInScene[GameData.focusDog].PlayQuestionMark();
  605. }
  606. }
  607. else
  608. {
  609. Debug.Log(data["message"]);
  610. }
  611. }
  612. else if (sceneMode == SceneMode.TRAINING)
  613. {
  614. Debug.Log("Voice training Callback");
  615. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  616. if (data != null && data["status"].ToString().ToLower() == "success")
  617. {
  618. if (data["message"].ToString().ToLower() == "pass")
  619. {
  620. // 刷新狗的数据,包含dogsInScene
  621. string dogJson = data["dogs"].ToString();
  622. UserProperty.RefreshDogInfo(dogJson);
  623. var trainingDog = dogsInScene[GameData.focusDog];
  624. trainingDog.ReloadDogProperty(); // 刷新狗的数据
  625. // 成功后让狗子播放训练的动画
  626. if (trainingContent != "voiceCall")
  627. {
  628. string command = trainingContent.Substring(7);
  629. trainingDog.animator.SetTrigger(command);
  630. // string[] noStatusCommand = { "apple", "banana", "cherry" };
  631. trainingDog.animator.SetBool(command + "_status", true);
  632. }
  633. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_10", EnviromentSetting.languageCode });
  634. if (msg.Contains("<<dog_name>>"))
  635. {
  636. msg = msg.Replace("<<dog_name>>", interactDog.name);
  637. }
  638. GameTool.PauseGameTime();
  639. MessageBoxController.ShowMessage(msg, ExitTrainingMode);
  640. this.sceneMode = SceneMode.NORMAL;
  641. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  642. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  643. }
  644. else if (data["message"].ToString() == "fail")
  645. {
  646. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  647. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  648. if (msg.Contains("<<dog_name>>"))
  649. {
  650. msg = msg.Replace("<<dog_name>>", interactDog.name);
  651. }
  652. GameTool.PauseGameTime();
  653. MessageBoxController.ShowMessage(msg, RestartTraining);
  654. }
  655. }
  656. else
  657. {
  658. Debug.Log(data["message"]);
  659. if (EnviromentSetting.runEnv == "Release")
  660. {
  661. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  662. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  663. if (msg.Contains("<<dog_name>>"))
  664. {
  665. msg = msg.Replace("<<dog_name>>", interactDog.name);
  666. }
  667. GameTool.PauseGameTime();
  668. MessageBoxController.ShowMessage(msg, RestartTraining);
  669. }
  670. }
  671. SetDogsIsTrigger(true);
  672. }
  673. }
  674. #endregion
  675. #region interact mode
  676. // 重置training相关参数
  677. private void ExitTrainingMode()
  678. {
  679. foreach (var dog in dogsInScene)
  680. {
  681. if (dog.dogProperty.d_id == trainingDogId)
  682. {
  683. dog.ExitInteract();
  684. }
  685. }
  686. trainingContent = String.Empty;
  687. totalTrainingTimes = 2;
  688. currentTrainingTimes = 0;
  689. trainingDogId = "";
  690. isTrainingMsgShowed_1 = false;
  691. isTrainingMsgShowed_2 = false;
  692. isTrainingAnimationPlayed = false;
  693. sceneMode = SceneMode.NORMAL; // 交互模式
  694. Debug.Log("Reset Training Mode Parameters");
  695. GameTool.ResumeGameTime();
  696. GameData.SetIsVoiceTrainingToday(); // 训练完成,设置为true
  697. var BGM = GameObject.Find("BGM");
  698. if (BGM != null)
  699. {
  700. FadeBGM(BGM.GetComponent<AudioSource>(), true);
  701. }
  702. }
  703. private void RestartTraining()
  704. {
  705. currentTrainingTimes = 0;
  706. isTrainingMsgShowed_1 = false;
  707. isTrainingMsgShowed_2 = false;
  708. Time.timeScale = 1f;
  709. }
  710. // 改变Voice And Menu 菜单形态
  711. public void VoiceButtonOnlySwitch(bool state)
  712. {
  713. // 交互时候关闭其他菜单
  714. var vamUI = GameObject.Find("VoiceAndMenu");
  715. if (vamUI != null)
  716. {
  717. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  718. var voiceController = UIdocument.GetComponent<VoiceController>();
  719. voiceController.isCommandMode = state;
  720. }
  721. }
  722. // 检测是否点击在狗上
  723. void PointerOnDog()
  724. {
  725. //DetectTouchMethod();
  726. // 检查当前指针是否有效
  727. if (Pointer.current == null) return;
  728. // 获取当前指针的悬浮位置
  729. Vector2 pointerPosition = Pointer.current.position.ReadValue();
  730. var mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
  731. Ray ray = mainCamera.ScreenPointToRay(pointerPosition);
  732. if (Physics.Raycast(ray, out RaycastHit hit))
  733. {
  734. //Debug.Log($"Clicked on: {hit.collider.gameObject.name}");
  735. // 射线检测起始点击是否在狗上
  736. if (hit.collider.gameObject == interactDog)
  737. {
  738. if (previousPointerPosition != pointerPosition)
  739. {
  740. interactTime += Time.deltaTime;
  741. Debug.Log("interactTime:" + interactTime);
  742. foreach (var dog in dogsInScene)
  743. {
  744. if (dog.gameObject == interactDog)
  745. {
  746. dog.interactLastUpdate = DateTime.Now;
  747. }
  748. }
  749. previousPointerPosition = pointerPosition;
  750. }
  751. }
  752. if (interactTime > 2.5) // 如果交互时间超过1秒,播放心形粒子效果
  753. {
  754. HeartParticlePlay();
  755. DogBarkController.Instance.PlayDogBarkWithDelay(1); // 狗叫相应一下
  756. }
  757. }
  758. }
  759. void HeartParticlePlay()
  760. {
  761. // 播放心形粒子效果
  762. var heartParticle = GameObject.Find("Particle Heart");
  763. heartParticle.GetComponent<ParticleSystem>().Play();
  764. interactTime = 0;
  765. }
  766. public void SetInteractDog(GameObject dog)
  767. {
  768. interactDog = dog;
  769. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  770. dogCam.Priority = 10;
  771. }
  772. #endregion
  773. #region 场景环境控制
  774. // 淡入或淡出背景音乐
  775. private void FadeBGM(AudioSource bgmSource, bool fadeIn, float duration = 2f)
  776. {
  777. // fadeIn: true表示淡入 false表示淡出
  778. if (bgmSource == null) return; // 如果没有 AudioSource,则直接返回
  779. StartCoroutine(FadeBGMCoroutine(bgmSource, fadeIn, duration));
  780. }
  781. private IEnumerator FadeBGMCoroutine(AudioSource bgmSource, bool fadeIn, float duration)
  782. {
  783. float elapsedTime = 0f;
  784. float startVolume = bgmSource.volume;
  785. float targetVolume = fadeIn ? 0.4f : 0f; // 淡入目标音量为1,淡出目标音量为0
  786. while (elapsedTime < duration)
  787. {
  788. bgmSource.volume = Mathf.Lerp(startVolume, targetVolume, elapsedTime / duration);
  789. elapsedTime += Time.deltaTime;
  790. yield return null;
  791. }
  792. bgmSource.volume = targetVolume; // 确保音量达到目标值
  793. if (!fadeIn)
  794. {
  795. bgmSource.Stop(); // 如果是淡出,停止播放
  796. }
  797. else
  798. {
  799. bgmSource.Play(); // 如果是淡入,开始播放
  800. }
  801. }
  802. // 设置场景模式
  803. public void SetSceneMode(SceneMode mode)
  804. {
  805. this.sceneMode = mode;
  806. }
  807. // 刷新dogInScene的狗数据
  808. public void RefreshDogInScene()
  809. {
  810. foreach (var dog in dogsInScene)
  811. {
  812. dog.ReloadDogProperty();
  813. }
  814. }
  815. // 场景随机切换镜头看向不同的狗
  816. void RandomCameraChange()
  817. {
  818. int delay = 10; // 延迟10秒执行一次
  819. TimeSpan ts = DateTime.Now - lastCameraChange;
  820. if (ts.TotalSeconds < delay) { return; }
  821. int dogCount = dogsInScene.Count;
  822. int r = UnityEngine.Random.Range(0, dogCount + 1);
  823. if (r < dogCount)
  824. {
  825. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  826. dogCam.Priority = 10;
  827. playerCam.Priority = 1;
  828. }
  829. else
  830. {
  831. dogCam.Priority = 1;
  832. playerCam.Priority = 10;
  833. }
  834. lastCameraChange = DateTime.Now;
  835. }
  836. // 检测场景是否初始化完成
  837. bool SceneInitialCheck()
  838. {
  839. bool initDone = true;
  840. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  841. {
  842. foreach (var dog in dogsInScene)
  843. {
  844. if (dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  845. {
  846. initDone = false;
  847. }
  848. }
  849. }
  850. else
  851. {
  852. initDone = false;
  853. }
  854. //Debug.Log("Home scene initial status:"+initDone);
  855. return initDone;
  856. }
  857. // 计算多只狗的中心位置,用于主摄像机瞄准
  858. private Vector3 CenterOfDogs()
  859. {
  860. if (dogsInScene.Count == 0)
  861. {
  862. return Vector3.zero;
  863. }
  864. Vector3 center = Vector3.zero;
  865. foreach (var dog in dogsInScene)
  866. {
  867. center += dog.gameObject.transform.position;
  868. }
  869. center /= dogsInScene.Count;
  870. return center;
  871. }
  872. // 设置所有狗is trigger属性
  873. public void SetDogsIsTrigger(bool triggerSetting)
  874. {
  875. foreach (var dog in dogsInScene)
  876. {
  877. BoxCollider boxCollider = dog.gameObject.GetComponent<BoxCollider>();
  878. if (boxCollider != null)
  879. {
  880. boxCollider.isTrigger = triggerSetting;
  881. }
  882. }
  883. }
  884. #endregion
  885. #region 道具使用控制
  886. public IEnumerator HideBowlAfterItemConsume(ItemGroup type)
  887. {
  888. isHideBowlRunning = true; // 设置为正在运行状态
  889. string inTheBowl;
  890. string bowlName;
  891. if (type == ItemGroup.FOOD)
  892. {
  893. inTheBowl = "Food";
  894. bowlName = "Bowl_food";
  895. }
  896. else if (type == ItemGroup.WATER)
  897. {
  898. inTheBowl = "Water";
  899. bowlName = "Bowl_water";
  900. }
  901. else
  902. {
  903. yield break; // 如果类型不匹配,直接返回
  904. }
  905. bool allDogsDone = false;
  906. while (!allDogsDone)
  907. {
  908. allDogsDone = true; // 假设所有狗都完成了
  909. foreach (var dog in dogsInScene)
  910. {
  911. if (dog.dogState == DogState.ITEM_CONSUME)
  912. {
  913. allDogsDone = false; // 如果有狗还在消耗状态,则设置为false
  914. break;
  915. }
  916. }
  917. yield return new WaitForSeconds(0.5f); // 每0.5秒检查一次
  918. }
  919. var food = GameObject.Find(inTheBowl);
  920. var targetBowl = GameObject.Find(bowlName);
  921. food.transform.localPosition = new Vector3(-1, -10, -1);
  922. yield return new WaitForSeconds(2f); // 暂停2秒
  923. targetBowl.transform.position = new Vector3(-1, -10, -1); // 将饭盆回归原位
  924. food.transform.localPosition = Vector3.zero; // 将食物回归原位
  925. // 重制摄像头和菜单
  926. HomeController.dogCam.Priority = 1;
  927. HomeController.playerCam.Priority = 10;
  928. var uiPlaceholder = GameObject.Find("UI Placeholder");
  929. var vamUI = uiPlaceholder.transform.Find("VoiceAndMenu").gameObject;
  930. vamUI.SetActive(true);
  931. isHideBowlRunning = false; // 设置为不在运行状态
  932. }
  933. #endregion
  934. }
  935. public enum ItemGroup
  936. {
  937. FOOD,
  938. WATER
  939. }
  940. public enum SceneMode
  941. {
  942. TRAINING,
  943. INACTIVE,
  944. NORMAL,
  945. }