HomeController.cs 40 KB

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