PlayToyController.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 = 60;
  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. float screenWidth = Screen.width;
  75. float screenHeight = Screen.height;
  76. float aspectRatio = screenWidth / screenHeight;
  77. Debug.Log("屏幕宽高比: " + aspectRatio);
  78. xForce = (mouseEndPosition.x - mouseStartPosition.x)/throwTime/forceAdjust*aspectRatio;
  79. yForce = (mouseEndPosition.y - mouseStartPosition.y)/throwTime/forceAdjust*aspectRatio;
  80. Debug.Log("xForce is: " + xForce);
  81. Debug.Log("yForce is: " + yForce);
  82. if (yForce > 1 && yForce > xForce*0.5f) // 确保是向前飞出飞盘
  83. {
  84. AddThrowForce();
  85. }
  86. // 重置值
  87. mouseStartPosition = Vector2.zero;
  88. mouseEndPosition = Vector2.zero;
  89. }
  90. }
  91. // 飞碟飞出后,给飞碟添加一个力
  92. public void AddThrowForce()
  93. {
  94. if (PlayData.gameStatus == PlayData.GameStatus.notStart)
  95. {
  96. float verticalForce = 6; // 定义垂直方向力量
  97. var toy = GameObject.Find("toy");
  98. PlayData.throwStartPoision = toy.transform.position; // 上报飞盘其实位置
  99. PlayData.gameStatus = PlayData.GameStatus.inProgress; // 游戏状态设置为进行中
  100. Rigidbody rb = toy.GetComponent<Rigidbody>();
  101. Vector3 force = new Vector3(xForce, verticalForce, yForce);
  102. rb.isKinematic = false;
  103. rb.AddForce(force, ForceMode.Impulse);
  104. PlayData.gameStatus = PlayData.GameStatus.inProgress;
  105. }
  106. else
  107. {
  108. return;
  109. }
  110. }
  111. // 飞碟飞出后,狗追逐飞碟
  112. public void DogCatchToy()
  113. {
  114. // 调整摄像机
  115. CamPlayer.Priority = 0;
  116. CamDog.Priority = 10;
  117. var dog = GameObject.Find("dog");
  118. var toy = GameObject.Find("toy");
  119. DogProperty dogProperty = UserProperty.dogs[0]; // 读取狗的数据
  120. //float turnSpeed = 90.0f; // 每秒最多旋转角度
  121. //dog.transform.LookAt(fisbee.transform.position);
  122. if (toy.transform.position.y < 0.43 && PlayData.gameStatus == PlayData.GameStatus.inProgress)
  123. {
  124. PlayData.gameStatus = PlayData.GameStatus.finishFail; // 游戏状态设置为失败。狗依然在追逐飞盘,但是飞盘已经落地
  125. Animator animator = dog.GetComponent<Animator>();
  126. animator.SetBool("runState", false);
  127. Debug.Log("飞盘落地了");
  128. }
  129. else if (dog != null && toy != null)
  130. {
  131. // 计算目标方向
  132. Vector3 direction = toy.transform.position - dog.transform.position;
  133. direction.y = 0; // 忽略垂直方向的偏移
  134. var targetPosition = toy.transform.position;
  135. targetPosition.y = 0.4f;
  136. Quaternion targetRotation = new();
  137. // 创建目标旋转
  138. if (direction != Vector3.zero)
  139. {
  140. targetRotation = Quaternion.LookRotation(direction);
  141. }
  142. // 直接转向
  143. dog.transform.LookAt(targetPosition);
  144. // 平滑旋转到目标方向
  145. //dog.transform.rotation = Quaternion.RotateTowards(dog.transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
  146. float dogSpeed = (100+dogProperty.runSpeed)/20; // 狗向飞盘移动
  147. dog.transform.position = Vector3.MoveTowards(dog.transform.position, targetPosition, dogSpeed * Time.deltaTime);
  148. // 狗切换到跑步状态
  149. Animator animator = dog.GetComponent<Animator>();
  150. if (animator.GetBool("runState") != true) { animator.SetBool("runState", true); }
  151. }
  152. else
  153. {
  154. Debug.LogError("Dog or toy object is not assigned!");
  155. }
  156. }
  157. // 初始化 playground UI 的按键语言和功能
  158. public void UI_Initial()
  159. {
  160. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  161. var btnArea = root.Q<VisualElement>("btnArea");
  162. var confirmBtn = btnArea.Q<Button>("confirm");
  163. var playagainBtn = btnArea.Q<Button>("playAgain");
  164. string textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "confirm", EnviromentSetting.languageCode });
  165. confirmBtn.text = textValue;
  166. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "play_again", EnviromentSetting.languageCode });
  167. playagainBtn.text = textValue;
  168. playagainBtn.clicked += ()=> GameReset();
  169. confirmBtn.clicked += ConfirmBtnClick;
  170. }
  171. // 游戏结束调用显示显示结果UI
  172. public void ShowGameResult()
  173. {
  174. if (PlayData.isResultShowed == false)
  175. {
  176. var playgroundUI = GameObject.Find("UI Placeholder").transform.Find("PlaygroundUI").gameObject;
  177. playgroundUI.SetActive(true);
  178. UI_Initial();
  179. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  180. var gameResult = root.Q<Label>("gameResult");
  181. string textValue;
  182. if (PlayData.gameStatus == PlayData.GameStatus.finishSuccess)
  183. {
  184. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishSuccess", EnviromentSetting.languageCode });
  185. textValue = textValue.Replace("<<distance>>", Math.Round(PlayData.throwDistance(), 2).ToString()); // 保留小数点后2位
  186. gameResult.text = textValue;
  187. }
  188. else if (PlayData.gameStatus == PlayData.GameStatus.finishFail)
  189. {
  190. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishFail", EnviromentSetting.languageCode });
  191. gameResult.text = textValue;
  192. }
  193. else if (PlayData.gameStatus == PlayData.GameStatus.finishOutOfBound)
  194. {
  195. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishOutOfBound", EnviromentSetting.languageCode });
  196. gameResult.text = textValue;
  197. }
  198. }
  199. PlayData.isResultShowed = true;
  200. }
  201. // 游戏重置
  202. void GameReset()
  203. {
  204. PlayData.Reset();
  205. // 获取当前场景的名称
  206. string currentSceneName = SceneManager.GetActiveScene().name;
  207. // 重新加载当前场景
  208. SceneManager.LoadScene(currentSceneName);
  209. }
  210. // UI 点击确认后,返回到Home界面
  211. void ConfirmBtnClick()
  212. {
  213. SceneManager.LoadScene("Home");
  214. }
  215. }
  216. public static class PlayData
  217. {
  218. public static bool throwHitWall = false; // 飞盘是否撞到空气墙
  219. public static bool throwCatched = false; // 飞盘是否被狗接到
  220. public static bool isResultShowed = false; // 是否显示游戏结果
  221. public static bool isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  222. public static Vector3 throwStartPoision = Vector3.zero;
  223. public static Vector3 throwEndPosition = Vector3.zero;
  224. public enum GameStatus
  225. {
  226. notStart,
  227. inProgress,
  228. finishSuccess,
  229. finishFail, // 玩具丢出,但是狗没有接住
  230. finishOutOfBound // 玩具飞出界
  231. }
  232. public static GameStatus gameStatus = GameStatus.notStart;
  233. //public static string gameStatus = "not start";
  234. public static float throwDistance()
  235. {
  236. if (gameStatus == GameStatus.finishSuccess) {
  237. Debug.Log("start position is"+throwStartPoision);
  238. Debug.Log("end position is" + throwEndPosition);
  239. return Vector3.Distance(throwEndPosition, throwStartPoision);
  240. }
  241. else { return 0; }
  242. }
  243. public static void Reset()
  244. {
  245. PlayData.throwHitWall = false; // 飞盘是否撞到空气墙
  246. PlayData.throwCatched = false; // 飞盘是否被狗接到
  247. PlayData.isResultShowed = false; // 是否显示游戏结果
  248. PlayData.isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  249. PlayData.throwStartPoision = Vector3.zero;
  250. PlayData.throwEndPosition = Vector3.zero;
  251. PlayData.gameStatus = GameStatus.notStart ;
  252. }
  253. }