HomeController.cs 28 KB

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