PlayToyController.cs 10 KB

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