PlayToyController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. using Cinemachine;
  2. using System;
  3. using UnityEngine;
  4. using UnityEngine.InputSystem;
  5. using UnityEngine.SceneManagement;
  6. using UnityEngine.UIElements;
  7. /* PlayToyController玩飞盘的主要控制代码
  8. * DogCatchToy 启动狗去抓玩具飞盘
  9. * ShowGameResult 显示游戏结算canvas
  10. * Throw 丢飞盘出去控制
  11. * addThrowForce 给飞盘玩具添加初始力量
  12. * UILanguageInit 初始化游戏语言
  13. * GameReset 游戏重置
  14. * PlayData 静态类用于存储游戏运行状态和数据
  15. */
  16. public class PlayToyController : MonoBehaviour
  17. {
  18. private float throwTime;
  19. private float xForce, yForce;
  20. Vector2 mouseStartPosition = new(0f, 0f);
  21. Vector2 mouseEndPosition = new(0f, 0f);
  22. // forceAdjust 用于调节力量参数,数字越大减力效果越高
  23. public int forceAdjust = 100;
  24. private CinemachineVirtualCamera CamPlayer, CamDog;
  25. private GameObject dog;
  26. // Start is called once before the first execution of Update after the MonoBehaviour is created
  27. void Start()
  28. {
  29. PlayData.Reset();
  30. CamPlayer = GameObject.Find("Player CAM").GetComponent<CinemachineVirtualCamera>();
  31. CamDog = GameObject.Find("Dog CAM").GetComponent<CinemachineVirtualCamera>();
  32. }
  33. // FixedUpdate is called once per frame
  34. void FixedUpdate()
  35. {
  36. if (PlayData.gameStatus == PlayData.GameStatus.inProgress)
  37. {
  38. DogCatchToy();
  39. }
  40. else if (PlayData.gameStatus != PlayData.GameStatus.notStart) // 游戏结束状态
  41. {
  42. ShowGameResult();
  43. }
  44. }
  45. public void Throw(InputAction.CallbackContext context)
  46. {
  47. //Debug.Log(context.control.device);
  48. if (PlayData.gameStatus == PlayData.GameStatus.inProgress) { return; }
  49. // 按下鼠标
  50. if (context.phase == InputActionPhase.Started)
  51. {
  52. // 动态配置Dog V Cam。不能放在Start()里面,因为狗是动态加载的。Start时候狗还没有加载。
  53. dog = GameObject.Find("dog");
  54. CamDog.m_Follow = dog.transform;
  55. CamDog.m_LookAt = dog.transform;
  56. Ray ray = Camera.main.ScreenPointToRay(Pointer.current.position.ReadValue());
  57. if (Physics.Raycast(ray, out RaycastHit hit))
  58. {
  59. Debug.Log($"Clicked on: {hit.collider.gameObject.tag}");
  60. // 射线检测起始点击是否在飞盘上
  61. if (hit.collider.gameObject.name == "toy")
  62. {
  63. PlayData.isMouseStartOnTarget = true;
  64. mouseStartPosition = Pointer.current.position.ReadValue();
  65. }
  66. }
  67. }
  68. // 松开鼠标
  69. if (context.phase == InputActionPhase.Canceled && PlayData.isMouseStartOnTarget)
  70. {
  71. mouseEndPosition = Pointer.current.position.ReadValue();
  72. Debug.Log("Drag end time at: " + context.duration);
  73. throwTime = Convert.ToSingle(context.duration);
  74. xForce = (mouseEndPosition.x - mouseStartPosition.x)/throwTime/forceAdjust;
  75. yForce = (mouseEndPosition.y - mouseStartPosition.y)/throwTime/forceAdjust;
  76. Debug.Log("xForce is: " + xForce);
  77. Debug.Log("yForce is: " + yForce);
  78. if (yForce > 1 && yForce > xForce*0.5f) // 确保是向前飞出飞盘
  79. {
  80. AddThrowForce();
  81. }
  82. // 重置值
  83. mouseStartPosition = Vector2.zero;
  84. mouseEndPosition = Vector2.zero;
  85. }
  86. }
  87. // 飞碟飞出后,给飞碟添加一个力
  88. public void AddThrowForce()
  89. {
  90. if (PlayData.gameStatus == PlayData.GameStatus.notStart)
  91. {
  92. float verticalForce = 6; // 定义垂直方向力量
  93. var toy = GameObject.Find("toy");
  94. PlayData.throwStartPoision = toy.transform.position; // 上报飞盘其实位置
  95. PlayData.gameStatus = PlayData.GameStatus.inProgress; // 游戏状态设置为进行中
  96. Rigidbody rb = toy.GetComponent<Rigidbody>();
  97. Vector3 force = new Vector3(xForce, verticalForce, yForce);
  98. rb.isKinematic = false;
  99. rb.AddForce(force, ForceMode.Impulse);
  100. PlayData.gameStatus = PlayData.GameStatus.inProgress;
  101. }
  102. else
  103. {
  104. return;
  105. }
  106. }
  107. // 飞碟飞出后,狗追逐飞碟
  108. public void DogCatchToy()
  109. {
  110. // 调整摄像机
  111. CamPlayer.Priority = 0;
  112. CamDog.Priority = 10;
  113. var dog = GameObject.Find("dog");
  114. var toy = GameObject.Find("toy");
  115. DogProperty dogProperty = UserProperty.dogs[0]; // 读取狗的数据
  116. //float turnSpeed = 90.0f; // 每秒最多旋转角度
  117. //dog.transform.LookAt(fisbee.transform.position);
  118. if (toy.transform.position.y < 0.43 && PlayData.gameStatus == PlayData.GameStatus.inProgress)
  119. {
  120. PlayData.gameStatus = PlayData.GameStatus.finishFail; // 游戏状态设置为失败。狗依然在追逐飞盘,但是飞盘已经落地
  121. Animator animator = dog.GetComponent<Animator>();
  122. animator.SetBool("runState", false);
  123. Debug.Log("飞盘落地了");
  124. }
  125. else if (dog != null && toy != null)
  126. {
  127. // 计算目标方向
  128. Vector3 direction = toy.transform.position - dog.transform.position;
  129. direction.y = 0; // 忽略垂直方向的偏移
  130. var targetPosition = toy.transform.position;
  131. targetPosition.y = 0.4f;
  132. Quaternion targetRotation = new();
  133. // 创建目标旋转
  134. if (direction != Vector3.zero)
  135. {
  136. targetRotation = Quaternion.LookRotation(direction);
  137. }
  138. // 直接转向
  139. dog.transform.LookAt(targetPosition);
  140. // 平滑旋转到目标方向
  141. //dog.transform.rotation = Quaternion.RotateTowards(dog.transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
  142. float dogSpeed = dogProperty.runSpeed/10; // 狗向飞盘移动
  143. dog.transform.position = Vector3.MoveTowards(dog.transform.position, targetPosition, dogSpeed * Time.deltaTime);
  144. // 狗切换到跑步状态
  145. Animator animator = dog.GetComponent<Animator>();
  146. if (animator.GetBool("runState") != true) { animator.SetBool("runState", true); }
  147. }
  148. else
  149. {
  150. Debug.LogError("Dog or toy object is not assigned!");
  151. }
  152. }
  153. // 初始化 playground UI 的按键语言和功能
  154. public void UI_Initial()
  155. {
  156. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  157. var btnArea = root.Q<VisualElement>("btnArea");
  158. var confirmBtn = btnArea.Q<Button>("confirm");
  159. var playagainBtn = btnArea.Q<Button>("playAgain");
  160. string textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "confirm", EnviromentSetting.languageCode });
  161. confirmBtn.text = textValue;
  162. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "play_again", EnviromentSetting.languageCode });
  163. playagainBtn.text = textValue;
  164. playagainBtn.clicked += ()=> GameReset();
  165. confirmBtn.clicked += ConfirmBtnClick;
  166. }
  167. // 游戏结束调用显示显示结果UI
  168. public void ShowGameResult()
  169. {
  170. if (PlayData.isResultShowed == false)
  171. {
  172. var playgroundUI = GameObject.Find("UI Placeholder").transform.Find("PlaygroundUI").gameObject;
  173. playgroundUI.SetActive(true);
  174. UI_Initial();
  175. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  176. var gameResult = root.Q<Label>("gameResult");
  177. string textValue;
  178. if (PlayData.gameStatus == PlayData.GameStatus.finishSuccess)
  179. {
  180. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishSuccess", EnviromentSetting.languageCode });
  181. textValue = textValue.Replace("<<distance>>", Math.Round(PlayData.throwDistance(), 2).ToString()); // 保留小数点后2位
  182. gameResult.text = textValue;
  183. }
  184. else if (PlayData.gameStatus == PlayData.GameStatus.finishFail)
  185. {
  186. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishFail", EnviromentSetting.languageCode });
  187. gameResult.text = textValue;
  188. }
  189. else if (PlayData.gameStatus == PlayData.GameStatus.finishOutOfBound)
  190. {
  191. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishOutOfBound", EnviromentSetting.languageCode });
  192. gameResult.text = textValue;
  193. }
  194. }
  195. PlayData.isResultShowed = true;
  196. }
  197. // 游戏重置
  198. void GameReset()
  199. {
  200. PlayData.Reset();
  201. // 获取当前场景的名称
  202. string currentSceneName = SceneManager.GetActiveScene().name;
  203. // 重新加载当前场景
  204. SceneManager.LoadScene(currentSceneName);
  205. }
  206. // UI 点击确认后,返回到Home界面
  207. void ConfirmBtnClick()
  208. {
  209. SceneManager.LoadScene("Home");
  210. }
  211. }
  212. public static class PlayData
  213. {
  214. public static bool throwHitWall = false; // 飞盘是否撞到空气墙
  215. public static bool throwCatched = false; // 飞盘是否被狗接到
  216. public static bool isResultShowed = false; // 是否显示游戏结果
  217. public static bool isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  218. public static Vector3 throwStartPoision = Vector3.zero;
  219. public static Vector3 throwEndPosition = Vector3.zero;
  220. public enum GameStatus
  221. {
  222. notStart,
  223. inProgress,
  224. finishSuccess,
  225. finishFail, // 玩具丢出,但是狗没有接住
  226. finishOutOfBound // 玩具飞出界
  227. }
  228. public static GameStatus gameStatus = GameStatus.notStart;
  229. //public static string gameStatus = "not start";
  230. public static float throwDistance()
  231. {
  232. if (gameStatus == GameStatus.finishSuccess) {
  233. Debug.Log("start position is"+throwStartPoision);
  234. Debug.Log("end position is" + throwEndPosition);
  235. return Vector3.Distance(throwEndPosition, throwStartPoision);
  236. }
  237. else { return 0; }
  238. }
  239. public static void Reset()
  240. {
  241. PlayData.throwHitWall = false; // 飞盘是否撞到空气墙
  242. PlayData.throwCatched = false; // 飞盘是否被狗接到
  243. PlayData.isResultShowed = false; // 是否显示游戏结果
  244. PlayData.isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  245. PlayData.throwStartPoision = Vector3.zero;
  246. PlayData.throwEndPosition = Vector3.zero;
  247. PlayData.gameStatus = GameStatus.notStart ;
  248. }
  249. }