HomeController.cs 38 KB

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