PlayToyController.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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.25f, 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. }
  99. }
  100. // 松开鼠标
  101. if (context.phase == InputActionPhase.Canceled && PlayData.isMouseStartOnTarget)
  102. {
  103. mouseEndPosition = Pointer.current.position.ReadValue();
  104. Debug.Log("Drag end time at: " + context.duration);
  105. throwTime = Convert.ToSingle(context.duration);
  106. float screenWidth = Screen.width;
  107. float screenHeight = Screen.height;
  108. float aspectRatio = screenWidth / screenHeight;
  109. Debug.Log("屏幕宽高比: " + aspectRatio);
  110. xForce = (mouseEndPosition.x - mouseStartPosition.x) / throwTime / forceAdjust * aspectRatio;
  111. yForce = (mouseEndPosition.y - mouseStartPosition.y) / throwTime / forceAdjust * aspectRatio;
  112. Debug.Log("xForce is: " + xForce);
  113. Debug.Log("yForce is: " + yForce);
  114. if (yForce > 1 && yForce > xForce*0.5f) // 确保是向前飞出飞盘
  115. {
  116. AddThrowForce();
  117. }
  118. // 重置值
  119. mouseStartPosition = Vector2.zero;
  120. mouseEndPosition = Vector2.zero;
  121. }
  122. }
  123. // 飞碟飞出后,给飞碟添加一个力
  124. public void AddThrowForce()
  125. {
  126. if (PlayData.gameStatus == PlayData.GameStatus.notStart)
  127. {
  128. float verticalForce = 6; // 定义垂直方向力量
  129. var toy = GameObject.Find("toy");
  130. PlayData.throwStartPoision = toy.transform.position; // 上报飞盘其实位置
  131. PlayData.gameStatus = PlayData.GameStatus.inProgress; // 游戏状态设置为进行中
  132. Rigidbody rb = toy.GetComponent<Rigidbody>();
  133. Vector3 force = new Vector3(xForce, verticalForce, yForce);
  134. rb.isKinematic = false;
  135. rb.AddForce(force, ForceMode.Impulse);
  136. PlayData.gameStatus = PlayData.GameStatus.inProgress;
  137. }
  138. else
  139. {
  140. return;
  141. }
  142. }
  143. // 飞碟飞出后,狗追逐飞碟
  144. public void DogCatchToy()
  145. {
  146. // 调整摄像机
  147. CamPlayer.Priority = 0;
  148. CamDog.Priority = 10;
  149. var dog = GameObject.Find("dog");
  150. var toy = GameObject.Find("toy");
  151. DogProperty dogProperty = UserProperty.dogs[0]; // 读取狗的数据
  152. //float turnSpeed = 90.0f; // 每秒最多旋转角度
  153. //dog.transform.LookAt(fisbee.transform.position);
  154. if (toy.transform.position.y < 0.43 && PlayData.gameStatus == PlayData.GameStatus.inProgress)
  155. {
  156. PlayData.gameStatus = PlayData.GameStatus.finishFail; // 游戏状态设置为失败。狗依然在追逐飞盘,但是飞盘已经落地
  157. Animator animator = dog.GetComponent<Animator>();
  158. animator.SetBool("runState", false);
  159. Debug.Log("飞盘落地了");
  160. }
  161. else if (dog != null && toy != null)
  162. {
  163. // 计算目标方向
  164. Vector3 direction = toy.transform.position - dog.transform.position;
  165. direction.y = 0; // 忽略垂直方向的偏移
  166. var targetPosition = toy.transform.position;
  167. targetPosition.y = 0.4f;
  168. Quaternion targetRotation = new();
  169. // 创建目标旋转
  170. if (direction != Vector3.zero)
  171. {
  172. targetRotation = Quaternion.LookRotation(direction);
  173. }
  174. // 直接转向
  175. dog.transform.LookAt(targetPosition);
  176. // 平滑旋转到目标方向
  177. //dog.transform.rotation = Quaternion.RotateTowards(dog.transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
  178. float dogSpeed = (100 + dogProperty.runSpeed) / 10; // 狗向飞盘移动
  179. dog.transform.position = Vector3.MoveTowards(dog.transform.position, targetPosition, dogSpeed * Time.deltaTime);
  180. // 狗切换到跑步状态
  181. Animator animator = dog.GetComponent<Animator>();
  182. if (animator.GetBool("runState") != true) { animator.SetBool("runState", true); }
  183. }
  184. else
  185. {
  186. Debug.LogError("Dog or toy object is not assigned!");
  187. }
  188. }
  189. // 初始化 playground UI 的按键语言和功能
  190. public void UI_Initial()
  191. {
  192. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  193. var btnArea = root.Q<VisualElement>("btnArea");
  194. var confirmBtn = btnArea.Q<Button>("confirm");
  195. var playagainBtn = btnArea.Q<Button>("playAgain");
  196. string textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "confirm", EnviromentSetting.languageCode });
  197. confirmBtn.text = textValue;
  198. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "button", "play_again", EnviromentSetting.languageCode });
  199. playagainBtn.text = textValue;
  200. playagainBtn.clicked += ()=> GameReset();
  201. confirmBtn.clicked += ConfirmBtnClick;
  202. }
  203. // 游戏结束调用显示显示结果UI
  204. public void ShowGameResult()
  205. {
  206. if (PlayData.isResultShowed == false)
  207. {
  208. var playgroundUI = GameObject.Find("UI Placeholder").transform.Find("PlaygroundUI").gameObject;
  209. playgroundUI.SetActive(true);
  210. UI_Initial();
  211. var root = GameObject.Find("PlaygroundUIDocument").GetComponent<UIDocument>().rootVisualElement;
  212. var gameResult = root.Q<Label>("gameResult");
  213. string textValue;
  214. if (PlayData.gameStatus == PlayData.GameStatus.finishSuccess)
  215. {
  216. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishSuccess", EnviromentSetting.languageCode });
  217. textValue = textValue.Replace("<<distance>>", Math.Round(PlayData.throwDistance(), 2).ToString()); // 保留小数点后2位
  218. gameResult.text = textValue;
  219. }
  220. else if (PlayData.gameStatus == PlayData.GameStatus.finishFail)
  221. {
  222. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishFail", EnviromentSetting.languageCode });
  223. gameResult.text = textValue;
  224. }
  225. else if (PlayData.gameStatus == PlayData.GameStatus.finishOutOfBound)
  226. {
  227. textValue = GameTool.GetValueAtPath(EnviromentSetting.languageData, new string[] { "playgroundUI", "label", "game_result", "finishOutOfBound", EnviromentSetting.languageCode });
  228. gameResult.text = textValue;
  229. }
  230. }
  231. PlayData.isResultShowed = true;
  232. }
  233. // 游戏重置
  234. void GameReset()
  235. {
  236. PlayData.Reset();
  237. // 获取当前场景的名称
  238. string currentSceneName = SceneManager.GetActiveScene().name;
  239. // 重新加载当前场景
  240. SceneManager.LoadScene(currentSceneName);
  241. }
  242. // UI 点击确认后,提交道具使用信息返回到Home界面
  243. void ConfirmBtnClick()
  244. {
  245. PlayFinishRequest();
  246. }
  247. // 提交道具使用和受影响狗的列表
  248. void PlayFinishRequest()
  249. {
  250. Debug.Log("Play Frisbee finish request");
  251. List<string> dogs = new List<string>();
  252. dogs.Add(UserProperty.dogs[GameData.focusDog].d_id);
  253. string dogsJson = JsonConvert.SerializeObject(dogs);
  254. string url = "/api/item/use/";
  255. WWWForm form = new();
  256. form.AddField("user_id", UserProperty.userId);
  257. form.AddField("item_id", GameData.playedToy);
  258. form.AddField("dog_list", dogsJson);
  259. form.AddField("date_time", DateTime.Now.ToString()); // 可选项,以服务器时间为准
  260. StartCoroutine(WebController.PostRequest(url, form, callback: PlayFrisbeeReqCallback));
  261. }
  262. void PlayFrisbeeReqCallback(string json)
  263. {
  264. var data = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
  265. if (data != null && data["status"].ToString() == "success")
  266. {
  267. // TODO 清除然后重新写入用户道具数据
  268. // 清除然后重新写入狗的数据
  269. DogProperty[] dogProperties = JsonConvert.DeserializeObject<DogProperty[]>(data["dogs"].ToString());
  270. UserProperty.dogs.Clear();
  271. foreach (var dog in dogProperties)
  272. {
  273. UserProperty.dogs.Add(dog);
  274. }
  275. SceneManager.LoadScene("Home");
  276. }
  277. else
  278. {
  279. Debug.Log(data["message"]);
  280. }
  281. }
  282. }
  283. public static class PlayData
  284. {
  285. public static bool throwHitWall = false; // 飞盘是否撞到空气墙
  286. public static bool throwCatched = false; // 飞盘是否被狗接到
  287. public static bool isResultShowed = false; // 是否显示游戏结果
  288. public static bool isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  289. public static Vector3 throwStartPoision = Vector3.zero;
  290. public static Vector3 throwEndPosition = Vector3.zero;
  291. public enum GameStatus
  292. {
  293. notStart,
  294. inProgress,
  295. finishSuccess,
  296. finishFail, // 玩具丢出,但是狗没有接住
  297. finishOutOfBound // 玩具飞出界
  298. }
  299. public static GameStatus gameStatus = GameStatus.notStart;
  300. //public static string gameStatus = "not start";
  301. public static float throwDistance()
  302. {
  303. if (gameStatus == GameStatus.finishSuccess) {
  304. Debug.Log("start position is"+throwStartPoision);
  305. Debug.Log("end position is" + throwEndPosition);
  306. return Vector3.Distance(throwEndPosition, throwStartPoision);
  307. }
  308. else { return 0; }
  309. }
  310. public static void Reset()
  311. {
  312. PlayData.throwHitWall = false; // 飞盘是否撞到空气墙
  313. PlayData.throwCatched = false; // 飞盘是否被狗接到
  314. PlayData.isResultShowed = false; // 是否显示游戏结果
  315. PlayData.isMouseStartOnTarget = false; // 是否鼠标滑动开始在允许的目标上
  316. PlayData.throwStartPoision = Vector3.zero;
  317. PlayData.throwEndPosition = Vector3.zero;
  318. PlayData.gameStatus = GameStatus.notStart ;
  319. }
  320. }