public enum HeroDistance {
Top,
Bottom,
Left,
Right,
None
}
private GameObject ControlPanel;
//获取自身
private bool isMouseDown;//鼠标是否按下
private bool isFollowMouse;//是否跟随鼠标移动
public GameObject[] ControlDirection=new GameObject[4];
//创建一个GameObject数组,得到4个不同方向的Image
private Canvas canvas;
//获取UGUI的根面板
private RectTransform rectTransform;
//获取UGUI根面板的相对坐标系
private HeroDistance heroDistance = HeroDistance.None;
//初始化方向,为None。
void Awake() {
ControlPanel = this.transform.Find("ControlPanel").gameObject;
canvas = GameObject.Find("Canvas").GetComponent
为检测鼠标的按下与抬起,需要实现两个接口,分别是:IPointerDownHandler,IPointerUpHandler。
为实现接口而创建的两个类:
#region 检测鼠标按下抬起
public void OnPointerDown(PointerEventData eventData) {
isMouseDown = true;
}
public void OnPointerUp(PointerEventData eventData) {
isMouseDown = false;
}
#endregion
其他方法通过获取isMouseDown对象来确定是否按下。
采用itween运动插件
#region 放大控件-Larger(GameObject);缩小控件-Narrow(GameObject)
//当Scale不为1时进行放大
if (go.transform.localScale.x < 1 || go.transform.localScale.y < 1) {
Hashtable parameters = new Hashtable();
//创建Hash表
parameters.Add("scale", new Vector3(1, 1, 1));
//运动的Scale
parameters.Add("time", 0.2f);
//运动时间
parameters.Add("ignoretimescale", true);
//不受time.timescale的控制
iTween.ScaleTo(go,parameters);
}
}
//运动方式与放大刚好相反
private void Narrow(GameObject go){
if (go.transform.localScale.x > 0 || go.transform.localScale.y > 0) {
Hashtable parameters = new Hashtable();
parameters.Add("scale", new Vector3(0, 0, 1));
parameters.Add("time", 0.2f);
parameters.Add("ignoretimescale", true);
iTween.ScaleTo(go, parameters);
}
}
#endregion
#region 跟随鼠标移动- FollowMouse()
private void FollowMouse() {
//如果检测到鼠标按下
if (isMouseDown) {
//如果正在跟随鼠标移动
if (isFollowMouse) {
//通过ReturnMouseDownPos()方法获取鼠标移动到的位置
Vector2 pos = ReturnMouseDownPos();
//设置边界,在边界内
if (pos.x <= 210f && pos.x >= -220f && pos.y <= 300f && pos.y >= -380f)
{
//设置虚拟摇杆的位置
this.transform.localPosition = new Vector3(pos.x, pos.y, this.transform.localPosition.z);
}
else
{
//在边界外
float newX = pos.x, newY = pos.y;
if (pos.x > 210f)
{
newX = 210f;
}
else if(pos.x< -220f)
{
newX = -220f;
}
if (pos.y > 300f)
{
newY = 300f;
}
else if(pos.y< -380f)
{
newY = -380f;
}
this.transform.localPosition = new Vector3(newX, newY, this.transform.localPosition.z);
}
}
}
}
#endregion