HomeController.cs 37 KB

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