HomeController.cs 43 KB

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