HomeController.cs 34 KB

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