HomeController.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. using Cinemachine;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using UnityEngine;
  7. using UnityEngine.InputSystem;
  8. /* 本代码控制室内场景
  9. * 控制宠物在Home场景动画
  10. * !!!特别注意:Dog Initializer 必须挂载在同一个组件下,并且必须在本组价下方。确保比本组件先执行
  11. * 主要调节参数在FixedUpdate代码段里面
  12. * 提示用户注册
  13. * SetDogsIsTrigger 正常模式下为true。交互模式和进食模式下为false。
  14. */
  15. public class HomeController : MonoBehaviour
  16. {
  17. public static HomeController Instance;
  18. public static List<DogInScene> dogsInScene = new List<DogInScene>();
  19. public static bool listenBreak = false; // 当按下说话按键后,所有狗停止行动,立刻切换到监听状态。
  20. public static CinemachineVirtualCamera playerCam, dogCam;
  21. public static DateTime lastCameraChange;
  22. private bool isSleepChecked = false; // 用于检测第一次睡眠检测是否执行完成
  23. // Start is called once before the first execution of Update after the MonoBehaviour is created
  24. private GameObject centerOfDogs;
  25. private SceneMode sceneMode = SceneMode.NORMAL; // 当前场景处在的模式
  26. //private bool isInteractMode = false; // 场景是否在交互状态
  27. private Vector2 previousPointerPosition = Vector2.zero; // 前一帧鼠标位置
  28. private GameObject interactDog; // 交互的狗
  29. float interactTime = 0f; // 交互时间
  30. //private bool isTrainingMode = false; // 是否在训练状态
  31. private string trainingContent = String.Empty; // 训练内容 _xx 对于language.json 0x开始提示 1x成功提示 2x失败提示
  32. private int totalTrainingTimes = 2; // 训练总次数
  33. private int currentTrainingTimes = 0; // 当前训练次数
  34. private string trainingDogId = ""; // 训练的狗id
  35. private bool isTrainingMsgShowed_1 = false; // 第一条是否已经显示训练提示
  36. private bool isTrainingMsgShowed_2 = false; // 第二条是否已经显示训练提示
  37. private bool isTrainingAnimationPlayed = false; // 训练动画是否已经播放
  38. public bool isHideBowlRunning = false; // 是否正在运行隐藏碗的协程
  39. private void Awake()
  40. {
  41. if (Instance == null)
  42. {
  43. Instance = this;
  44. //DontDestroyOnLoad(gameObject); // 必须关掉否则会导致原场景destroy不能执行
  45. }
  46. else
  47. {
  48. Destroy(gameObject);
  49. }
  50. }
  51. void Start()
  52. {
  53. Time.timeScale = 1; // 确保时间流逝正常
  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. trainingContent = String.Empty;
  108. foreach (var dog in dogsInScene)
  109. {
  110. if (trainingContent != String.Empty) { break; } // 如果已经有狗进入训练模式,跳出循环
  111. if (!dog.dogProperty.voiceCallEnable)
  112. {
  113. trainingContent = "voiceCall";
  114. }
  115. if (trainingContent != String.Empty)
  116. {
  117. sceneMode = SceneMode.TRAINING;
  118. dog.RemoveZzzParticle();
  119. trainingDogId = dog.dogProperty.d_id;
  120. totalTrainingTimes = 2;
  121. currentTrainingTimes = 0;
  122. GameData.focusDog = dogsInScene.IndexOf(dog);
  123. //GameData.focusDog = UserProperty.GetDogIndexById(dog.dogProperty.d_id);
  124. dogsInScene[GameData.focusDog].SetupInteract();
  125. interactDog = dogsInScene[GameData.focusDog].gameObject;
  126. // GameData.isVoiceTrainingToday = true;
  127. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  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. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  160. }
  161. }
  162. else if (dog.dogProperty.voiceCommand >= 40 && dog.dogProperty.CommandTrainingPhase() >= 4)
  163. {
  164. // 当狗的voiceCommand大于等于40并且完成第一阶段所有训练,进入第二阶段指令训练模式
  165. int random = UnityEngine.Random.Range(0, 100);
  166. if (GameTool.IntBetween(0, 20, random) && !dog.dogProperty.commandShake)
  167. {
  168. trainingContent = "commandShake";
  169. }
  170. else if (GameTool.IntBetween(20, 40, random) && !dog.dogProperty.commandTouch)
  171. {
  172. trainingContent = "commandTouch";
  173. }
  174. else if (GameTool.IntBetween(40, 60, random) && !dog.dogProperty.commandDeath)
  175. {
  176. trainingContent = "commandDeath";
  177. }
  178. else if (GameTool.IntBetween(60, 80, random) && !dog.dogProperty.commandTurnL)
  179. {
  180. trainingContent = "commandTurnL";
  181. }
  182. else if (GameTool.IntBetween(80, 100, random) && !dog.dogProperty.commandTurnR)
  183. {
  184. trainingContent = "commandTurnR";
  185. }
  186. }
  187. }
  188. if (trainingContent != String.Empty)
  189. {
  190. sceneMode = SceneMode.TRAINING;
  191. dog.RemoveZzzParticle();
  192. trainingDogId = dog.dogProperty.d_id;
  193. totalTrainingTimes = 2;
  194. currentTrainingTimes = 0;
  195. GameData.focusDog = dogsInScene.IndexOf(dog);
  196. //GameData.focusDog = UserProperty.GetDogIndexById(dog.dogProperty.d_id);
  197. dogsInScene[GameData.focusDog].SetupInteract();
  198. interactDog = dogsInScene[GameData.focusDog].gameObject;
  199. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  200. VoiceButtonOnlySwitch(true); // 交互模式下关闭其他菜单
  201. }
  202. }
  203. }
  204. if (this.sceneMode == SceneMode.TRAINING) // 这段代码控制场景进入训练模式
  205. {
  206. foreach (var dog in dogsInScene)
  207. {
  208. if (dog.dogState == DogState.INTERACT || dog.dogState == DogState.TRAINING)
  209. {
  210. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  211. dogCam.Priority = 10;
  212. // 单只狗在交互的状态控制代码
  213. if (dog.isMovingToPlayer)
  214. {
  215. dog.MovetoPlayer();
  216. }
  217. else
  218. {
  219. // 开始训练时让狗播放动画
  220. if (trainingContent != "voiceCall" && !isTrainingAnimationPlayed)
  221. {
  222. string command = trainingContent.Substring(7);
  223. dog.animator.SetTrigger(command);
  224. dog.animator.SetBool(command + "_status", true);
  225. isTrainingAnimationPlayed = true;
  226. }
  227. // 狗完成移动后,开始进入正式训练交互模式
  228. dog.dogState = DogState.TRAINING;
  229. if (!isTrainingMsgShowed_1 && !isTrainingMsgShowed_2 && currentTrainingTimes == 0)
  230. {
  231. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_00", EnviromentSetting.languageCode });
  232. if (msg.Contains("<<dog_name>>"))
  233. {
  234. msg = msg.Replace("<<dog_name>>", dog.dogProperty.dog_name);
  235. }
  236. MessageBoxController.ShowMessage(msg);
  237. var BGM = GameObject.Find("BGM");
  238. if (BGM != null)
  239. {
  240. FadeBGM(BGM.GetComponent<AudioSource>(), false);
  241. }
  242. isTrainingMsgShowed_1 = true;
  243. }
  244. else if (!isTrainingMsgShowed_2 && isTrainingMsgShowed_1 && currentTrainingTimes == 1)
  245. {
  246. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_01", EnviromentSetting.languageCode });
  247. if (msg.Contains("<<dog_name>>"))
  248. {
  249. msg = msg.Replace("<<dog_name>>", dog.dogProperty.dog_name);
  250. }
  251. MessageBoxController.ShowMessage(msg);
  252. isTrainingMsgShowed_2 = true;
  253. }
  254. }
  255. }
  256. else
  257. {
  258. // 暂时将其他非训练状态的狗game object隐藏
  259. //dog.gameObject.SetActive(false);
  260. }
  261. }
  262. }
  263. else if (sceneMode == SceneMode.INACTIVE) // 这段代码控制场景在交互模式
  264. {
  265. foreach (var dog in dogsInScene)
  266. {
  267. if (dog.dogState == DogState.INTERACT)
  268. {
  269. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  270. dogCam.Priority = 10;
  271. // 单只狗在交互的状态控制代码
  272. if (dog.isMovingToPlayer)
  273. {
  274. dog.MovetoPlayer();
  275. }
  276. else if (dog.InteractTimeout()) // 如果交互时间结束,结束交互状态
  277. {
  278. dog.ExitInteract();
  279. sceneMode = SceneMode.NORMAL; // 交互结束,退出交互状态
  280. //isInteractMode = false; // 交互结束,退出交互状态
  281. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  282. }
  283. else
  284. {
  285. PointerOnDog(); // 检测是否点击在狗上
  286. }
  287. }
  288. }
  289. }
  290. else
  291. {
  292. // 普通场景下的控制代码
  293. foreach (var dog in dogsInScene)
  294. {
  295. // 如果在eat drink进程结束前不执行随机场景代码
  296. // 恢复因为交互,训练模式隐藏的狗
  297. //if (dog.gameObject.activeSelf == false)
  298. //{
  299. // dog.gameObject.SetActive(true);
  300. //}
  301. if (dog.dogState == DogState.ITEM_CONSUME)
  302. {
  303. if (dog.isMovingToBowl)
  304. {
  305. dog.MovetoBowl();
  306. }
  307. }
  308. else
  309. {
  310. // 随机动作控制控制
  311. RandomCameraChange();
  312. if (listenBreak) // 如果用户按下说话按键,立刻切换到监听状态
  313. {
  314. dog.Listen();
  315. // StartCoroutine(dog.RotationToPlayerAndListen());
  316. }
  317. else if (dog.isMoving)
  318. {
  319. dog.RandomMove();
  320. }
  321. else if (sceneRandomFactor == dog.randomFactor && !dog.isSleeping) // 当狗自身的随机数和系统随机数相同时候触发。约100秒触发一次。
  322. {
  323. TimeSpan ts = DateTime.Now - dog.animationStartTime;
  324. if (ts.Seconds >= 30) // 如果距离上一个动作超过30秒就可以开始新的动作
  325. {
  326. float r = UnityEngine.Random.Range(0, 1f);
  327. if (r > 0.6) // 随机选择开始动画,或者移动
  328. {
  329. dog.IdleAnimation();
  330. }
  331. else // 狗狗开始步行移动
  332. {
  333. dog.SetMoveSpeed(0);
  334. dog.moveSpeed = 0;
  335. dog.RandomMove();
  336. }
  337. }
  338. }
  339. }
  340. }
  341. }
  342. #endregion
  343. }
  344. }
  345. private void OnDestroy()
  346. {
  347. Debug.Log("Home scene is destoried.");
  348. }
  349. IEnumerator InitialScene()
  350. {
  351. yield return null; // 跳过三帧,初始化最多三只狗
  352. //Debug.Log(isInitialDone);
  353. foreach (var dog in UserProperty.dogs)
  354. {
  355. DogInScene dogInScene = new DogInScene(dog);
  356. float x = UnityEngine.Random.Range(-1f, 1f); // 随机生成位置,考虑到手机评估宽度限制宽度
  357. float z = UnityEngine.Random.Range(0f, 5f); // 随机生成位置,考虑且保持和用户距离
  358. float y = UnityEngine.Random.Range(90f, 270f); // 随机生成朝向,且面向用户
  359. var initPosition = new Vector3(x, 0, z);
  360. StartCoroutine(DogComponentInstaller(dog)); // 加载狗的其他组件
  361. var dogGameObject = GameObject.Find(dog.dog_name);
  362. if (dogGameObject == null)
  363. {
  364. Debug.Log(dog.dog_name + "is not found in Home Controller");
  365. }
  366. dogGameObject.transform.position = initPosition;
  367. dogGameObject.transform.rotation = Quaternion.Euler(0, y, 0);
  368. dogGameObject.transform.localScale = new Vector3(2, 2, 2);
  369. dogInScene.SetGameObject(dogGameObject);
  370. dogsInScene.Add(dogInScene);
  371. }
  372. }
  373. // 加载狗的其他组件
  374. IEnumerator DogComponentInstaller(DogProperty dogProperty)
  375. {
  376. // 等待一帧,确保所有 Start() 方法都执行完成
  377. yield return null;
  378. // 第一帧以后开始执行
  379. GameObject dog = GameObject.Find(dogProperty.dog_name);
  380. // 加载指定的Animator controller
  381. Animator animator = dog.GetComponent<Animator>();
  382. RuntimeAnimatorController animatorController = Resources.Load<RuntimeAnimatorController>(DogBreedController.GetDogAnimationController(dogProperty.breed, "home_default"));
  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.6f, 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.RefreshDogInfo(dogJson);
  441. // 根据返回结果设定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; // 狗的voiceCall属性值/1000计算加成
  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. Debug.Log("Voice command training request at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  518. }
  519. else if (sceneMode == SceneMode.TRAINING)
  520. {
  521. //Debug.Log("current times before ++:" + this.currentTrainingTimes.ToString());
  522. this.currentTrainingTimes++;
  523. string url = "/api/voice/training/";
  524. WWWForm form = new();
  525. form.AddField("dog_id", UserProperty.dogs[GameData.focusDog].d_id);
  526. form.AddField("user_id", UserProperty.userId);
  527. form.AddField("voice_type", trainingContent);
  528. form.AddField("current_times", this.currentTrainingTimes);
  529. //Debug.Log("current times after ++:" + this.currentTrainingTimes.ToString());
  530. form.AddField("total_times", totalTrainingTimes);
  531. StartCoroutine(WebController.PostRequest(url, form, filePath, callback: VoiceCommandCallback));
  532. }
  533. }
  534. // 语音呼唤上传回调函数
  535. void VoiceCommandCallback(string json)
  536. {
  537. // 打印返回时间
  538. Debug.Log("Voice command callback at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  539. if (sceneMode == SceneMode.INACTIVE)
  540. {
  541. Debug.Log("Voice command callback");
  542. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  543. if (data != null && data["status"].ToString() == "success")
  544. {
  545. // 刷新狗的数据
  546. string dogJson = data["dogs"].ToString();
  547. UserProperty.RefreshDogInfo(dogJson);
  548. // 找到得分最高的指令
  549. float highestScore = 0;
  550. string highestScoreCommand = "";
  551. string scores = data["commandScoreMFCC"].ToString();
  552. var scoresList = JsonConvert.DeserializeObject<Dictionary<string, float>>(scores);
  553. foreach (var score in scoresList)
  554. {
  555. if (score.Value > highestScore)
  556. {
  557. highestScore = score.Value;
  558. highestScoreCommand = score.Key;
  559. }
  560. }
  561. // 根据狗的voiceCommand属性值修正得分。计算方式为狗的voiceCommand属性值/1000
  562. highestScore += UserProperty.dogs[GameData.focusDog].voiceCommand / 1000f;
  563. if (highestScore > 1)
  564. {
  565. highestScore = 1;
  566. }
  567. Debug.Log("Highest score:" + highestScore.ToString());
  568. Debug.Log("Highest command:" + highestScoreCommand);
  569. dogsInScene[GameData.focusDog].ResetAnimationStatus(); // 重置狗的动画状态
  570. if (highestScore >= EnviromentSetting.voiceRecognitionScore)
  571. {
  572. string animationTrigger = highestScoreCommand.Substring(7);
  573. string animationBool = animationTrigger + "_status";
  574. var animator = dogsInScene[GameData.focusDog].gameObject.GetComponent<Animator>();
  575. if (highestScoreCommand == "commandBark")
  576. {
  577. DogBarkController.Instance.PlayDogBarkWithDelay(3); // 狗叫相应一下
  578. }
  579. else
  580. {
  581. HomeSoundEffectController.Instance.PlaySoundEffect(5);
  582. }
  583. //animator.SetTrigger(animationTrigger);
  584. animator.Play(animationTrigger);
  585. string[] noStatusCommand = { "turnL", "turnR" };
  586. if (Array.IndexOf(noStatusCommand, animationTrigger) < 0)
  587. {
  588. animator.SetBool(animationBool, true);
  589. Debug.Log(animationBool + " is " + animator.GetBool(animationBool));
  590. }
  591. else
  592. {
  593. // turnL 和 turnR 动画不需要设置状态
  594. }
  595. // animator.SetBool(animationBool, true);
  596. // 交互动画执行一段时间后停止
  597. dogsInScene[GameData.focusDog].interactAnimationStartTime = DateTime.Now;
  598. StartCoroutine(dogsInScene[GameData.focusDog].InteractAnimationCountDown());
  599. }
  600. else
  601. {
  602. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  603. dogsInScene[GameData.focusDog].PlayQuestionMark();
  604. }
  605. }
  606. else
  607. {
  608. Debug.Log(data["message"]);
  609. }
  610. }
  611. else if (sceneMode == SceneMode.TRAINING)
  612. {
  613. Debug.Log("Voice training Callback");
  614. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  615. if (data != null && data["status"].ToString().ToLower() == "success")
  616. {
  617. if (data["message"].ToString().ToLower() == "pass")
  618. {
  619. // 刷新狗的数据,包含dogsInScene
  620. string dogJson = data["dogs"].ToString();
  621. UserProperty.RefreshDogInfo(dogJson);
  622. var trainingDog = dogsInScene[GameData.focusDog];
  623. trainingDog.ReloadDogProperty(); // 刷新狗的数据
  624. // 成功后让狗子播放训练的动画
  625. if (trainingContent != "voiceCall")
  626. {
  627. string command = trainingContent.Substring(7);
  628. trainingDog.animator.SetTrigger(command);
  629. // string[] noStatusCommand = { "apple", "banana", "cherry" };
  630. trainingDog.animator.SetBool(command + "_status", true);
  631. }
  632. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_10", EnviromentSetting.languageCode });
  633. if (msg.Contains("<<dog_name>>"))
  634. {
  635. msg = msg.Replace("<<dog_name>>", interactDog.name);
  636. }
  637. GameTool.PauseGameTime();
  638. MessageBoxController.ShowMessage(msg, ExitTrainingMode);
  639. this.sceneMode = SceneMode.NORMAL;
  640. VoiceButtonOnlySwitch(false); // 交互结束,打开其他菜单
  641. GameData.SetIsVoiceTrainingToday(); // 设置当天已经完成了语音训练
  642. }
  643. else if (data["message"].ToString() == "fail")
  644. {
  645. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  646. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  647. if (msg.Contains("<<dog_name>>"))
  648. {
  649. msg = msg.Replace("<<dog_name>>", interactDog.name);
  650. }
  651. GameTool.PauseGameTime();
  652. MessageBoxController.ShowMessage(msg, RestartTraining);
  653. }
  654. }
  655. else
  656. {
  657. Debug.Log(data["message"]);
  658. if (EnviromentSetting.runEnv == "Release")
  659. {
  660. HomeSoundEffectController.Instance.PlaySoundEffect(4);
  661. string msg = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "game_message", trainingContent + "_20", EnviromentSetting.languageCode });
  662. if (msg.Contains("<<dog_name>>"))
  663. {
  664. msg = msg.Replace("<<dog_name>>", interactDog.name);
  665. }
  666. GameTool.PauseGameTime();
  667. MessageBoxController.ShowMessage(msg, RestartTraining);
  668. }
  669. }
  670. SetDogsIsTrigger(true);
  671. }
  672. }
  673. #endregion
  674. #region interact mode
  675. // 重置training相关参数
  676. private void ExitTrainingMode()
  677. {
  678. foreach (var dog in dogsInScene)
  679. {
  680. if (dog.dogProperty.d_id == trainingDogId)
  681. {
  682. dog.ExitInteract();
  683. }
  684. }
  685. trainingContent = String.Empty;
  686. totalTrainingTimes = 2;
  687. currentTrainingTimes = 0;
  688. trainingDogId = "";
  689. isTrainingMsgShowed_1 = false;
  690. isTrainingMsgShowed_2 = false;
  691. isTrainingAnimationPlayed = false;
  692. sceneMode = SceneMode.NORMAL; // 交互模式
  693. Debug.Log("Reset Training Mode Parameters");
  694. GameTool.ResumeGameTime();
  695. GameData.SetIsVoiceTrainingToday(); // 训练完成,设置为true
  696. var BGM = GameObject.Find("BGM");
  697. if (BGM != null)
  698. {
  699. FadeBGM(BGM.GetComponent<AudioSource>(), true);
  700. }
  701. }
  702. private void RestartTraining()
  703. {
  704. currentTrainingTimes = 0;
  705. isTrainingMsgShowed_1 = false;
  706. isTrainingMsgShowed_2 = false;
  707. Time.timeScale = 1f;
  708. }
  709. // 改变Voice And Menu 菜单形态
  710. public void VoiceButtonOnlySwitch(bool state)
  711. {
  712. // 交互时候关闭其他菜单
  713. var vamUI = GameObject.Find("VoiceAndMenu");
  714. if (vamUI != null)
  715. {
  716. var UIdocument = vamUI.transform.Find("UIDocument").gameObject;
  717. var voiceController = UIdocument.GetComponent<VoiceController>();
  718. voiceController.isCommandMode = state;
  719. }
  720. }
  721. // 检测是否点击在狗上
  722. void PointerOnDog()
  723. {
  724. //DetectTouchMethod();
  725. // 检查当前指针是否有效
  726. if (Pointer.current == null) return;
  727. // 获取当前指针的悬浮位置
  728. Vector2 pointerPosition = Pointer.current.position.ReadValue();
  729. var mainCamera = GameObject.Find("Camera").GetComponent<Camera>();
  730. Ray ray = mainCamera.ScreenPointToRay(pointerPosition);
  731. if (Physics.Raycast(ray, out RaycastHit hit))
  732. {
  733. //Debug.Log($"Clicked on: {hit.collider.gameObject.name}");
  734. // 射线检测起始点击是否在狗上
  735. if (hit.collider.gameObject == interactDog)
  736. {
  737. if (previousPointerPosition != pointerPosition)
  738. {
  739. interactTime += Time.deltaTime;
  740. Debug.Log("interactTime:" + interactTime);
  741. foreach (var dog in dogsInScene)
  742. {
  743. if (dog.gameObject == interactDog)
  744. {
  745. dog.interactLastUpdate = DateTime.Now;
  746. }
  747. }
  748. previousPointerPosition = pointerPosition;
  749. }
  750. }
  751. if (interactTime > 2.5) // 如果交互时间超过1秒,播放心形粒子效果
  752. {
  753. HeartParticlePlay();
  754. DogBarkController.Instance.PlayDogBarkWithDelay(1); // 狗叫相应一下
  755. }
  756. }
  757. }
  758. void HeartParticlePlay()
  759. {
  760. // 播放心形粒子效果
  761. var heartParticle = GameObject.Find("Particle Heart");
  762. heartParticle.GetComponent<ParticleSystem>().Play();
  763. interactTime = 0;
  764. }
  765. public void SetInteractDog(GameObject dog)
  766. {
  767. interactDog = dog;
  768. dogCam.m_LookAt = dog.gameObject.transform; // 摄像机看向交互的狗
  769. dogCam.Priority = 10;
  770. }
  771. #endregion
  772. #region 场景环境控制
  773. // 淡入或淡出背景音乐
  774. private void FadeBGM(AudioSource bgmSource, bool fadeIn, float duration = 2f)
  775. {
  776. // fadeIn: true表示淡入 false表示淡出
  777. if (bgmSource == null) return; // 如果没有 AudioSource,则直接返回
  778. StartCoroutine(FadeBGMCoroutine(bgmSource, fadeIn, duration));
  779. }
  780. private IEnumerator FadeBGMCoroutine(AudioSource bgmSource, bool fadeIn, float duration)
  781. {
  782. float elapsedTime = 0f;
  783. float startVolume = bgmSource.volume;
  784. float targetVolume = fadeIn ? 0.4f : 0f; // 淡入目标音量为1,淡出目标音量为0
  785. while (elapsedTime < duration)
  786. {
  787. bgmSource.volume = Mathf.Lerp(startVolume, targetVolume, elapsedTime / duration);
  788. elapsedTime += Time.deltaTime;
  789. yield return null;
  790. }
  791. bgmSource.volume = targetVolume; // 确保音量达到目标值
  792. if (!fadeIn)
  793. {
  794. bgmSource.Stop(); // 如果是淡出,停止播放
  795. }
  796. else
  797. {
  798. bgmSource.Play(); // 如果是淡入,开始播放
  799. }
  800. }
  801. // 设置场景模式
  802. public void SetSceneMode(SceneMode mode)
  803. {
  804. this.sceneMode = mode;
  805. }
  806. // 刷新dogInScene的狗数据
  807. public void RefreshDogInScene()
  808. {
  809. foreach (var dog in dogsInScene)
  810. {
  811. dog.ReloadDogProperty();
  812. }
  813. }
  814. // 场景随机切换镜头看向不同的狗
  815. void RandomCameraChange()
  816. {
  817. int delay = 10; // 延迟10秒执行一次
  818. TimeSpan ts = DateTime.Now - lastCameraChange;
  819. if (ts.TotalSeconds < delay) { return; }
  820. int dogCount = dogsInScene.Count;
  821. int r = UnityEngine.Random.Range(0, dogCount + 1);
  822. if (r < dogCount)
  823. {
  824. dogCam.m_LookAt = dogsInScene[r].gameObject.transform;
  825. dogCam.Priority = 10;
  826. playerCam.Priority = 1;
  827. }
  828. else
  829. {
  830. dogCam.Priority = 1;
  831. playerCam.Priority = 10;
  832. }
  833. lastCameraChange = DateTime.Now;
  834. }
  835. // 检测场景是否初始化完成
  836. bool SceneInitialCheck()
  837. {
  838. bool initDone = true;
  839. if (dogsInScene.Count == UserProperty.dogs.Count) // 检测是否所有狗都被加载
  840. {
  841. foreach (var dog in dogsInScene)
  842. {
  843. if (dog.gameObject.GetComponent<Animator>().runtimeAnimatorController == null)
  844. {
  845. initDone = false;
  846. }
  847. }
  848. }
  849. else
  850. {
  851. initDone = false;
  852. }
  853. //Debug.Log("Home scene initial status:"+initDone);
  854. return initDone;
  855. }
  856. // 计算多只狗的中心位置,用于主摄像机瞄准
  857. private Vector3 CenterOfDogs()
  858. {
  859. if (dogsInScene.Count == 0)
  860. {
  861. return Vector3.zero;
  862. }
  863. Vector3 center = Vector3.zero;
  864. foreach (var dog in dogsInScene)
  865. {
  866. center += dog.gameObject.transform.position;
  867. }
  868. center /= dogsInScene.Count;
  869. return center;
  870. }
  871. // 设置所有狗is trigger属性
  872. public void SetDogsIsTrigger(bool triggerSetting)
  873. {
  874. foreach (var dog in dogsInScene)
  875. {
  876. BoxCollider boxCollider = dog.gameObject.GetComponent<BoxCollider>();
  877. if (boxCollider != null)
  878. {
  879. boxCollider.isTrigger = triggerSetting;
  880. }
  881. }
  882. }
  883. #endregion
  884. #region 道具使用控制
  885. public IEnumerator HideBowlAfterItemConsume(ItemGroup type)
  886. {
  887. isHideBowlRunning = true; // 设置为正在运行状态
  888. string inTheBowl;
  889. string bowlName;
  890. if (type == ItemGroup.FOOD)
  891. {
  892. inTheBowl = "Food";
  893. bowlName = "Bowl_food";
  894. }
  895. else if (type == ItemGroup.WATER)
  896. {
  897. inTheBowl = "Water";
  898. bowlName = "Bowl_water";
  899. }
  900. else
  901. {
  902. yield break; // 如果类型不匹配,直接返回
  903. }
  904. bool allDogsDone = false;
  905. while (!allDogsDone)
  906. {
  907. allDogsDone = true; // 假设所有狗都完成了
  908. foreach (var dog in dogsInScene)
  909. {
  910. if (dog.dogState == DogState.ITEM_CONSUME)
  911. {
  912. allDogsDone = false; // 如果有狗还在消耗状态,则设置为false
  913. break;
  914. }
  915. }
  916. yield return new WaitForSeconds(0.5f); // 每0.5秒检查一次
  917. }
  918. var food = GameObject.Find(inTheBowl);
  919. var targetBowl = GameObject.Find(bowlName);
  920. food.transform.localPosition = new Vector3(-1, -10, -1);
  921. yield return new WaitForSeconds(2f); // 暂停2秒
  922. targetBowl.transform.position = new Vector3(-1, -10, -1); // 将饭盆回归原位
  923. food.transform.localPosition = Vector3.zero; // 将食物回归原位
  924. // 重制摄像头和菜单
  925. HomeController.dogCam.Priority = 1;
  926. HomeController.playerCam.Priority = 10;
  927. var uiPlaceholder = GameObject.Find("UI Placeholder");
  928. var vamUI = uiPlaceholder.transform.Find("VoiceAndMenu").gameObject;
  929. vamUI.SetActive(true);
  930. isHideBowlRunning = false; // 设置为不在运行状态
  931. }
  932. #endregion
  933. }
  934. public enum ItemGroup
  935. {
  936. FOOD,
  937. WATER
  938. }
  939. public enum SceneMode
  940. {
  941. TRAINING,
  942. INACTIVE,
  943. NORMAL,
  944. }