SW 중심대학 OSS GIT 서버 박건태, 이승준, 고기완, 이준호 새로운 배포
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

513 lines
21 KiB

4 years ago
  1. /*
  2. ------------------- Code Monkey -------------------
  3. Thank you for downloading the Code Monkey Utilities
  4. I hope you find them useful in your projects
  5. If you have any questions use the contact form
  6. Cheers!
  7. unitycodemonkey.com
  8. --------------------------------------------------
  9. */
  10. using System;
  11. using System.Collections.Generic;
  12. using UnityEngine;
  13. using UnityEngine.UI;
  14. using UnityEngine.EventSystems;
  15. namespace CodeMonkey.Utils {
  16. /*
  17. * Various assorted utilities functions
  18. * */
  19. public static class UtilsClass {
  20. private static readonly Vector3 Vector3zero = Vector3.zero;
  21. private static readonly Vector3 Vector3one = Vector3.one;
  22. private static readonly Vector3 Vector3yDown = new Vector3(0,-1);
  23. public const int sortingOrderDefault = 5000;
  24. // Get Sorting order to set SpriteRenderer sortingOrder, higher position = lower sortingOrder
  25. public static int GetSortingOrder(Vector3 position, int offset, int baseSortingOrder = sortingOrderDefault) {
  26. return (int)(baseSortingOrder - position.y) + offset;
  27. }
  28. // Get Main Canvas Transform
  29. private static Transform cachedCanvasTransform;
  30. public static Transform GetCanvasTransform() {
  31. if (cachedCanvasTransform == null) {
  32. Canvas canvas = MonoBehaviour.FindObjectOfType<Canvas>();
  33. if (canvas != null) {
  34. cachedCanvasTransform = canvas.transform;
  35. }
  36. }
  37. return cachedCanvasTransform;
  38. }
  39. // Get Default Unity Font, used in text objects if no font given
  40. public static Font GetDefaultFont() {
  41. return Resources.GetBuiltinResource<Font>("Arial.ttf");
  42. }
  43. // Create a Sprite in the World, no parent
  44. public static GameObject CreateWorldSprite(string name, Sprite sprite, Vector3 position, Vector3 localScale, int sortingOrder, Color color) {
  45. return CreateWorldSprite(null, name, sprite, position, localScale, sortingOrder, color);
  46. }
  47. // Create a Sprite in the World
  48. public static GameObject CreateWorldSprite(Transform parent, string name, Sprite sprite, Vector3 localPosition, Vector3 localScale, int sortingOrder, Color color) {
  49. GameObject gameObject = new GameObject(name, typeof(SpriteRenderer));
  50. Transform transform = gameObject.transform;
  51. transform.SetParent(parent, false);
  52. transform.localPosition = localPosition;
  53. transform.localScale = localScale;
  54. SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
  55. spriteRenderer.sprite = sprite;
  56. spriteRenderer.sortingOrder = sortingOrder;
  57. spriteRenderer.color = color;
  58. return gameObject;
  59. }
  60. // Create a Sprite in the World with Button_Sprite, no parent
  61. public static Button_Sprite CreateWorldSpriteButton(string name, Sprite sprite, Vector3 localPosition, Vector3 localScale, int sortingOrder, Color color) {
  62. return CreateWorldSpriteButton(null, name, sprite, localPosition, localScale, sortingOrder, color);
  63. }
  64. // Create a Sprite in the World with Button_Sprite
  65. public static Button_Sprite CreateWorldSpriteButton(Transform parent, string name, Sprite sprite, Vector3 localPosition, Vector3 localScale, int sortingOrder, Color color) {
  66. GameObject gameObject = CreateWorldSprite(parent, name, sprite, localPosition, localScale, sortingOrder, color);
  67. gameObject.AddComponent<BoxCollider2D>();
  68. Button_Sprite buttonSprite = gameObject.AddComponent<Button_Sprite>();
  69. return buttonSprite;
  70. }
  71. // Creates a Text Mesh in the World and constantly updates it
  72. public static FunctionUpdater CreateWorldTextUpdater(Func<string> GetTextFunc, Vector3 localPosition, Transform parent = null) {
  73. TextMesh textMesh = CreateWorldText(GetTextFunc(), parent, localPosition);
  74. return FunctionUpdater.Create(() => {
  75. textMesh.text = GetTextFunc();
  76. return false;
  77. }, "WorldTextUpdater");
  78. }
  79. // Create Text in the World
  80. public static TextMesh CreateWorldText(string text, Transform parent = null, Vector3 localPosition = default(Vector3), int fontSize = 40, Color? color = null, TextAnchor textAnchor = TextAnchor.UpperLeft, TextAlignment textAlignment = TextAlignment.Left, int sortingOrder = sortingOrderDefault) {
  81. if (color == null) color = Color.white;
  82. return CreateWorldText(parent, text, localPosition, fontSize, (Color)color, textAnchor, textAlignment, sortingOrder);
  83. }
  84. // Create Text in the World
  85. public static TextMesh CreateWorldText(Transform parent, string text, Vector3 localPosition, int fontSize, Color color, TextAnchor textAnchor, TextAlignment textAlignment, int sortingOrder) {
  86. GameObject gameObject = new GameObject("World_Text", typeof(TextMesh));
  87. Transform transform = gameObject.transform;
  88. transform.SetParent(parent, false);
  89. transform.localPosition = localPosition;
  90. TextMesh textMesh = gameObject.GetComponent<TextMesh>();
  91. textMesh.anchor = textAnchor;
  92. textMesh.alignment = textAlignment;
  93. textMesh.text = text;
  94. textMesh.fontSize = fontSize;
  95. textMesh.color = color;
  96. textMesh.GetComponent<MeshRenderer>().sortingOrder = sortingOrder;
  97. return textMesh;
  98. }
  99. // Create a Text Popup in the World, no parent
  100. public static void CreateWorldTextPopup(string text, Vector3 localPosition) {
  101. CreateWorldTextPopup(null, text, localPosition, 40, Color.white, localPosition + new Vector3(0, 20), 1f);
  102. }
  103. // Create a Text Popup in the World
  104. public static void CreateWorldTextPopup(Transform parent, string text, Vector3 localPosition, int fontSize, Color color, Vector3 finalPopupPosition, float popupTime) {
  105. TextMesh textMesh = CreateWorldText(parent, text, localPosition, fontSize, color, TextAnchor.LowerLeft, TextAlignment.Left, sortingOrderDefault);
  106. Transform transform = textMesh.transform;
  107. Vector3 moveAmount = (finalPopupPosition - localPosition) / popupTime;
  108. FunctionUpdater.Create(delegate () {
  109. transform.position += moveAmount * Time.deltaTime;
  110. popupTime -= Time.deltaTime;
  111. if (popupTime <= 0f) {
  112. UnityEngine.Object.Destroy(transform.gameObject);
  113. return true;
  114. } else {
  115. return false;
  116. }
  117. }, "WorldTextPopup");
  118. }
  119. // Create Text Updater in UI
  120. public static FunctionUpdater CreateUITextUpdater(Func<string> GetTextFunc, Vector2 anchoredPosition) {
  121. Text text = DrawTextUI(GetTextFunc(), anchoredPosition, 20, GetDefaultFont());
  122. return FunctionUpdater.Create(() => {
  123. text.text = GetTextFunc();
  124. return false;
  125. }, "UITextUpdater");
  126. }
  127. // Draw a UI Sprite
  128. public static RectTransform DrawSprite(Color color, Transform parent, Vector2 pos, Vector2 size, string name = null) {
  129. RectTransform rectTransform = DrawSprite(null, color, parent, pos, size, name);
  130. return rectTransform;
  131. }
  132. // Draw a UI Sprite
  133. public static RectTransform DrawSprite(Sprite sprite, Transform parent, Vector2 pos, Vector2 size, string name = null) {
  134. RectTransform rectTransform = DrawSprite(sprite, Color.white, parent, pos, size, name);
  135. return rectTransform;
  136. }
  137. // Draw a UI Sprite
  138. public static RectTransform DrawSprite(Sprite sprite, Color color, Transform parent, Vector2 pos, Vector2 size, string name = null) {
  139. // Setup icon
  140. if (name == null || name == "") name = "Sprite";
  141. GameObject go = new GameObject(name, typeof(RectTransform), typeof(Image));
  142. RectTransform goRectTransform = go.GetComponent<RectTransform>();
  143. goRectTransform.SetParent(parent, false);
  144. goRectTransform.sizeDelta = size;
  145. goRectTransform.anchoredPosition = pos;
  146. Image image = go.GetComponent<Image>();
  147. image.sprite = sprite;
  148. image.color = color;
  149. return goRectTransform;
  150. }
  151. public static Text DrawTextUI(string textString, Vector2 anchoredPosition, int fontSize, Font font) {
  152. return DrawTextUI(textString, GetCanvasTransform(), anchoredPosition, fontSize, font);
  153. }
  154. public static Text DrawTextUI(string textString, Transform parent, Vector2 anchoredPosition, int fontSize, Font font) {
  155. GameObject textGo = new GameObject("Text", typeof(RectTransform), typeof(Text));
  156. textGo.transform.SetParent(parent, false);
  157. Transform textGoTrans = textGo.transform;
  158. textGoTrans.SetParent(parent, false);
  159. textGoTrans.localPosition = Vector3zero;
  160. textGoTrans.localScale = Vector3one;
  161. RectTransform textGoRectTransform = textGo.GetComponent<RectTransform>();
  162. textGoRectTransform.sizeDelta = new Vector2(0,0);
  163. textGoRectTransform.anchoredPosition = anchoredPosition;
  164. Text text = textGo.GetComponent<Text>();
  165. text.text = textString;
  166. text.verticalOverflow = VerticalWrapMode.Overflow;
  167. text.horizontalOverflow = HorizontalWrapMode.Overflow;
  168. text.alignment = TextAnchor.MiddleLeft;
  169. if (font == null) font = GetDefaultFont();
  170. text.font = font;
  171. text.fontSize = fontSize;
  172. return text;
  173. }
  174. // Parse a float, return default if failed
  175. public static float Parse_Float(string txt, float _default) {
  176. float f;
  177. if (!float.TryParse(txt, out f)) {
  178. f = _default;
  179. }
  180. return f;
  181. }
  182. // Parse a int, return default if failed
  183. public static int Parse_Int(string txt, int _default) {
  184. int i;
  185. if (!int.TryParse(txt, out i)) {
  186. i = _default;
  187. }
  188. return i;
  189. }
  190. public static int Parse_Int(string txt) {
  191. return Parse_Int(txt, -1);
  192. }
  193. // Get Mouse Position in World with Z = 0f
  194. public static Vector3 GetMouseWorldPosition() {
  195. Vector3 vec = GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
  196. vec.z = 0f;
  197. return vec;
  198. }
  199. public static Vector3 GetMouseWorldPositionWithZ() {
  200. return GetMouseWorldPositionWithZ(Input.mousePosition, Camera.main);
  201. }
  202. public static Vector3 GetMouseWorldPositionWithZ(Camera worldCamera) {
  203. return GetMouseWorldPositionWithZ(Input.mousePosition, worldCamera);
  204. }
  205. public static Vector3 GetMouseWorldPositionWithZ(Vector3 screenPosition, Camera worldCamera) {
  206. Vector3 worldPosition = worldCamera.ScreenToWorldPoint(screenPosition);
  207. return worldPosition;
  208. }
  209. // Is Mouse over a UI Element? Used for ignoring World clicks through UI
  210. public static bool IsPointerOverUI() {
  211. if (EventSystem.current.IsPointerOverGameObject()) {
  212. return true;
  213. } else {
  214. PointerEventData pe = new PointerEventData(EventSystem.current);
  215. pe.position = Input.mousePosition;
  216. List<RaycastResult> hits = new List<RaycastResult>();
  217. EventSystem.current.RaycastAll( pe, hits );
  218. return hits.Count > 0;
  219. }
  220. }
  221. // Returns 00-FF, value 0->255
  222. public static string Dec_to_Hex(int value) {
  223. return value.ToString("X2");
  224. }
  225. // Returns 0-255
  226. public static int Hex_to_Dec(string hex) {
  227. return Convert.ToInt32(hex, 16);
  228. }
  229. // Returns a hex string based on a number between 0->1
  230. public static string Dec01_to_Hex(float value) {
  231. return Dec_to_Hex((int)Mathf.Round(value*255f));
  232. }
  233. // Returns a float between 0->1
  234. public static float Hex_to_Dec01(string hex) {
  235. return Hex_to_Dec(hex)/255f;
  236. }
  237. // Get Hex Color FF00FF
  238. public static string GetStringFromColor(Color color) {
  239. string red = Dec01_to_Hex(color.r);
  240. string green = Dec01_to_Hex(color.g);
  241. string blue = Dec01_to_Hex(color.b);
  242. return red+green+blue;
  243. }
  244. // Get Hex Color FF00FFAA
  245. public static string GetStringFromColorWithAlpha(Color color) {
  246. string alpha = Dec01_to_Hex(color.a);
  247. return GetStringFromColor(color)+alpha;
  248. }
  249. // Sets out values to Hex String 'FF'
  250. public static void GetStringFromColor(Color color, out string red, out string green, out string blue, out string alpha) {
  251. red = Dec01_to_Hex(color.r);
  252. green = Dec01_to_Hex(color.g);
  253. blue = Dec01_to_Hex(color.b);
  254. alpha = Dec01_to_Hex(color.a);
  255. }
  256. // Get Hex Color FF00FF
  257. public static string GetStringFromColor(float r, float g, float b) {
  258. string red = Dec01_to_Hex(r);
  259. string green = Dec01_to_Hex(g);
  260. string blue = Dec01_to_Hex(b);
  261. return red+green+blue;
  262. }
  263. // Get Hex Color FF00FFAA
  264. public static string GetStringFromColor(float r, float g, float b, float a) {
  265. string alpha = Dec01_to_Hex(a);
  266. return GetStringFromColor(r,g,b)+alpha;
  267. }
  268. // Get Color from Hex string FF00FFAA
  269. public static Color GetColorFromString(string color) {
  270. float red = Hex_to_Dec01(color.Substring(0,2));
  271. float green = Hex_to_Dec01(color.Substring(2,2));
  272. float blue = Hex_to_Dec01(color.Substring(4,2));
  273. float alpha = 1f;
  274. if (color.Length >= 8) {
  275. // Color string contains alpha
  276. alpha = Hex_to_Dec01(color.Substring(6,2));
  277. }
  278. return new Color(red, green, blue, alpha);
  279. }
  280. // Generate random normalized direction
  281. public static Vector3 GetRandomDir() {
  282. return new Vector3(UnityEngine.Random.Range(-1f,1f), UnityEngine.Random.Range(-1f,1f)).normalized;
  283. }
  284. public static Vector3 GetVectorFromAngle(int angle) {
  285. // angle = 0 -> 360
  286. float angleRad = angle * (Mathf.PI/180f);
  287. return new Vector3(Mathf.Cos(angleRad), Mathf.Sin(angleRad));
  288. }
  289. public static float GetAngleFromVectorFloat(Vector3 dir) {
  290. dir = dir.normalized;
  291. float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
  292. if (n < 0) n += 360;
  293. return n;
  294. }
  295. public static int GetAngleFromVector(Vector3 dir) {
  296. dir = dir.normalized;
  297. float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
  298. if (n < 0) n += 360;
  299. int angle = Mathf.RoundToInt(n);
  300. return angle;
  301. }
  302. public static int GetAngleFromVector180(Vector3 dir) {
  303. dir = dir.normalized;
  304. float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
  305. int angle = Mathf.RoundToInt(n);
  306. return angle;
  307. }
  308. public static Vector3 ApplyRotationToVector(Vector3 vec, Vector3 vecRotation) {
  309. return ApplyRotationToVector(vec, GetAngleFromVectorFloat(vecRotation));
  310. }
  311. public static Vector3 ApplyRotationToVector(Vector3 vec, float angle) {
  312. return Quaternion.Euler(0,0,angle) * vec;
  313. }
  314. public static FunctionUpdater CreateMouseDraggingAction(Action<Vector3> onMouseDragging) {
  315. return CreateMouseDraggingAction(0, onMouseDragging);
  316. }
  317. public static FunctionUpdater CreateMouseDraggingAction(int mouseButton, Action<Vector3> onMouseDragging) {
  318. bool dragging = false;
  319. return FunctionUpdater.Create(() => {
  320. if (Input.GetMouseButtonDown(mouseButton)) {
  321. dragging = true;
  322. }
  323. if (Input.GetMouseButtonUp(mouseButton)) {
  324. dragging = false;
  325. }
  326. if (dragging) {
  327. onMouseDragging(UtilsClass.GetMouseWorldPosition());
  328. }
  329. return false;
  330. });
  331. }
  332. public static FunctionUpdater CreateMouseClickFromToAction(Action<Vector3, Vector3> onMouseClickFromTo, Action<Vector3, Vector3> onWaitingForToPosition) {
  333. return CreateMouseClickFromToAction(0, 1, onMouseClickFromTo, onWaitingForToPosition);
  334. }
  335. public static FunctionUpdater CreateMouseClickFromToAction(int mouseButton, int cancelMouseButton, Action<Vector3, Vector3> onMouseClickFromTo, Action<Vector3, Vector3> onWaitingForToPosition) {
  336. int state = 0;
  337. Vector3 from = Vector3.zero;
  338. return FunctionUpdater.Create(() => {
  339. if (state == 1) {
  340. if (onWaitingForToPosition != null) onWaitingForToPosition(from, UtilsClass.GetMouseWorldPosition());
  341. }
  342. if (state == 1 && Input.GetMouseButtonDown(cancelMouseButton)) {
  343. // Cancel
  344. state = 0;
  345. }
  346. if (Input.GetMouseButtonDown(mouseButton) && !UtilsClass.IsPointerOverUI()) {
  347. if (state == 0) {
  348. state = 1;
  349. from = UtilsClass.GetMouseWorldPosition();
  350. } else {
  351. state = 0;
  352. onMouseClickFromTo(from, UtilsClass.GetMouseWorldPosition());
  353. }
  354. }
  355. return false;
  356. });
  357. }
  358. public static FunctionUpdater CreateMouseClickAction(Action<Vector3> onMouseClick) {
  359. return CreateMouseClickAction(0, onMouseClick);
  360. }
  361. public static FunctionUpdater CreateMouseClickAction(int mouseButton, Action<Vector3> onMouseClick) {
  362. return FunctionUpdater.Create(() => {
  363. if (Input.GetMouseButtonDown(mouseButton)) {
  364. onMouseClick(GetWorldPositionFromUI());
  365. }
  366. return false;
  367. });
  368. }
  369. public static FunctionUpdater CreateKeyCodeAction(KeyCode keyCode, Action onKeyDown) {
  370. return FunctionUpdater.Create(() => {
  371. if (Input.GetKeyDown(keyCode)) {
  372. onKeyDown();
  373. }
  374. return false;
  375. });
  376. }
  377. // Get UI Position from World Position
  378. public static Vector2 GetWorldUIPosition(Vector3 worldPosition, Transform parent, Camera uiCamera, Camera worldCamera) {
  379. Vector3 screenPosition = worldCamera.WorldToScreenPoint(worldPosition);
  380. Vector3 uiCameraWorldPosition = uiCamera.ScreenToWorldPoint(screenPosition);
  381. Vector3 localPos = parent.InverseTransformPoint(uiCameraWorldPosition);
  382. return new Vector2(localPos.x, localPos.y);
  383. }
  384. public static Vector3 GetWorldPositionFromUIZeroZ() {
  385. Vector3 vec = GetWorldPositionFromUI(Input.mousePosition, Camera.main);
  386. vec.z = 0f;
  387. return vec;
  388. }
  389. // Get World Position from UI Position
  390. public static Vector3 GetWorldPositionFromUI() {
  391. return GetWorldPositionFromUI(Input.mousePosition, Camera.main);
  392. }
  393. public static Vector3 GetWorldPositionFromUI(Camera worldCamera) {
  394. return GetWorldPositionFromUI(Input.mousePosition, worldCamera);
  395. }
  396. public static Vector3 GetWorldPositionFromUI(Vector3 screenPosition, Camera worldCamera) {
  397. Vector3 worldPosition = worldCamera.ScreenToWorldPoint(screenPosition);
  398. return worldPosition;
  399. }
  400. public static Vector3 GetWorldPositionFromUI_Perspective() {
  401. return GetWorldPositionFromUI_Perspective(Input.mousePosition, Camera.main);
  402. }
  403. public static Vector3 GetWorldPositionFromUI_Perspective(Camera worldCamera) {
  404. return GetWorldPositionFromUI_Perspective(Input.mousePosition, worldCamera);
  405. }
  406. public static Vector3 GetWorldPositionFromUI_Perspective(Vector3 screenPosition, Camera worldCamera) {
  407. Ray ray = worldCamera.ScreenPointToRay(screenPosition);
  408. Plane xy = new Plane(Vector3.forward, new Vector3(0, 0, 0f));
  409. float distance;
  410. xy.Raycast(ray, out distance);
  411. return ray.GetPoint(distance);
  412. }
  413. // Screen Shake
  414. public static void ShakeCamera(float intensity, float timer) {
  415. Vector3 lastCameraMovement = Vector3.zero;
  416. FunctionUpdater.Create(delegate () {
  417. timer -= Time.unscaledDeltaTime;
  418. Vector3 randomMovement = new Vector3(UnityEngine.Random.Range(-1f, 1f), UnityEngine.Random.Range(-1f, 1f)).normalized * intensity;
  419. Camera.main.transform.position = Camera.main.transform.position - lastCameraMovement + randomMovement;
  420. lastCameraMovement = randomMovement;
  421. return timer <= 0f;
  422. }, "CAMERA_SHAKE");
  423. }
  424. }
  425. }