PlayToyController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. FrisbeeRotateController frisbeeRotateController = toy.AddComponent<FrisbeeRotateController>();
  78. }
  79. public void Throw(InputAction.CallbackContext context)
  80. {
  81. //Debug.Log(context.control.device);
  82. if (PlayData.gameStatus == PlayData.GameStatus.inProgress) { return; }
  83. // 按下鼠标
  84. if (context.phase == InputActionPhase.Started)
  85. {
  86. // 动态配置Dog V Cam。不能放在Start()里面,因为狗是动态加载的。Start时候狗还没有加载。
  87. dog = GameObject.Find("dog");
  88. CamDog.m_Follow = dog.transform;
  89. CamDog.m_LookAt = dog.transform;
  90. Ray ray = Camera.main.ScreenPointToRay(Pointer.current.position.ReadValue());
  91. if (Physics.Raycast(ray, out RaycastHit hit))
  92. {
  93. Debug.Log($"Clicked on: {hit.collider.gameObject.tag}");
  94. // 射线检测起始点击是否在飞盘上
  95. if (hit.collider.gameObject.name == "toy")
  96. {
  97. PlayData.isMouseStartOnTarget = true;
  98. mouseStartPosition = Pointer.current.position.ReadValue();
  99. // 如果已经按下鼠标后,就不能切换狗了
  100. var dogSelector = GameObject.Find("Dog Selector");
  101. if (dogSelector != null) { dogSelector.SetActive(false); }
  102. }
  103. }
  104. }
  105. // 松开鼠标
  106. if (context.phase == InputActionPhase.Canceled && PlayData.isMouseStartOnTarget)
  107. {
  108. mouseEndPosition = Pointer.current.position.ReadValue();
  109. Debug.Log("Drag end time at: " + context.duration);
  110. throwTime = Convert.ToSingle(context.duration);
  111. float screenWidth = Screen.width;
  112. float screenHeight = Screen.height;
  113. float aspectRatio = screenWidth / screenHeight;
  114. Debug.Log("屏幕宽高比: " + aspectRatio);
  115. xForce = (mouseEndPosition.x - mouseStartPosition.x) / throwTime / forceAdjust * aspectRatio;
  116. yForce = (mouseEndPosition.y - mouseStartPosition.y) / throwTime / forceAdjust * aspectRatio;
  117. Debug.Log("xForce is: " + xForce);
  118. Debug.Log("yForce is: " + yForce);
  119. if (yForce > 1 && yForce > xForce * 0.5f) // 确保是向前飞出飞盘
  120. {
  121. AddThrowForce();
  122. }
  123. // 重置值
  124. mouseStartPosition = Vector2.zero;
  125. mouseEndPosition = Vector2.zero;
  126. }
  127. }
  128. // 飞碟飞出后,给飞碟添加一个力
  129. public void AddThrowForce()
  130. {
  131. if (PlayData.gameStatus == PlayData.GameStatus.notStart)
  132. {
  133. float verticalForce = 6; // 定义垂直方向力量
  134. var toy = GameObject.Find("toy");
  135. PlayData.throwStartPoision = toy.transform.position; // 上报飞盘其实位置
  136. PlayData.gameStatus = PlayData.GameStatus.inProgress; // 游戏状态设置为进行中
  137. Rigidbody rb = toy.GetComponent<Rigidbody>();
  138. Vector3 force = new Vector3(xForce, verticalForce, yForce);
  139. rb.isKinematic = false;
  140. rb.AddForce(force, ForceMode.Impulse);
  141. PlayData.gameStatus = PlayData.GameStatus.inProgress;
  142. // 添加飞盘初始化旋转速度
  143. FrisbeeRotateController frisbeeRotateController = toy.GetComponent<FrisbeeRotateController>();
  144. if (frisbeeRotateController != null)
  145. {
  146. float combinedForce = Mathf.Sqrt(xForce * xForce + yForce * yForce + verticalForce * verticalForce) * 10;
  147. if (yForce < 0)
  148. {
  149. combinedForce = -combinedForce; // 如果yForce小于0,旋转反向
  150. }
  151. Debug.Log("Frisbee rotationSpeed: " + combinedForce);
  152. frisbeeRotateController.rotationSpeed = combinedForce; // 设置飞盘旋转速度
  153. }
  154. else
  155. {
  156. Debug.LogError("FrisbeeRotateController not found on the toy object!");
  157. }
  158. }
  159. else
  160. {
  161. return;
  162. }
  163. }
  164. // 飞碟飞出后,狗追逐飞碟
  165. public void DogCatchToy()
  166. {
  167. // 调整摄像机
  168. CamPlayer.Priority = 0;
  169. CamDog.Priority = 10;
  170. var dog = GameObject.Find("dog");
  171. var toy = GameObject.Find("toy");
  172. DogProperty dogProperty = UserProperty.dogs[0]; // 读取狗的数据
  173. //float turnSpeed = 90.0f; // 每秒最多旋转角度
  174. //dog.transform.LookAt(fisbee.transform.position);
  175. if (toy.transform.position.y < 0.43 && PlayData.gameStatus == PlayData.GameStatus.inProgress)
  176. {
  177. PlayData.gameStatus = PlayData.GameStatus.finishFail; // 游戏状态设置为失败。狗依然在追逐飞盘,但是飞盘已经落地
  178. Animator animator = dog.GetComponent<Animator>();
  179. animator.SetBool("runState", false);
  180. Debug.Log("飞盘落地了");
  181. }
  182. else if (dog != null && toy != null)
  183. {
  184. // 计算目标方向
  185. Vector3 direction = toy.transform.position - dog.transform.position;
  186. direction.y = 0; // 忽略垂直方向的偏移
  187. var targetPosition = toy.transform.position;
  188. targetPosition.y = 0.4f;
  189. Quaternion targetRotation = new();
  190. // 创建目标旋转
  191. if (direction != Vector3.zero)
  192. {
  193. targetRotation = Quaternion.LookRotation(direction);
  194. }
  195. // 直接转向
  196. dog.transform.LookAt(targetPosition);
  197. // 平滑旋转到目标方向
  198. //dog.transform.rotation = Quaternion.RotateTowards(dog.transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
  199. float dogSpeed = (100 + dogProperty.runSpeed) / 10; // 狗向飞盘移动
  200. dog.transform.position = Vector3.MoveTowards(dog.transform.position, targetPosition, dogSpeed * Time.deltaTime);
  201. // 狗切换到跑步状态
  202. Animator animator = dog.GetComponent<Animator>();
  203. if (animator.GetBool("runState") != true) { animator.SetBool("runState", true); }
  204. }
  205. else
  206. {
  207. Debug.LogError("Dog or toy object is not assigned!");
  208. }
  209. }
  210. // 初始化 playground UI 的按键语言和功能
  211. public void UI_Initial()
  212. {
  213. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  214. var btnArea = root.Q<VisualElement>("btnArea");
  215. var confirmBtn = btnArea.Q<Button>("confirm");
  216. var playagainBtn = btnArea.Q<Button>("playAgain");
  217. string textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "confirm", EnviromentSetting.languageCode });
  218. confirmBtn.text = textValue;
  219. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "play_again", EnviromentSetting.languageCode });
  220. playagainBtn.text = textValue;
  221. playagainBtn.clicked += () => GameReset();
  222. confirmBtn.clicked += ConfirmBtnClick;
  223. }
  224. // 游戏结束调用显示显示结果UI
  225. public void ShowGameResult()
  226. {
  227. if (PlayData.isResultShowed == false)
  228. {
  229. var playgroundUI = GameObject.Find("UI Placeholder").transform.Find("PlaygroundUI").gameObject;
  230. playgroundUI.SetActive(true);
  231. UI_Initial();
  232. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  233. var gameResult = root.Q<Label>("gameResult");
  234. string textValue;
  235. if (PlayData.gameStatus == PlayData.GameStatus.finishSuccess)
  236. {
  237. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishSuccess", EnviromentSetting.languageCode });
  238. textValue = textValue.Replace("<<distance>>", Math.Round(PlayData.throwDistance(), 2).ToString()); // 保留小数点后2位
  239. gameResult.text = textValue;
  240. }
  241. else if (PlayData.gameStatus == PlayData.GameStatus.finishFail)
  242. {
  243. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishFail", EnviromentSetting.languageCode });
  244. gameResult.text = textValue;
  245. }
  246. else if (PlayData.gameStatus == PlayData.GameStatus.finishOutOfBound)
  247. {
  248. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishOutOfBound", EnviromentSetting.languageCode });
  249. gameResult.text = textValue;
  250. }
  251. // 飞碟游戏成功后,提交成绩
  252. float distance = PlayData.throwDistance();
  253. bool isSuccess = PlayData.gameStatus == PlayData.GameStatus.finishSuccess;
  254. PlayFinishRequest(distance, isSuccess);
  255. }
  256. PlayData.isResultShowed = true;
  257. }
  258. // 游戏重置
  259. void GameReset()
  260. {
  261. var UIPlaceholder = GameObject.Find("UI Placeholder");
  262. var dogSelector = UIPlaceholder.transform.Find("Dog Selector").gameObject;
  263. dogSelector.SetActive(true);
  264. PlayData.Reset();
  265. // 获取当前场景的名称
  266. string currentSceneName = SceneManager.GetActiveScene().name;
  267. // 重新加载当前场景
  268. SceneManager.LoadScene(currentSceneName);
  269. }
  270. // UI 点击确认后,返回到Home界面
  271. void ConfirmBtnClick()
  272. {
  273. //SceneManager.LoadScene("Home");
  274. MaskTransitions.TransitionManager.Instance.LoadLevel("Home");
  275. }
  276. // 提交道具使用和受影响狗的列表
  277. void PlayFinishRequest(float distance, bool isSuccess)
  278. {
  279. Debug.Log("Play Frisbee finish request");
  280. string url = "/api/frisbee/score/";
  281. WWWForm form = new();
  282. string dogId = UserProperty.GetDogIdByIndex(GameData.focusDog);
  283. form.AddField("user_id", UserProperty.userId);
  284. form.AddField("item_id", GameData.playedToy);
  285. form.AddField("dog_id", dogId);
  286. form.AddField("distance", distance.ToString());
  287. form.AddField("catch", isSuccess ? "true" : "false");
  288. StartCoroutine(WebController.PostRequest(url, form, callback: PlayFrisbeeReqCallback));
  289. }
  290. void PlayFrisbeeReqCallback(string json)
  291. {
  292. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  293. if (data != null && data["status"].ToString() == "success")
  294. {
  295. // 刷新狗的数据
  296. string dogs = data["dogs"].ToString();
  297. UserProperty.RefreshDogInfo(dogs);
  298. // 刷新用户数据
  299. string user = data["user_info"].ToString();
  300. UserProperty.RefreshUserInfo(user);
  301. // 提示金币数量
  302. int coinAward = Convert.ToInt32(data["reward_coins"]);
  303. if (coinAward > 0)
  304. {
  305. MessageBoxController.ShowCoinAward(coinAward);
  306. }
  307. }
  308. else
  309. {
  310. Debug.Log(data["message"]);
  311. }
  312. }
  313. }
  314. public static class PlayData
  315. {
  316. public static bool throwHitWall = false; // 飞盘是否撞到空气墙
  317. public static bool throwCatched = false; // 飞盘是否被狗接到
  318. public static bool isResultShowed = false; // 是否显示游戏结果
  319. public static bool isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  320. public static Vector3 throwStartPoision = Vector3.zero;
  321. public static Vector3 throwEndPosition = Vector3.zero;
  322. public enum GameStatus
  323. {
  324. notStart,
  325. inProgress,
  326. finishSuccess,
  327. finishFail, // 玩具丢出,但是狗没有接住
  328. finishOutOfBound // 玩具飞出界
  329. }
  330. public static GameStatus gameStatus = GameStatus.notStart;
  331. //public static string gameStatus = "not start";
  332. public static float throwDistance()
  333. {
  334. if (gameStatus == GameStatus.finishSuccess)
  335. {
  336. Debug.Log("start position is" + throwStartPoision);
  337. Debug.Log("end position is" + throwEndPosition);
  338. return Vector3.Distance(throwEndPosition, throwStartPoision);
  339. }
  340. else { return 0; }
  341. }
  342. public static void Reset()
  343. {
  344. PlayData.throwHitWall = false; // 飞盘是否撞到空气墙
  345. PlayData.throwCatched = false; // 飞盘是否被狗接到
  346. PlayData.isResultShowed = false; // 是否显示游戏结果
  347. PlayData.isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  348. PlayData.throwStartPoision = Vector3.zero;
  349. PlayData.throwEndPosition = Vector3.zero;
  350. PlayData.gameStatus = GameStatus.notStart;
  351. }
  352. }