PlayToyController.cs 9.5 KB

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