标签:
去年刚刚结束UGUI,想做个贪吃蛇小游戏~
结果当然是跟大多数程序猿一样,实现了核心操作逻辑,后面就不了了之了。
但是昨天网上看到个跟我这个demo一模一样的帖子,我贪吃蛇的蛇头还被抄袭了,这真是不能忍了,还是把原版放出来好了~
---效果图点这里---
这么朴实的中文+拼音的编程风格恐怕就我好意思用了。
using System; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class JoyPlayerCtrl : MonoBehaviour { public enum AxisOption { Both, // Use both OnlyHorizontal, // Only horizontal OnlyVertical // Only vertical } public JoystickInput mJoystick; public int 距离Max = 100; public AxisOption axesToUse = AxisOption.Both; bool m_UseX; // Toggle for using the x axis bool m_UseY; // Toggle for using the Y axis Vector3 StartPos; Vector3 FirstPos; Image IMGBG; public Image IMGCheck; public static JoyPlayerCtrl Instance; void Awake() { Instance = this; IMGBG = GetComponent<Image>(); m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); mJoystick = new JoystickInput(); mJoystick.距离Max = 距离Max; StartPos = transform.localPosition; OnPointerUp(); } void Update() { if (Input.GetKeyDown(KeyCode.Mouse0)) { OnPointerDown(new Vector2(Input.mousePosition.x, Input.mousePosition.y)); } if (Input.GetKey(KeyCode.Mouse0)) { OnDragDuan(new Vector2(Input.mousePosition.x, Input.mousePosition.y)); } if (Input.GetKeyUp(KeyCode.Mouse0)) { OnPointerUp(); } } /// <summary> /// 首次按下 /// </summary> /// <param name="mousePos"></param> public void OnPointerDown(Vector2 mousePos) { IMGBG.enabled = true; IMGCheck.enabled = true; mJoystick.isUser = true; IMGCheck.transform.localPosition = Vector3.zero; FirstPos = mousePos; transform.localPosition = new Vector3(mousePos.x - Screen.width / 2, mousePos.y - Screen.height / 2, StartPos.z); } /// <summary> /// 弹起 /// </summary> public void OnPointerUp() { IMGBG.enabled = false; IMGCheck.enabled = false; mJoystick.isUser = false; } /// <summary> /// 拖动 /// </summary> /// <param name="DragPos"></param> void OnDragDuan(Vector3 DragPos) { Vector3 方向v3 = (DragPos - FirstPos).normalized; if (方向v3 != Vector3.zero) { mJoystick.方向 = Quaternion.LookRotation(方向v3, new Vector3(0, 0, -1)); mJoystick.距离 = Mathf.Clamp(Vector3.Distance(DragPos, FirstPos), 0, mJoystick.距离Max); IMGCheck.transform.localPosition = mJoystick.方向 * Vector3.forward * mJoystick.距离; } } public class JoystickInput { public bool isUser; public Quaternion 方向; public float 距离; public float 距离Max; public float get力度() { return 距离 / 距离Max; } public Quaternion getY方向() { Quaternion temp = JoyPlayerCtrl.Instance.mJoystick.方向 * Quaternion.Euler(90,0,0); return Quaternion.Euler(0, -temp.eulerAngles.z, 0); } } void OnGUI() { if (mJoystick.isUser) { GUI.Label(new Rect(10, 10, 200, 30), "方向" + mJoystick.方向.eulerAngles.ToString()); GUI.Label(new Rect(10, 50, 200, 30), "距离" + mJoystick.距离); GUI.Label(new Rect(10, 90, 200, 30), "力度" + mJoystick.get力度()); } } }
场景布置结构如下:
标签:
原文地址:http://blog.csdn.net/asd237241291/article/details/51372060