HomeController.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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. StartCoroutine(dog.RotationToPlayer());
  303. }
  304. else if (dog.isMoving)
  305. {
  306. dog.RandomMove();
  307. }
  308. else if (sceneRandomFactor == dog.randomFactor && !dog.isSleeping) // 当狗自身的随机数和系统随机数相同时候触发。约100秒触发一次。
  309. {
  310. TimeSpan ts = DateTime.Now - dog.animationStartTime;
  311. if (ts.Seconds >= 30) // 如果距离上一个动作超过30秒就可以开始新的动作
  312. {
  313. float r = UnityEngine.Random.Range(0, 1f);
  314. if (r > 0.6) // 随机选择开始动画,或者移动
  315. {
  316. dog.IdleAnimation();
  317. }
  318. else // 狗狗开始步行移动
  319. {
  320. dog.SetMoveSpeed(0);
  321. dog.moveSpeed = 0;
  322. dog.RandomMove();
  323. }
  324. }
  325. }
  326. }
  327. }
  328. }
  329. #endregion
  330. }
  331. }
  332. private void OnDestroy()
  333. {
  334. Debug.Log("Home scene is destoried.");
  335. }
  336. IEnumerator InitialScene()
  337. {
  338. yield return null; // 跳过三帧,初始化最多三只狗
  339. //Debug.Log(isInitialDone);
  340. foreach (var dog in UserProperty.dogs)
  341. {
  342. DogInScene dogInScene = new DogInScene(dog);
  343. float x = UnityEngine.Random.Range(-1f, 1f); // 随机生成位置,考虑到手机评估宽度限制宽度
  344. float z = UnityEngine.Random.Range(-5f, 5f);
  345. float y = UnityEngine.Random.Range(0, 360f);
  346. var initPosition = new Vector3(x, 0, z);
  347. StartCoroutine(DogComponentInstaller(dog)); // 加载狗的其他组件
  348. var dogGameObject = GameObject.Find(dog.dog_name);
  349. if (dogGameObject == null)
  350. {
  351. Debug.Log(dog.dog_name + "is not found in Home Controller");
  352. }
  353. dogGameObject.transform.position = initPosition;
  354. dogGameObject.transform.rotation = Quaternion.Euler(0, y, 0);
  355. dogGameObject.transform.localScale = new Vector3(2, 2, 2);
  356. dogInScene.SetGameObject(dogGameObject);
  357. dogsInScene.Add(dogInScene);
  358. }
  359. }
  360. // 加载狗的其他组件
  361. IEnumerator DogComponentInstaller(DogProperty dogProperty)
  362. {
  363. // 等待一帧,确保所有 Start() 方法都执行完成
  364. yield return null;
  365. // 第一帧以后开始执行
  366. GameObject dog = GameObject.Find(dogProperty.dog_name);
  367. // 加载指定的Animator controller
  368. Animator animator = dog.GetComponent<Animator>();
  369. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController");
  370. if (dogProperty.breed == "shibaInu") { animatorController = Resources.Load<RuntimeAnimatorController>("Dog/AnimatorController/shibaInu/HomeDogAnimatorController"); }
  371. animator.runtimeAnimatorController = animatorController;
  372. // 加载Rigidbody
  373. Rigidbody rigidbody = dog.AddComponent<Rigidbody>();
  374. //Rigidbody rigidbody = dog.GetComponent<Rigidbody>();
  375. //rigidbody.isKinematic = true;
  376. rigidbody.mass = 10;
  377. rigidbody.linearDamping = 10;
  378. rigidbody.angularDamping = 10;
  379. //rigidbody.freezeRotation = true;
  380. rigidbody.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotation;
  381. rigidbody.interpolation = RigidbodyInterpolation.Interpolate;
  382. rigidbody.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative;
  383. // 加载box collider
  384. BoxCollider boxCollider = dog.AddComponent<BoxCollider>();
  385. boxCollider.isTrigger = false;
  386. boxCollider.center = new Vector3(0, 0.25f, 0);
  387. boxCollider.size = new Vector3(0.12f, 0.45f, 0.54f);
  388. // 加载Particle Question Mark
  389. ParticleSystem questionMarkParticle = Resources.Load<ParticleSystem>("Home/Particle_QuestionMark");
  390. questionMarkParticle = Instantiate(questionMarkParticle);
  391. questionMarkParticle.name = "QuestionMarkParticle";
  392. questionMarkParticle.transform.SetParent(dog.transform);
  393. questionMarkParticle.transform.localPosition = new Vector3(0, 0.4f, 0.4f);
  394. questionMarkParticle.transform.localRotation = Quaternion.Euler(-90, 0, 0);
  395. ParticleSystem ps = questionMarkParticle.GetComponent<ParticleSystem>();
  396. ps.Stop();
  397. // 加载sleep particle
  398. ParticleSystem zzzParticle = Resources.Load<ParticleSystem>("Home/Particle_Z");
  399. zzzParticle = Instantiate(zzzParticle);
  400. zzzParticle.name = "zzzParticle";
  401. zzzParticle.transform.SetParent(dog.gameObject.transform);
  402. zzzParticle.transform.localPosition = new Vector3(0.05f, 0.2f, 0.2f);
  403. zzzParticle.transform.localRotation = Quaternion.Euler(-90, 0, 0);
  404. zzzParticle.gameObject.SetActive(false); // 默认关闭
  405. //yield return null;
  406. }
  407. // 场景随机切换镜头看向不同的狗
  408. void RandomCameraChange()
  409. {
  410. int delay = 10; // 延迟10秒执行一次
  411. TimeSpan ts = DateTime.Now - lastCameraChange;
  412. if (ts.TotalSeconds < delay) { return; }
  413. int dogCount = dogsInScene.Count;
  414. int r = UnityEngine.Random.Range(0, dogCount + 1);
  415. if (r < dogCount)
  416. {
  417. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  418. dogCam.Priority = 10;
  419. playerCam.Priority = 1;
  420. }
  421. else
  422. {
  423. dogCam.Priority = 1;
  424. playerCam.Priority = 10;
  425. }
  426. lastCameraChange = DateTime.Now;
  427. }
  428. // 检测场景是否初始化完成
  429. bool SceneInitialCheck()
  430. {
  431. bool initDone = true;
  432. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  433. {
  434. foreach (var dog in dogsInScene)
  435. {
  436. if (dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  437. {
  438. initDone = false;
  439. }
  440. }
  441. }
  442. else
  443. {
  444. initDone = false;
  445. }
  446. //Debug.Log("Home scene initial status:"+initDone);
  447. return initDone;
  448. }
  449. // 计算多只狗的中心位置,用于主摄像机瞄准
  450. private Vector3 CenterOfDogs()
  451. {
  452. if (dogsInScene.Count == 0)
  453. {
  454. return Vector3.zero;
  455. }
  456. Vector3 center = Vector3.zero;
  457. foreach (var dog in dogsInScene)
  458. {
  459. center += dog.gameObject.transform.position;
  460. }
  461. center /= dogsInScene.Count;
  462. return center;
  463. }
  464. #region 语音控制区
  465. // 用户语音呼唤上传,Voice call指令用于呼唤所有的狗,得分最高的过来进入交互模式
  466. public void VoiceCallRequest(string filePath)
  467. {
  468. Debug.Log("Voice Call Post request");
  469. string url = "/api/voice/call/";
  470. WWWForm form = new();
  471. form.AddField("user_id", UserProperty.userId);
  472. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCallCallback));
  473. }
  474. // 语音呼唤上传回调函数
  475. void VoiceCallCallback(string json)
  476. {
  477. Debug.Log("Voice call callback");
  478. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  479. if (data != null && data["status"].ToString() == "success")
  480. {
  481. // 刷新狗的数据
  482. string dogJson = data["dogs"].ToString();
  483. UserProperty.FreshDogInfo(dogJson);
  484. // TODO 根据返回结果设定focusdog
  485. float highestScore = 0;
  486. string highestScoreDogId = String.Empty;
  487. var scores = data["call Score MFCC"].ToString();
  488. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  489. foreach (var score in scoresList)
  490. {
  491. // 根据狗的数量度修正得分。计算方式为狗的voiceCall属性值/1000
  492. int dogIndex = UserProperty.GetDogIndexById(score.Key);
  493. if (dogIndex < 0)
  494. {
  495. continue;
  496. }
  497. float scoreFactor = UserProperty.dogs[dogIndex].voiceCall / 1000f;
  498. float adjScore = score.Value + scoreFactor;
  499. if (adjScore > 1)
  500. {
  501. adjScore = 1;
  502. }
  503. if (adjScore > highestScore)
  504. {
  505. highestScore = adjScore;
  506. highestScoreDogId = score.Key;
  507. }
  508. }
  509. if (highestScore >= EnviromentSetting.voiceRecognitionScore) // 60分以上才可以进入交互模式
  510. {
  511. GameData.focusDog = UserProperty.GetDogIndexById(highestScoreDogId);
  512. sceneMode = SceneMode.INACTIVE; // 交互模式
  513. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  514. foreach (var dog in dogsInScene)
  515. {
  516. if (dog.dogProperty.d_id == highestScoreDogId)
  517. {
  518. // if (GameTool.Random100Check(dog.dogProperty.voiceCall))
  519. // {
  520. // dog.SetupInteract();
  521. interactDog = dog.gameObject;
  522. // focusdog 开启互动模式
  523. // HomeController.dogsInScene[GameData.focusDog].dogState = DogState.INTERACT;
  524. HomeController.dogsInScene[GameData.focusDog].SetupInteract();
  525. // 其他狗进入隐藏模式(先保留代码)
  526. //foreach (var otherDog in dogsInScene)
  527. //{
  528. // if (otherDog.dogProperty.d_id != highestScoreDogId)
  529. // {
  530. // otherDog.gameObject.SetActive(false);
  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. // 根据狗的voiceCommand属性值修正得分。计算方式为狗的voiceCommand属性值/1000
  601. highestScore += UserProperty.dogs[GameData.focusDog].voiceCommand / 1000f;
  602. if (highestScore > 1)
  603. {
  604. highestScore = 1;
  605. }
  606. Debug.Log("Highest score:" + highestScore.ToString());
  607. Debug.Log("Highest command:" + highestScoreCommand);
  608. dogsInScene[GameData.focusDog].ResetAnimationStatus(); // 重置狗的动画状态
  609. if (highestScore >= EnviromentSetting.voiceRecognitionScore)
  610. {
  611. string animationTrigger = highestScoreCommand.Substring(7);
  612. string animationBool = animationTrigger + "_status";
  613. var animator = dogsInScene[GameData.focusDog].gameObject.GetComponent<Animator>();
  614. if (highestScoreCommand == "commandBark")
  615. {
  616. DogBarkController.Instance.PlayDogBarkWithDelay(3); // 狗叫相应一下
  617. }
  618. else
  619. {
  620. HomeSoundEffectController.Instance.PlaySoundEffect(5);
  621. }
  622. animator.SetTrigger(animationTrigger);
  623. animator.SetBool(animationBool, true);
  624. // 交互动画执行一段时间后停止
  625. StartCoroutine(dogsInScene[GameData.focusDog].InteractAnimationCountDown());
  626. }
  627. else
  628. {
  629. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  630. }
  631. }
  632. else
  633. {
  634. Debug.Log(data["message"]);
  635. }
  636. }
  637. else if (sceneMode == SceneMode.TRAINING)
  638. {
  639. Debug.Log("Voice training Callback");
  640. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  641. if (data != null && data["status"].ToString().ToLower() == "success")
  642. {
  643. if (data["message"].ToString().ToLower() == "pass")
  644. {
  645. // 刷新狗的数据,包含dogsInScene
  646. string dogJson = data["dogs"].ToString();
  647. UserProperty.FreshDogInfo(dogJson);
  648. var trainingDog = dogsInScene[GameData.focusDog];
  649. trainingDog.ReloadDogProperty(); // 刷新狗的数据
  650. // 成功后让狗子播放训练的动画
  651. if (trainingContent != "voiceCall")
  652. {
  653. string command = trainingContent.Substring(7);
  654. trainingDog.animator.SetTrigger(command);
  655. trainingDog.animator.SetBool("is" + command + "ing", true);
  656. }
  657. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_10", EnviromentSetting.languageCode });
  658. if (msg.Contains("<<dog_name>>"))
  659. {
  660. msg = msg.Replace("<<dog_name>>", interactDog.name);
  661. }
  662. GameTool.PauseGameTime();
  663. MessageBoxController.ShowMessage(msg, ExitTrainingMode);
  664. this.sceneMode = SceneMode.NORMAL;
  665. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  666. GameData.isVoiceTrainingToday = true; // 训练完成,设置为true
  667. string todayDate = System.DateTime.Now.ToString("yyyy-MM-dd");
  668. PlayerPrefs.SetString("lastTrainingDate", todayDate);
  669. PlayerPrefs.Save();
  670. }
  671. else if (data["message"].ToString() == "fail")
  672. {
  673. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  674. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  675. if (msg.Contains("<<dog_name>>"))
  676. {
  677. msg = msg.Replace("<<dog_name>>", interactDog.name);
  678. }
  679. GameTool.PauseGameTime();
  680. MessageBoxController.ShowMessage(msg, RestartTraining);
  681. }
  682. }
  683. else
  684. {
  685. Debug.Log(data["message"]);
  686. if (EnviromentSetting.runEnv == "Release")
  687. {
  688. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  689. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  690. if (msg.Contains("<<dog_name>>"))
  691. {
  692. msg = msg.Replace("<<dog_name>>", interactDog.name);
  693. }
  694. GameTool.PauseGameTime();
  695. MessageBoxController.ShowMessage(msg, RestartTraining);
  696. }
  697. }
  698. }
  699. }
  700. #endregion
  701. #region interact mode
  702. // 重置training相关参数
  703. private void ExitTrainingMode()
  704. {
  705. foreach (var dog in dogsInScene)
  706. {
  707. if (dog.dogProperty.d_id == trainingDogId)
  708. {
  709. dog.ExitInteract();
  710. }
  711. }
  712. trainingContent = String.Empty;
  713. totalTrainingTimes = 2;
  714. currentTrainingTimes = 0;
  715. trainingDogId = "";
  716. isTrainingMsgShowed_1 = false;
  717. isTrainingMsgShowed_2 = false;
  718. isTrainingAnimationPlayed = false;
  719. sceneMode = SceneMode.NORMAL; // 交互模式
  720. Debug.Log("Reset Training Mode Parameters");
  721. GameTool.ResumeGameTime();
  722. GameData.isVoiceTrainingToday = true; // 训练完成,设置为true
  723. var BGM = GameObject.Find("BGM");
  724. if (BGM != null)
  725. {
  726. FadeBGM(BGM.GetComponent<AudioSource>(), true);
  727. }
  728. }
  729. private void RestartTraining()
  730. {
  731. currentTrainingTimes = 0;
  732. isTrainingMsgShowed_1 = false;
  733. isTrainingMsgShowed_2 = false;
  734. Time.timeScale = 1f;
  735. }
  736. // 改变Voice And Menu 菜单形态
  737. public void VoiceButtonOnlySwitch(bool state)
  738. {
  739. // 交互时候关闭其他菜单
  740. var vamUI = GameObject.Find("VoiceAndMenu");
  741. if (vamUI != null)
  742. {
  743. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  744. var voiceController = UIdocument.GetComponent<VoiceController>();
  745. voiceController.isCommandMode = state;
  746. }
  747. }
  748. // 检测是否点击在狗上
  749. void PointerOnDog()
  750. {
  751. //DetectTouchMethod();
  752. // 检查当前指针是否有效
  753. if (Pointer.current == null) return;
  754. // 获取当前指针的悬浮位置
  755. Vector2 pointerPosition = Pointer.current.position.ReadValue();
  756. var mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
  757. Ray ray = mainCamera.ScreenPointToRay(pointerPosition);
  758. if (Physics.Raycast(ray, out RaycastHit hit))
  759. {
  760. //Debug.Log($"Clicked on: {hit.collider.gameObject.name}");
  761. // 射线检测起始点击是否在狗上
  762. if (hit.collider.gameObject == interactDog)
  763. {
  764. if (previousPointerPosition != pointerPosition)
  765. {
  766. interactTime += Time.deltaTime;
  767. Debug.Log("interactTime:" + interactTime);
  768. foreach (var dog in dogsInScene)
  769. {
  770. if (dog.gameObject == interactDog)
  771. {
  772. dog.interactLastUpdate = DateTime.Now;
  773. }
  774. }
  775. previousPointerPosition = pointerPosition;
  776. }
  777. }
  778. if (interactTime > 2.5) // 如果交互时间超过1秒,播放心形粒子效果
  779. {
  780. HeartParticlePlay();
  781. DogBarkController.Instance.PlayDogBarkWithDelay(1); // 狗叫相应一下
  782. }
  783. }
  784. }
  785. void HeartParticlePlay()
  786. {
  787. // 播放心形粒子效果
  788. var heartParticle = GameObject.Find("Particle Heart");
  789. heartParticle.GetComponent<ParticleSystem>().Play();
  790. interactTime = 0;
  791. }
  792. public void SetInteractDog(GameObject dog)
  793. {
  794. interactDog = dog;
  795. }
  796. #endregion
  797. #region 场景环境控制
  798. // 淡入或淡出背景音乐
  799. private void FadeBGM(AudioSource bgmSource, bool fadeIn, float duration = 2f)
  800. {
  801. // fadeIn: true表示淡入 false表示淡出
  802. if (bgmSource == null) return; // 如果没有 AudioSource,则直接返回
  803. StartCoroutine(FadeBGMCoroutine(bgmSource, fadeIn, duration));
  804. }
  805. private IEnumerator FadeBGMCoroutine(AudioSource bgmSource, bool fadeIn, float duration)
  806. {
  807. float elapsedTime = 0f;
  808. float startVolume = bgmSource.volume;
  809. float targetVolume = fadeIn ? 0.4f : 0f; // 淡入目标音量为1,淡出目标音量为0
  810. while (elapsedTime < duration)
  811. {
  812. bgmSource.volume = Mathf.Lerp(startVolume, targetVolume, elapsedTime / duration);
  813. elapsedTime += Time.deltaTime;
  814. yield return null;
  815. }
  816. bgmSource.volume = targetVolume; // 确保音量达到目标值
  817. if (!fadeIn)
  818. {
  819. bgmSource.Stop(); // 如果是淡出,停止播放
  820. }
  821. else
  822. {
  823. bgmSource.Play(); // 如果是淡入,开始播放
  824. }
  825. }
  826. // 设置场景模式
  827. public void SetSceneMode(SceneMode mode)
  828. {
  829. this.sceneMode = mode;
  830. }
  831. // 刷新dogInScene的狗数据
  832. public void RefreshDogInScene()
  833. {
  834. foreach (var dog in dogsInScene)
  835. {
  836. dog.ReloadDogProperty();
  837. }
  838. }
  839. #endregion
  840. }
  841. public enum ItemGroup
  842. {
  843. FOOD,
  844. WATER
  845. }
  846. public enum SceneMode
  847. {
  848. TRAINING,
  849. INACTIVE,
  850. NORMAL,
  851. }