HomeController.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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.commandShake)
  146. {
  147. trainingContent = "commandShake";
  148. }
  149. else if (GameTool.IntBetween(20, 40, random) && !dog.dogProperty.commandTouch)
  150. {
  151. trainingContent = "commandTouch";
  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. boxCollider.isTrigger = true;
  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. // 添加DogCollisionController
  406. DogCollisionController dogCollisionController = dog.AddComponent<DogCollisionController>();
  407. //yield return null;
  408. }
  409. // 场景随机切换镜头看向不同的狗
  410. void RandomCameraChange()
  411. {
  412. int delay = 10; // 延迟10秒执行一次
  413. TimeSpan ts = DateTime.Now - lastCameraChange;
  414. if (ts.TotalSeconds < delay) { return; }
  415. int dogCount = dogsInScene.Count;
  416. int r = UnityEngine.Random.Range(0, dogCount + 1);
  417. if (r < dogCount)
  418. {
  419. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  420. dogCam.Priority = 10;
  421. playerCam.Priority = 1;
  422. }
  423. else
  424. {
  425. dogCam.Priority = 1;
  426. playerCam.Priority = 10;
  427. }
  428. lastCameraChange = DateTime.Now;
  429. }
  430. // 检测场景是否初始化完成
  431. bool SceneInitialCheck()
  432. {
  433. bool initDone = true;
  434. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  435. {
  436. foreach (var dog in dogsInScene)
  437. {
  438. if (dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  439. {
  440. initDone = false;
  441. }
  442. }
  443. }
  444. else
  445. {
  446. initDone = false;
  447. }
  448. //Debug.Log("Home scene initial status:"+initDone);
  449. return initDone;
  450. }
  451. // 计算多只狗的中心位置,用于主摄像机瞄准
  452. private Vector3 CenterOfDogs()
  453. {
  454. if (dogsInScene.Count == 0)
  455. {
  456. return Vector3.zero;
  457. }
  458. Vector3 center = Vector3.zero;
  459. foreach (var dog in dogsInScene)
  460. {
  461. center += dog.gameObject.transform.position;
  462. }
  463. center /= dogsInScene.Count;
  464. return center;
  465. }
  466. #region 语音控制区
  467. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  468. public void VoiceCallRequest(string filePath)
  469. {
  470. Debug.Log("Voice Call Post request");
  471. string url = "/api/voice/call/";
  472. WWWForm form = new();
  473. form.AddField("user_id", UserProperty.userId);
  474. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCallCallback));
  475. }
  476. // 语音呼唤上传回调函数
  477. void VoiceCallCallback(string json)
  478. {
  479. Debug.Log("Voice call callback");
  480. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  481. if (data != null && data["status"].ToString() == "success")
  482. {
  483. // 刷新狗的数据
  484. string dogJson = data["dogs"].ToString();
  485. UserProperty.FreshDogInfo(dogJson);
  486. // TODO 根据返回结果设定focusdog
  487. float highestScore = 0;
  488. string highestScoreDogId = String.Empty;
  489. var scores = data["call Score MFCC"].ToString();
  490. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  491. foreach (var score in scoresList)
  492. {
  493. // 根据狗的数量度修正得分。计算方式为狗的voiceCall属性值/1000
  494. int dogIndex = UserProperty.GetDogIndexById(score.Key);
  495. if (dogIndex < 0)
  496. {
  497. continue;
  498. }
  499. float scoreFactor = UserProperty.dogs[dogIndex].voiceCall / 1000f;
  500. float adjScore = score.Value + scoreFactor;
  501. if (adjScore > 1)
  502. {
  503. adjScore = 1;
  504. }
  505. if (adjScore > highestScore)
  506. {
  507. highestScore = adjScore;
  508. highestScoreDogId = score.Key;
  509. }
  510. }
  511. if (highestScore >= EnviromentSetting.voiceRecognitionScore) // 60分以上才可以进入交互模式
  512. {
  513. GameData.focusDog = UserProperty.GetDogIndexById(highestScoreDogId);
  514. sceneMode = SceneMode.INACTIVE; // 交互模式
  515. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  516. foreach (var dog in dogsInScene)
  517. {
  518. if (dog.dogProperty.d_id == highestScoreDogId)
  519. {
  520. // if (GameTool.Random100Check(dog.dogProperty.voiceCall))
  521. // {
  522. // dog.SetupInteract();
  523. interactDog = dog.gameObject;
  524. // focusdog 开启互动模式
  525. // HomeController.dogsInScene[GameData.focusDog].dogState = DogState.INTERACT;
  526. HomeController.dogsInScene[GameData.focusDog].SetupInteract();
  527. // 其他狗进入隐藏模式(先保留代码)
  528. //foreach (var otherDog in dogsInScene)
  529. //{
  530. // if (otherDog.dogProperty.d_id != highestScoreDogId)
  531. // {
  532. // otherDog.gameObject.SetActive(false);
  533. // }
  534. //}
  535. }
  536. }
  537. HomeSoundEffectController.Instance.PlaySoundEffect(5);
  538. }
  539. else
  540. {
  541. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  542. }
  543. }
  544. else
  545. {
  546. Debug.Log(data["message"]);
  547. }
  548. }
  549. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  550. public void VoiceCommandRequest(string filePath)
  551. {
  552. //Debug.Log("Voice Command Post request");
  553. if (sceneMode == SceneMode.INACTIVE)
  554. {
  555. Debug.Log("Voice Command Post request");
  556. string url = "/api/voice/command/";
  557. WWWForm form = new();
  558. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  559. form.AddField("user_id", UserProperty.userId);
  560. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  561. }
  562. else if (sceneMode == SceneMode.TRAINING)
  563. {
  564. //Debug.Log("current times before ++:" + this.currentTrainingTimes.ToString());
  565. this.currentTrainingTimes++;
  566. string url = "/api/voice/training/";
  567. WWWForm form = new();
  568. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  569. form.AddField("user_id", UserProperty.userId);
  570. form.AddField("voice_type", trainingContent);
  571. form.AddField("current_times", this.currentTrainingTimes);
  572. //Debug.Log("current times after ++:" + this.currentTrainingTimes.ToString());
  573. form.AddField("total_times", totalTrainingTimes);
  574. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  575. }
  576. }
  577. // 语音呼唤上传回调函数
  578. void VoiceCommandCallback(string json)
  579. {
  580. if (sceneMode == SceneMode.INACTIVE)
  581. {
  582. Debug.Log("Voice command callback");
  583. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  584. if (data != null && data["status"].ToString() == "success")
  585. {
  586. // 刷新狗的数据
  587. string dogJson = data["dogs"].ToString();
  588. UserProperty.FreshDogInfo(dogJson);
  589. // 找到得分最高的指令
  590. float highestScore = 0;
  591. string highestScoreCommand = "";
  592. string scores = data["commandScoreMFCC"].ToString();
  593. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  594. foreach (var score in scoresList)
  595. {
  596. if (score.Value > highestScore)
  597. {
  598. highestScore = score.Value;
  599. highestScoreCommand = score.Key;
  600. }
  601. }
  602. // 根据狗的voiceCommand属性值修正得分。计算方式为狗的voiceCommand属性值/1000
  603. highestScore += UserProperty.dogs[GameData.focusDog].voiceCommand / 1000f;
  604. if (highestScore > 1)
  605. {
  606. highestScore = 1;
  607. }
  608. Debug.Log("Highest score:" + highestScore.ToString());
  609. Debug.Log("Highest command:" + highestScoreCommand);
  610. dogsInScene[GameData.focusDog].ResetAnimationStatus(); // 重置狗的动画状态
  611. if (highestScore >= EnviromentSetting.voiceRecognitionScore)
  612. {
  613. string animationTrigger = highestScoreCommand.Substring(7);
  614. string animationBool = animationTrigger + "_status";
  615. var animator = dogsInScene[GameData.focusDog].gameObject.GetComponent<Animator>();
  616. if (highestScoreCommand == "commandBark")
  617. {
  618. DogBarkController.Instance.PlayDogBarkWithDelay(3); // 狗叫相应一下
  619. }
  620. else
  621. {
  622. HomeSoundEffectController.Instance.PlaySoundEffect(5);
  623. }
  624. //animator.SetTrigger(animationTrigger);
  625. animator.Play(animationTrigger);
  626. animator.SetBool(animationBool, true);
  627. // 交互动画执行一段时间后停止
  628. StartCoroutine(dogsInScene[GameData.focusDog].InteractAnimationCountDown());
  629. }
  630. else
  631. {
  632. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  633. dogsInScene[GameData.focusDog].PlayQuestionMark();
  634. }
  635. }
  636. else
  637. {
  638. Debug.Log(data["message"]);
  639. }
  640. }
  641. else if (sceneMode == SceneMode.TRAINING)
  642. {
  643. Debug.Log("Voice training Callback");
  644. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  645. if (data != null && data["status"].ToString().ToLower() == "success")
  646. {
  647. if (data["message"].ToString().ToLower() == "pass")
  648. {
  649. // 刷新狗的数据,包含dogsInScene
  650. string dogJson = data["dogs"].ToString();
  651. UserProperty.FreshDogInfo(dogJson);
  652. var trainingDog = dogsInScene[GameData.focusDog];
  653. trainingDog.ReloadDogProperty(); // 刷新狗的数据
  654. // 成功后让狗子播放训练的动画
  655. if (trainingContent != "voiceCall")
  656. {
  657. string command = trainingContent.Substring(7);
  658. trainingDog.animator.SetTrigger(command);
  659. trainingDog.animator.SetBool("is" + command + "ing", true);
  660. }
  661. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_10", EnviromentSetting.languageCode });
  662. if (msg.Contains("<<dog_name>>"))
  663. {
  664. msg = msg.Replace("<<dog_name>>", interactDog.name);
  665. }
  666. GameTool.PauseGameTime();
  667. MessageBoxController.ShowMessage(msg, ExitTrainingMode);
  668. this.sceneMode = SceneMode.NORMAL;
  669. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  670. GameData.isVoiceTrainingToday = true; // 训练完成,设置为true
  671. string todayDate = System.DateTime.Now.ToString("yyyy-MM-dd");
  672. PlayerPrefs.SetString("lastTrainingDate", todayDate);
  673. PlayerPrefs.Save();
  674. }
  675. else if (data["message"].ToString() == "fail")
  676. {
  677. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  678. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  679. if (msg.Contains("<<dog_name>>"))
  680. {
  681. msg = msg.Replace("<<dog_name>>", interactDog.name);
  682. }
  683. GameTool.PauseGameTime();
  684. MessageBoxController.ShowMessage(msg, RestartTraining);
  685. }
  686. }
  687. else
  688. {
  689. Debug.Log(data["message"]);
  690. if (EnviromentSetting.runEnv == "Release")
  691. {
  692. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  693. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  694. if (msg.Contains("<<dog_name>>"))
  695. {
  696. msg = msg.Replace("<<dog_name>>", interactDog.name);
  697. }
  698. GameTool.PauseGameTime();
  699. MessageBoxController.ShowMessage(msg, RestartTraining);
  700. }
  701. }
  702. }
  703. }
  704. #endregion
  705. #region interact mode
  706. // 重置training相关参数
  707. private void ExitTrainingMode()
  708. {
  709. foreach (var dog in dogsInScene)
  710. {
  711. if (dog.dogProperty.d_id == trainingDogId)
  712. {
  713. dog.ExitInteract();
  714. }
  715. }
  716. trainingContent = String.Empty;
  717. totalTrainingTimes = 2;
  718. currentTrainingTimes = 0;
  719. trainingDogId = "";
  720. isTrainingMsgShowed_1 = false;
  721. isTrainingMsgShowed_2 = false;
  722. isTrainingAnimationPlayed = false;
  723. sceneMode = SceneMode.NORMAL; // 交互模式
  724. Debug.Log("Reset Training Mode Parameters");
  725. GameTool.ResumeGameTime();
  726. GameData.isVoiceTrainingToday = true; // 训练完成,设置为true
  727. var BGM = GameObject.Find("BGM");
  728. if (BGM != null)
  729. {
  730. FadeBGM(BGM.GetComponent<AudioSource>(), true);
  731. }
  732. }
  733. private void RestartTraining()
  734. {
  735. currentTrainingTimes = 0;
  736. isTrainingMsgShowed_1 = false;
  737. isTrainingMsgShowed_2 = false;
  738. Time.timeScale = 1f;
  739. }
  740. // 改变Voice And Menu 菜单形态
  741. public void VoiceButtonOnlySwitch(bool state)
  742. {
  743. // 交互时候关闭其他菜单
  744. var vamUI = GameObject.Find("VoiceAndMenu");
  745. if (vamUI != null)
  746. {
  747. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  748. var voiceController = UIdocument.GetComponent<VoiceController>();
  749. voiceController.isCommandMode = state;
  750. }
  751. }
  752. // 检测是否点击在狗上
  753. void PointerOnDog()
  754. {
  755. //DetectTouchMethod();
  756. // 检查当前指针是否有效
  757. if (Pointer.current == null) return;
  758. // 获取当前指针的悬浮位置
  759. Vector2 pointerPosition = Pointer.current.position.ReadValue();
  760. var mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
  761. Ray ray = mainCamera.ScreenPointToRay(pointerPosition);
  762. if (Physics.Raycast(ray, out RaycastHit hit))
  763. {
  764. //Debug.Log($"Clicked on: {hit.collider.gameObject.name}");
  765. // 射线检测起始点击是否在狗上
  766. if (hit.collider.gameObject == interactDog)
  767. {
  768. if (previousPointerPosition != pointerPosition)
  769. {
  770. interactTime += Time.deltaTime;
  771. Debug.Log("interactTime:" + interactTime);
  772. foreach (var dog in dogsInScene)
  773. {
  774. if (dog.gameObject == interactDog)
  775. {
  776. dog.interactLastUpdate = DateTime.Now;
  777. }
  778. }
  779. previousPointerPosition = pointerPosition;
  780. }
  781. }
  782. if (interactTime > 2.5) // 如果交互时间超过1秒,播放心形粒子效果
  783. {
  784. HeartParticlePlay();
  785. DogBarkController.Instance.PlayDogBarkWithDelay(1); // 狗叫相应一下
  786. }
  787. }
  788. }
  789. void HeartParticlePlay()
  790. {
  791. // 播放心形粒子效果
  792. var heartParticle = GameObject.Find("Particle Heart");
  793. heartParticle.GetComponent<ParticleSystem>().Play();
  794. interactTime = 0;
  795. }
  796. public void SetInteractDog(GameObject dog)
  797. {
  798. interactDog = dog;
  799. }
  800. #endregion
  801. #region 场景环境控制
  802. // 淡入或淡出背景音乐
  803. private void FadeBGM(AudioSource bgmSource, bool fadeIn, float duration = 2f)
  804. {
  805. // fadeIn: true表示淡入 false表示淡出
  806. if (bgmSource == null) return; // 如果没有 AudioSource,则直接返回
  807. StartCoroutine(FadeBGMCoroutine(bgmSource, fadeIn, duration));
  808. }
  809. private IEnumerator FadeBGMCoroutine(AudioSource bgmSource, bool fadeIn, float duration)
  810. {
  811. float elapsedTime = 0f;
  812. float startVolume = bgmSource.volume;
  813. float targetVolume = fadeIn ? 0.4f : 0f; // 淡入目标音量为1,淡出目标音量为0
  814. while (elapsedTime < duration)
  815. {
  816. bgmSource.volume = Mathf.Lerp(startVolume, targetVolume, elapsedTime / duration);
  817. elapsedTime += Time.deltaTime;
  818. yield return null;
  819. }
  820. bgmSource.volume = targetVolume; // 确保音量达到目标值
  821. if (!fadeIn)
  822. {
  823. bgmSource.Stop(); // 如果是淡出,停止播放
  824. }
  825. else
  826. {
  827. bgmSource.Play(); // 如果是淡入,开始播放
  828. }
  829. }
  830. // 设置场景模式
  831. public void SetSceneMode(SceneMode mode)
  832. {
  833. this.sceneMode = mode;
  834. }
  835. // 刷新dogInScene的狗数据
  836. public void RefreshDogInScene()
  837. {
  838. foreach (var dog in dogsInScene)
  839. {
  840. dog.ReloadDogProperty();
  841. }
  842. }
  843. #endregion
  844. }
  845. public enum ItemGroup
  846. {
  847. FOOD,
  848. WATER
  849. }
  850. public enum SceneMode
  851. {
  852. TRAINING,
  853. INACTIVE,
  854. NORMAL,
  855. }