HomeController.cs 38 KB

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