HomeController.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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. /* 本代码控制室内场景
  14. * 控制宠物在Home场景动画
  15. * !!!特别注意:Dog Initializer 必须挂载在同一个组件下,并且必须在本组价下方。确保比本组件先执行
  16. * 主要调节参数在FixedUpdate代码段里面
  17. * 提示用户注册
  18. */
  19. public class HomeController : MonoBehaviour
  20. {
  21. public static HomeController Instance;
  22. public static List<DogInScene> dogsInScene = new List<DogInScene>();
  23. public static bool listenBreak = false; // 当按下说话按键后,所有狗停止行动,立刻切换到监听状态。
  24. public static CinemachineVirtualCamera playerCam, dogCam;
  25. public static DateTime lastCameraChange;
  26. private bool isSleepChecked = false; // 用于检测第一次睡眠检测是否执行完成
  27. // Start is called once before the first execution of Update after the MonoBehaviour is created
  28. private GameObject centerOfDogs;
  29. private bool isInteractMode = false; // 场景是否在交互状态
  30. private Vector2 previousPointerPosition = Vector2.zero; // 前一帧鼠标位置
  31. private GameObject interactDog; // 交互的狗
  32. float interactTime = 0f; // 交互时间
  33. private bool isTrainingMode = false; // 是否在训练状态
  34. private string trainingContent = ""; // 训练内容
  35. private int totalTrainingTimes = 2; // 训练总次数
  36. private int currentTrainingTimes = 0; // 当前训练次数
  37. private string trainingDogId = ""; // 训练的狗id
  38. private bool isTrainingMsgShowed_1 = false; // 第一条是否已经显示训练提示
  39. private bool isTrainingMsgShowed_2 = 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 randomCheck = UnityEngine.Random.Range(0, 51);
  104. // 检测是否有狗没有通过voiceCall训练,如果有,立刻进入训练模式
  105. foreach (var dog in dogsInScene)
  106. {
  107. if (dog.dogProperty.voiceCall == 0)
  108. {
  109. isTrainingMode = true;
  110. trainingContent = "voiceCall";
  111. trainingDogId = dog.dogProperty.d_id;
  112. totalTrainingTimes = 2;
  113. currentTrainingTimes = 0;
  114. GameData.focusDog = dogsInScene.IndexOf(dog);
  115. //GameData.focusDog = UserProperty.GetDogIndexById(dog.dogProperty.d_id);
  116. dogsInScene[GameData.focusDog].SetupInteract();
  117. interactDog = dogsInScene[GameData.focusDog].gameObject;
  118. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  119. }
  120. }
  121. if (isTrainingMode)
  122. {
  123. foreach (var dog in dogsInScene)
  124. {
  125. if (dog.dogState == "interact")
  126. {
  127. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  128. dogCam.Priority = 10;
  129. // 单只狗在交互的状态控制代码
  130. if (dog.isMovingToPlayer)
  131. {
  132. dog.MovetoPlayer();
  133. }
  134. else
  135. {
  136. dog.dogState = "training";
  137. if (!isTrainingMsgShowed_1 && !isTrainingMsgShowed_2 && currentTrainingTimes == 0)
  138. {
  139. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", "record_dog_name", EnviromentSetting.languageCode });
  140. MessageBoxController.ShowMessage(msg);
  141. isTrainingMsgShowed_1 = true;
  142. }
  143. else if (!isTrainingMsgShowed_2 && isTrainingMsgShowed_1 && currentTrainingTimes == 1)
  144. {
  145. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", "record_again", EnviromentSetting.languageCode });
  146. MessageBoxController.ShowMessage(msg);
  147. isTrainingMsgShowed_2 = true;
  148. }
  149. }
  150. }
  151. }
  152. }
  153. else
  154. if (isInteractMode)
  155. {
  156. foreach (var dog in dogsInScene)
  157. {
  158. if (dog.dogState == "interact")
  159. {
  160. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  161. dogCam.Priority = 10;
  162. // 单只狗在交互的状态控制代码
  163. if (dog.isMovingToPlayer)
  164. {
  165. dog.MovetoPlayer();
  166. }
  167. else if (dog.InteractTimeout()) // 如果交互时间结束,结束交互状态
  168. {
  169. dog.ExitInteract();
  170. isInteractMode = false; // 交互结束,退出交互状态
  171. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  172. }
  173. else
  174. {
  175. PointerOnDog(); // 检测是否点击在狗上
  176. }
  177. }
  178. }
  179. }
  180. else
  181. {
  182. // 场景非交互模式下的控制代码
  183. foreach (var dog in dogsInScene)
  184. {
  185. // 如果在eat drink进程结束前不执行随机场景代码
  186. //if (dog.itemConsumeProgress) // TODO 以后用DogInScene.dogState来判断
  187. if (dog.dogState == "itemConsume")
  188. {
  189. if (dog.isMovingToBowl)
  190. {
  191. dog.MovetoBowl();
  192. }
  193. }
  194. else
  195. {
  196. // 随机动作控制控制
  197. RandomCameraChange();
  198. if (listenBreak) // 如果用户按下说话按键,立刻切换到监听状态
  199. {
  200. dog.Listen();
  201. }
  202. else if (dog.isMoving)
  203. {
  204. dog.RandomMove();
  205. }
  206. else if (randomCheck == dog.randomFactor && !dog.isSleeping) // 当狗自身的随机数和系统随机数相同时候触发。约100秒触发一次。
  207. {
  208. TimeSpan ts = DateTime.Now - dog.animationStartTime;
  209. if (ts.Seconds >= 30) // 如果距离上一个动作超过30秒就可以开始新的动作
  210. {
  211. float r = UnityEngine.Random.Range(0, 1f);
  212. if (r > 0.6) // 随机选择开始动画,或者移动
  213. {
  214. dog.IdleAnimation();
  215. }
  216. else // 狗狗开始步行移动
  217. {
  218. dog.SetMoveSpeed(0);
  219. dog.moveSpeed = 0;
  220. dog.RandomMove();
  221. }
  222. }
  223. }
  224. }
  225. }
  226. }
  227. #endregion
  228. }
  229. }
  230. private void OnDestroy()
  231. {
  232. Debug.Log("Home scene is destoried.");
  233. }
  234. //void AniOrWalk(DogInScene dog) // 狗在普通状态下,随机或播放动画,或移动
  235. //{
  236. //}
  237. // 初始化场景,加载所有的狗,并配置components,添加到dogsInScene List里面去
  238. //void InitialScene()
  239. IEnumerator InitialScene()
  240. {
  241. //yield return null;
  242. //yield return null;
  243. yield return null; // 跳过三帧,初始化最多三只狗
  244. //Debug.Log(isInitialDone);
  245. foreach (var dog in UserProperty.dogs)
  246. {
  247. DogInScene dogInScene = new DogInScene(dog);
  248. float x = UnityEngine.Random.Range(-1f, 1f); // 随机生成位置,考虑到手机评估宽度限制宽度
  249. float z = UnityEngine.Random.Range(-5f, 5f);
  250. float y = UnityEngine.Random.Range(0, 360f);
  251. var initPosition = new Vector3(x, 0, z);
  252. StartCoroutine(DogComponentInstaller(dog)); // 加载狗的其他组件
  253. var dogGameObject = GameObject.Find(dog.dog_name);
  254. if (dogGameObject == null)
  255. {
  256. Debug.Log(dog.dog_name + "is not found in Home Controller");
  257. }
  258. dogGameObject.transform.position = initPosition;
  259. dogGameObject.transform.rotation = Quaternion.Euler(0, y, 0);
  260. dogGameObject.transform.localScale = new Vector3(2, 2, 2);
  261. dogInScene.SetGameObject(dogGameObject);
  262. dogsInScene.Add(dogInScene);
  263. }
  264. }
  265. // 加载狗的其他组件
  266. IEnumerator DogComponentInstaller(DogProperty dogProperty)
  267. {
  268. // 等待一帧,确保所有 Start() 方法都执行完成
  269. yield return null;
  270. // 第一帧以后开始执行
  271. GameObject dog = GameObject.Find(dogProperty.dog_name);
  272. // 加载指定的Animator controller
  273. Animator animator = dog.GetComponent<Animator>();
  274. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController");
  275. if (dogProperty.breed == "shibaInu") { animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController"); }
  276. animator.runtimeAnimatorController = animatorController;
  277. // 加载Rigidbody
  278. Rigidbody rigidbody = dog.AddComponent<Rigidbody>();
  279. //Rigidbody rigidbody = dog.GetComponent<Rigidbody>();
  280. //rigidbody.isKinematic = true;
  281. rigidbody.mass = 10;
  282. rigidbody.linearDamping = 10;
  283. rigidbody.angularDamping = 10;
  284. //rigidbody.freezeRotation = true;
  285. rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;
  286. rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
  287. rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
  288. // 加载box collider
  289. BoxCollider boxCollider = dog.AddComponent<BoxCollider>();
  290. boxCollider.isTrigger = false;
  291. boxCollider.center = new Vector3(0, 0.25f, 0);
  292. boxCollider.size = new Vector3(0.12f, 0.45f, 0.54f);
  293. // 加载Particle Question Mark
  294. ParticleSystem questionMarkParticle = Resources.Load<ParticleSystem>("Home/Particle_QuestionMark");
  295. questionMarkParticle = Instantiate(questionMarkParticle);
  296. questionMarkParticle.name = "QuestionMarkParticle";
  297. questionMarkParticle.transform.SetParent(dog.transform);
  298. questionMarkParticle.transform.localPosition = new Vector3(0, 0.4f, 0.4f);
  299. questionMarkParticle.transform.localRotation = Quaternion.Euler(-90, 0, 0);
  300. ParticleSystem ps = questionMarkParticle.GetComponent<ParticleSystem>();
  301. ps.Stop();
  302. // 加载sleep particle
  303. ParticleSystem zzzParticle = Resources.Load<ParticleSystem>("Home/Particle_Z");
  304. zzzParticle = Instantiate(zzzParticle);
  305. zzzParticle.name = "zzzParticle";
  306. zzzParticle.transform.SetParent(dog.gameObject.transform);
  307. zzzParticle.transform.localPosition = new Vector3(0.05f, 0.2f, 0.2f);
  308. zzzParticle.transform.localRotation = Quaternion.Euler(-90, 0, 0);
  309. zzzParticle.gameObject.SetActive(false); // 默认关闭
  310. //yield return null;
  311. }
  312. // 场景随机切换镜头看向不同的狗
  313. void RandomCameraChange()
  314. {
  315. int delay = 10; // 延迟10秒执行一次
  316. TimeSpan ts = DateTime.Now - lastCameraChange;
  317. if (ts.TotalSeconds < delay) { return; }
  318. int dogCount = dogsInScene.Count;
  319. int r = UnityEngine.Random.Range(0, dogCount + 1);
  320. if (r < dogCount)
  321. {
  322. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  323. dogCam.Priority = 10;
  324. playerCam.Priority = 1;
  325. }
  326. else
  327. {
  328. dogCam.Priority = 1;
  329. playerCam.Priority = 10;
  330. }
  331. lastCameraChange = DateTime.Now;
  332. }
  333. // 检测场景是否初始化完成
  334. bool SceneInitialCheck()
  335. {
  336. bool initDone = true;
  337. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  338. {
  339. foreach (var dog in dogsInScene)
  340. {
  341. if (dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  342. {
  343. initDone = false;
  344. }
  345. }
  346. }
  347. else
  348. {
  349. initDone = false;
  350. }
  351. //Debug.Log("Home scene initial status:"+initDone);
  352. return initDone;
  353. }
  354. // 计算多只狗的中心位置,用于主摄像机瞄准
  355. private Vector3 CenterOfDogs()
  356. {
  357. Vector3 center = Vector3.zero;
  358. foreach (var dog in dogsInScene)
  359. {
  360. center += dog.gameObject.transform.position;
  361. }
  362. center /= dogsInScene.Count;
  363. return center;
  364. }
  365. #region 语音控制区
  366. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  367. public void VoiceCallRequest(string filePath)
  368. {
  369. Debug.Log("Voice Call Post request");
  370. string url = "/api/voice/call/";
  371. WWWForm form = new();
  372. form.AddField("user_id", UserProperty.userId);
  373. // TODO 待后台开发完成后,开启网络通讯功能,目前暂用临时直接赋值
  374. // StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCallCallback));
  375. isInteractMode = true; // 场景进入交互模式
  376. dogsInScene[0].SetupInteract();
  377. interactDog = dogsInScene[0].gameObject;
  378. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  379. }
  380. // 语音呼唤上传回调函数
  381. void VoiceCallCallback(string json)
  382. {
  383. Debug.Log("Voice call callback");
  384. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  385. if (data != null && data["status"].ToString() == "success")
  386. {
  387. // 刷新狗的数据
  388. string dogJson = data["dogs"].ToString();
  389. UserProperty.FreshDogInfo(dogJson);
  390. // TODO 根据返回结果设定focusdog
  391. float highestScore = 0;
  392. string highestScoreDogId = "";
  393. var scores = data["call Score MFCC"].ToString();
  394. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  395. foreach (var score in scoresList)
  396. {
  397. if (score.Value > highestScore)
  398. {
  399. highestScore = score.Value;
  400. highestScoreDogId = score.Key;
  401. }
  402. }
  403. if (highestScore >= 60) // 60分以上才可以进入交互模式
  404. {
  405. GameData.focusDog = UserProperty.GetDogIndexById(highestScoreDogId);
  406. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  407. foreach (var dog in dogsInScene)
  408. {
  409. if (dog.dogProperty.d_id == highestScoreDogId)
  410. {
  411. if (GameTool.Random100Check(dog.dogProperty.voiceCall))
  412. {
  413. dog.SetupInteract();
  414. interactDog = dog.gameObject;
  415. // focusdog 开启互动模式
  416. HomeController.dogsInScene[GameData.focusDog].dogState = "interact";
  417. HomeController.dogsInScene[GameData.focusDog].SetupInteract();
  418. }
  419. }
  420. }
  421. }
  422. else
  423. {
  424. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  425. }
  426. }
  427. else
  428. {
  429. Debug.Log(data["message"]);
  430. }
  431. }
  432. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  433. public void VoiceCommandRequest(string filePath)
  434. {
  435. if (isInteractMode)
  436. {
  437. Debug.Log("Voice Command Post request");
  438. string url = "/api/voice/command/";
  439. WWWForm form = new();
  440. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  441. form.AddField("user_id", UserProperty.userId);
  442. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  443. }
  444. else if (isTrainingMode)
  445. {
  446. Debug.Log("Voice training Post request");
  447. currentTrainingTimes++;
  448. string url = "/api/voice/training/";
  449. WWWForm form = new();
  450. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  451. form.AddField("user_id", UserProperty.userId);
  452. form.AddField("voice_type", trainingContent);
  453. form.AddField("current_times", currentTrainingTimes);
  454. form.AddField("total_times", totalTrainingTimes);
  455. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  456. }
  457. }
  458. // 语音呼唤上传回调函数
  459. void VoiceCommandCallback(string json)
  460. {
  461. if (isInteractMode)
  462. {
  463. Debug.Log("Voice command callback");
  464. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  465. if (data != null && data["status"].ToString() == "success")
  466. {
  467. // 刷新狗的数据
  468. string dogJson = data["dogs"].ToString();
  469. UserProperty.FreshDogInfo(dogJson);
  470. // 找到得分最高的指令
  471. float highestScore = 0;
  472. string highestScoreCommand = "";
  473. string scores = data["commandScoreMFCC"].ToString();
  474. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  475. foreach (var score in scoresList)
  476. {
  477. if (score.Value > highestScore)
  478. {
  479. highestScore = score.Value;
  480. highestScoreCommand = score.Key;
  481. }
  482. }
  483. if (highestScore >= 60)
  484. {
  485. if (GameTool.Random100Check(dogsInScene[GameData.focusDog].dogProperty.voiceCommand))
  486. {
  487. string animationTrigger = highestScoreCommand.Substring(5);
  488. string animationBool = "is" + highestScoreCommand + "ing";
  489. var animator = dogsInScene[GameData.focusDog].gameObject.GetComponent<Animator>();
  490. animator.SetTrigger(animationTrigger);
  491. if (animationBool != "isSiting" || animationBool != "isLieing" || animationBool != "isDieing")
  492. {
  493. animator.SetBool(animationBool, true);
  494. dogsInScene[GameData.focusDog].interactAnimation = animationBool;
  495. dogsInScene[GameData.focusDog].interactAnimationStartTime = DateTime.Now;
  496. }
  497. }
  498. }
  499. else
  500. {
  501. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  502. }
  503. }
  504. else
  505. {
  506. Debug.Log(data["message"]);
  507. }
  508. }
  509. else if (isTrainingMode)
  510. {
  511. Debug.Log("Voice training Callback");
  512. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  513. if (data != null && data["status"].ToString() == "success")
  514. {
  515. if (data["message"].ToString() == "pass")
  516. {
  517. // 刷新狗的数据
  518. string dogJson = data["dogs"].ToString();
  519. UserProperty.FreshDogInfo(dogJson);
  520. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", "record_success", EnviromentSetting.languageCode });
  521. MessageBoxController.ShowMessage(msg);
  522. ResetTrainingModeParameters();
  523. isTrainingMode = false;
  524. foreach (var dog in dogsInScene)
  525. {
  526. if (dog.dogProperty.d_id == trainingDogId)
  527. {
  528. dog.ExitInteract();
  529. }
  530. }
  531. }
  532. else if (data["message"].ToString() == "fail")
  533. {
  534. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  535. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", "record_fail", EnviromentSetting.languageCode });
  536. MessageBoxController.ShowMessage(msg);
  537. }
  538. }
  539. else
  540. {
  541. Debug.Log(data["message"]);
  542. }
  543. }
  544. }
  545. #endregion
  546. #region interact mode
  547. // 重置training相关参数
  548. public void ResetTrainingModeParameters()
  549. {
  550. //isTrainingMode = false;
  551. trainingContent = "";
  552. totalTrainingTimes = 2;
  553. currentTrainingTimes = 0;
  554. trainingDogId = "";
  555. isTrainingMsgShowed_1 = false;
  556. isTrainingMsgShowed_2 = false;
  557. }
  558. // 改变Voice And Menu 菜单形态
  559. public void VoiceButtonOnlySwitch(bool state)
  560. {
  561. // 交互时候关闭其他菜单
  562. var vamUI = GameObject.Find("VoiceAndMenu");
  563. if (vamUI != null)
  564. {
  565. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  566. var voiceController = UIdocument.GetComponent<VoiceController>();
  567. voiceController.isCommandMode = state;
  568. }
  569. }
  570. // 检测是否点击在狗上
  571. void PointerOnDog()
  572. {
  573. //DetectTouchMethod();
  574. // 检查当前指针是否有效
  575. if (Pointer.current == null) return;
  576. // 获取当前指针的悬浮位置
  577. Vector2 pointerPosition = Pointer.current.position.ReadValue();
  578. var mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
  579. Ray ray = mainCamera.ScreenPointToRay(pointerPosition);
  580. if (Physics.Raycast(ray, out RaycastHit hit))
  581. {
  582. //Debug.Log($"Clicked on: {hit.collider.gameObject.name}");
  583. // 射线检测起始点击是否在狗上
  584. if (hit.collider.gameObject == interactDog)
  585. {
  586. if (previousPointerPosition != pointerPosition)
  587. {
  588. interactTime += Time.deltaTime;
  589. Debug.Log("interactTime:" + interactTime);
  590. foreach (var dog in dogsInScene)
  591. {
  592. if (dog.gameObject == interactDog)
  593. {
  594. dog.interactLastUpdate = DateTime.Now;
  595. }
  596. }
  597. previousPointerPosition = pointerPosition;
  598. }
  599. }
  600. if (interactTime > 3) // 如果交互时间超过1秒,播放心形粒子效果
  601. {
  602. HeartParticlePlay();
  603. var animation = interactDog.GetComponent<Animator>();
  604. animation.SetTrigger("Hug");
  605. }
  606. }
  607. }
  608. void HeartParticlePlay()
  609. {
  610. // 播放心形粒子效果
  611. var heartParticle = GameObject.Find("Particle Heart");
  612. heartParticle.GetComponent<ParticleSystem>().Play();
  613. interactTime = 0;
  614. }
  615. #endregion
  616. }
  617. public enum ItemGroup
  618. {
  619. food,
  620. water
  621. }