PlayToyController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using Cinemachine;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.InputSystem;
  7. using UnityEngine.SceneManagement;
  8. using UnityEngine.UIElements;
  9. /* PlayToyController玩飞盘的主要控制代码
  10. * DogCatchToy 启动狗去抓玩具飞盘
  11. * ShowGameResult 显示游戏结算canvas
  12. * Throw 丢飞盘出去控制
  13. * addThrowForce 给飞盘玩具添加初始力量
  14. * UILanguageInit 初始化游戏语言
  15. * GameReset 游戏重置
  16. * PlayData 静态类用于存储游戏运行状态和数据
  17. */
  18. public class PlayToyController : MonoBehaviour
  19. {
  20. private float throwTime;
  21. private float xForce, yForce;
  22. Vector2 mouseStartPosition = new(0f, 0f);
  23. Vector2 mouseEndPosition = new(0f, 0f);
  24. // forceAdjust 用于调节力量参数,数字越大减力效果越高
  25. public int forceAdjust = 60;
  26. private CinemachineVirtualCamera CamPlayer, CamDog;
  27. private GameObject dog;
  28. // Start is called once before the first execution of Update after the MonoBehaviour is created
  29. void Start()
  30. {
  31. PlayData.Reset();
  32. CamPlayer = GameObject.Find("Player CAM").GetComponent<CinemachineVirtualCamera>();
  33. CamDog = GameObject.Find("Dog CAM").GetComponent<CinemachineVirtualCamera>();
  34. LoadFrisbee();
  35. }
  36. // FixedUpdate is called once per frame
  37. void FixedUpdate()
  38. {
  39. if (PlayData.gameStatus == PlayData.GameStatus.inProgress)
  40. {
  41. DogCatchToy();
  42. }
  43. else if (PlayData.gameStatus != PlayData.GameStatus.notStart) // 游戏结束状态
  44. {
  45. ShowGameResult();
  46. }
  47. }
  48. // 读取飞盘
  49. private void LoadFrisbee()
  50. {
  51. GameObject toyResource = Resources.Load<GameObject>("Item/frisbee");
  52. GameObject toy = Instantiate(toyResource);
  53. toy.name = "toy";
  54. toy.tag = "Throw Material";
  55. toy.transform.localPosition = new Vector3(-0.1f, 0.66f, -10.8f);
  56. toy.transform.localRotation = Quaternion.Euler(-115f, 0, 0);
  57. toy.transform.localScale = new Vector3(0.75f, 0.75f, 0.75f); // 初始化位置
  58. // 配置material
  59. Renderer renderer = toy.GetComponent<Renderer>();
  60. Material mat = Resources.Load<Material>("Item/Materials/frisbee/blue");
  61. if (GameData.playedToy == "toy_00001")
  62. {
  63. mat = Resources.Load<Material>("Item/Materials/frisbee/blue");
  64. }
  65. renderer.material = mat;
  66. // 加载Rigidbody
  67. Rigidbody rigidbody = toy.AddComponent<Rigidbody>();
  68. rigidbody.isKinematic = true;
  69. rigidbody.mass = 1;
  70. rigidbody.angularDamping = 0.05f;
  71. // 加载box collider
  72. BoxCollider boxCollider = toy.AddComponent<BoxCollider>();
  73. boxCollider.isTrigger = false;
  74. boxCollider.center = Vector3.zero;
  75. boxCollider.size = new Vector3(0.4f, 0.4f, 0.04f);
  76. }
  77. public void Throw(InputAction.CallbackContext context)
  78. {
  79. //Debug.Log(context.control.device);
  80. if (PlayData.gameStatus == PlayData.GameStatus.inProgress) { return; }
  81. // 按下鼠标
  82. if (context.phase == InputActionPhase.Started)
  83. {
  84. // 动态配置Dog V Cam。不能放在Start()里面,因为狗是动态加载的。Start时候狗还没有加载。
  85. dog = GameObject.Find("dog");
  86. CamDog.m_Follow = dog.transform;
  87. CamDog.m_LookAt = dog.transform;
  88. Ray ray = Camera.main.ScreenPointToRay(Pointer.current.position.ReadValue());
  89. if (Physics.Raycast(ray, out RaycastHit hit))
  90. {
  91. Debug.Log($"Clicked on: {hit.collider.gameObject.tag}");
  92. // 射线检测起始点击是否在飞盘上
  93. if (hit.collider.gameObject.name == "toy")
  94. {
  95. PlayData.isMouseStartOnTarget = true;
  96. mouseStartPosition = Pointer.current.position.ReadValue();
  97. // 如果已经按下鼠标后,就不能切换狗了
  98. var dogSelector = GameObject.Find("Dog Selector");
  99. if (dogSelector != null) { dogSelector.SetActive(false); }
  100. }
  101. }
  102. }
  103. // 松开鼠标
  104. if (context.phase == InputActionPhase.Canceled && PlayData.isMouseStartOnTarget)
  105. {
  106. mouseEndPosition = Pointer.current.position.ReadValue();
  107. Debug.Log("Drag end time at: " + context.duration);
  108. throwTime = Convert.ToSingle(context.duration);
  109. float screenWidth = Screen.width;
  110. float screenHeight = Screen.height;
  111. float aspectRatio = screenWidth / screenHeight;
  112. Debug.Log("屏幕宽高比: " + aspectRatio);
  113. xForce = (mouseEndPosition.x - mouseStartPosition.x) / throwTime / forceAdjust * aspectRatio;
  114. yForce = (mouseEndPosition.y - mouseStartPosition.y) / throwTime / forceAdjust * aspectRatio;
  115. Debug.Log("xForce is: " + xForce);
  116. Debug.Log("yForce is: " + yForce);
  117. if (yForce > 1 && yForce > xForce * 0.5f) // 确保是向前飞出飞盘
  118. {
  119. AddThrowForce();
  120. }
  121. // 重置值
  122. mouseStartPosition = Vector2.zero;
  123. mouseEndPosition = Vector2.zero;
  124. }
  125. }
  126. // 飞碟飞出后,给飞碟添加一个力
  127. public void AddThrowForce()
  128. {
  129. if (PlayData.gameStatus == PlayData.GameStatus.notStart)
  130. {
  131. float verticalForce = 6; // 定义垂直方向力量
  132. var toy = GameObject.Find("toy");
  133. PlayData.throwStartPoision = toy.transform.position; // 上报飞盘其实位置
  134. PlayData.gameStatus = PlayData.GameStatus.inProgress; // 游戏状态设置为进行中
  135. Rigidbody rb = toy.GetComponent<Rigidbody>();
  136. Vector3 force = new Vector3(xForce, verticalForce, yForce);
  137. rb.isKinematic = false;
  138. rb.AddForce(force, ForceMode.Impulse);
  139. PlayData.gameStatus = PlayData.GameStatus.inProgress;
  140. }
  141. else
  142. {
  143. return;
  144. }
  145. }
  146. // 飞碟飞出后,狗追逐飞碟
  147. public void DogCatchToy()
  148. {
  149. // 调整摄像机
  150. CamPlayer.Priority = 0;
  151. CamDog.Priority = 10;
  152. var dog = GameObject.Find("dog");
  153. var toy = GameObject.Find("toy");
  154. DogProperty dogProperty = UserProperty.dogs[0]; // 读取狗的数据
  155. //float turnSpeed = 90.0f; // 每秒最多旋转角度
  156. //dog.transform.LookAt(fisbee.transform.position);
  157. if (toy.transform.position.y < 0.43 && PlayData.gameStatus == PlayData.GameStatus.inProgress)
  158. {
  159. PlayData.gameStatus = PlayData.GameStatus.finishFail; // 游戏状态设置为失败。狗依然在追逐飞盘,但是飞盘已经落地
  160. Animator animator = dog.GetComponent<Animator>();
  161. animator.SetBool("runState", false);
  162. Debug.Log("飞盘落地了");
  163. }
  164. else if (dog != null && toy != null)
  165. {
  166. // 计算目标方向
  167. Vector3 direction = toy.transform.position - dog.transform.position;
  168. direction.y = 0; // 忽略垂直方向的偏移
  169. var targetPosition = toy.transform.position;
  170. targetPosition.y = 0.4f;
  171. Quaternion targetRotation = new();
  172. // 创建目标旋转
  173. if (direction != Vector3.zero)
  174. {
  175. targetRotation = Quaternion.LookRotation(direction);
  176. }
  177. // 直接转向
  178. dog.transform.LookAt(targetPosition);
  179. // 平滑旋转到目标方向
  180. //dog.transform.rotation = Quaternion.RotateTowards(dog.transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
  181. float dogSpeed = (100 + dogProperty.runSpeed) / 10; // 狗向飞盘移动
  182. dog.transform.position = Vector3.MoveTowards(dog.transform.position, targetPosition, dogSpeed * Time.deltaTime);
  183. // 狗切换到跑步状态
  184. Animator animator = dog.GetComponent<Animator>();
  185. if (animator.GetBool("runState") != true) { animator.SetBool("runState", true); }
  186. }
  187. else
  188. {
  189. Debug.LogError("Dog or toy object is not assigned!");
  190. }
  191. }
  192. // 初始化 playground UI 的按键语言和功能
  193. public void UI_Initial()
  194. {
  195. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  196. var btnArea = root.Q<VisualElement>("btnArea");
  197. var confirmBtn = btnArea.Q<Button>("confirm");
  198. var playagainBtn = btnArea.Q<Button>("playAgain");
  199. string textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "confirm", EnviromentSetting.languageCode });
  200. confirmBtn.text = textValue;
  201. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "play_again", EnviromentSetting.languageCode });
  202. playagainBtn.text = textValue;
  203. playagainBtn.clicked += () => GameReset();
  204. confirmBtn.clicked += ConfirmBtnClick;
  205. }
  206. // 游戏结束调用显示显示结果UI
  207. public void ShowGameResult()
  208. {
  209. if (PlayData.isResultShowed == false)
  210. {
  211. var playgroundUI = GameObject.Find("UI Placeholder").transform.Find("PlaygroundUI").gameObject;
  212. playgroundUI.SetActive(true);
  213. UI_Initial();
  214. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  215. var gameResult = root.Q<Label>("gameResult");
  216. string textValue;
  217. if (PlayData.gameStatus == PlayData.GameStatus.finishSuccess)
  218. {
  219. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishSuccess", EnviromentSetting.languageCode });
  220. textValue = textValue.Replace("<<distance>>", Math.Round(PlayData.throwDistance(), 2).ToString()); // 保留小数点后2位
  221. gameResult.text = textValue;
  222. }
  223. else if (PlayData.gameStatus == PlayData.GameStatus.finishFail)
  224. {
  225. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishFail", EnviromentSetting.languageCode });
  226. gameResult.text = textValue;
  227. }
  228. else if (PlayData.gameStatus == PlayData.GameStatus.finishOutOfBound)
  229. {
  230. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishOutOfBound", EnviromentSetting.languageCode });
  231. gameResult.text = textValue;
  232. }
  233. // 飞碟游戏成功后,提交成绩
  234. float distance = PlayData.throwDistance();
  235. bool isSuccess = PlayData.gameStatus == PlayData.GameStatus.finishSuccess;
  236. PlayFinishRequest(distance, isSuccess);
  237. }
  238. PlayData.isResultShowed = true;
  239. }
  240. // 游戏重置
  241. void GameReset()
  242. {
  243. var UIPlaceholder = GameObject.Find("UI Placeholder");
  244. var dogSelector = UIPlaceholder.transform.Find("Dog Selector").gameObject;
  245. dogSelector.SetActive(true);
  246. PlayData.Reset();
  247. // 获取当前场景的名称
  248. string currentSceneName = SceneManager.GetActiveScene().name;
  249. // 重新加载当前场景
  250. SceneManager.LoadScene(currentSceneName);
  251. }
  252. // UI 点击确认后,返回到Home界面
  253. void ConfirmBtnClick()
  254. {
  255. //SceneManager.LoadScene("Home");
  256. MaskTransitions.TransitionManager.Instance.LoadLevel("Home");
  257. }
  258. // 提交道具使用和受影响狗的列表
  259. void PlayFinishRequest(float distance, bool isSuccess)
  260. {
  261. Debug.Log("Play Frisbee finish request");
  262. string url = "/api/frisbee/score/";
  263. WWWForm form = new();
  264. string dogId = UserProperty.GetDogIdByIndex(GameData.focusDog);
  265. form.AddField("user_id", UserProperty.userId);
  266. form.AddField("item_id", GameData.playedToy);
  267. form.AddField("dog_id", dogId);
  268. form.AddField("distance", distance.ToString());
  269. form.AddField("is_success", isSuccess ? "true" : "false");
  270. StartCoroutine(WebController.PostRequest(url, form, callback: PlayFrisbeeReqCallback));
  271. }
  272. void PlayFrisbeeReqCallback(string json)
  273. {
  274. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  275. if (data != null && data["status"].ToString() == "success")
  276. {
  277. // 刷新狗的数据
  278. string dogs = data["dogs"].ToString();
  279. UserProperty.RefreshDogInfo(dogs);
  280. }
  281. else
  282. {
  283. Debug.Log(data["message"]);
  284. }
  285. }
  286. }
  287. public static class PlayData
  288. {
  289. public static bool throwHitWall = false; // 飞盘是否撞到空气墙
  290. public static bool throwCatched = false; // 飞盘是否被狗接到
  291. public static bool isResultShowed = false; // 是否显示游戏结果
  292. public static bool isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  293. public static Vector3 throwStartPoision = Vector3.zero;
  294. public static Vector3 throwEndPosition = Vector3.zero;
  295. public enum GameStatus
  296. {
  297. notStart,
  298. inProgress,
  299. finishSuccess,
  300. finishFail, // 玩具丢出,但是狗没有接住
  301. finishOutOfBound // 玩具飞出界
  302. }
  303. public static GameStatus gameStatus = GameStatus.notStart;
  304. //public static string gameStatus = "not start";
  305. public static float throwDistance()
  306. {
  307. if (gameStatus == GameStatus.finishSuccess)
  308. {
  309. Debug.Log("start position is" + throwStartPoision);
  310. Debug.Log("end position is" + throwEndPosition);
  311. return Vector3.Distance(throwEndPosition, throwStartPoision);
  312. }
  313. else { return 0; }
  314. }
  315. public static void Reset()
  316. {
  317. PlayData.throwHitWall = false; // 飞盘是否撞到空气墙
  318. PlayData.throwCatched = false; // 飞盘是否被狗接到
  319. PlayData.isResultShowed = false; // 是否显示游戏结果
  320. PlayData.isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  321. PlayData.throwStartPoision = Vector3.zero;
  322. PlayData.throwEndPosition = Vector3.zero;
  323. PlayData.gameStatus = GameStatus.notStart;
  324. }
  325. }