HomeController.cs 41 KB

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