HomeController.cs 40 KB

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