- 知识从上一篇接入
[策略思路]:
1.声明一个isPress Bool 类型记录“手柄”的长按状态,在手柄”按下时isPress设为true,并InvokeRepeating,一个你需要实现的功能方法,手柄”抬起时isPress设为false,并利用isPress状态进行(实现的功能方法)的排错。
2.利用手柄按下与抬起的矢量向量进行位移,并在抬起时复位
3.将摇杆的手柄的背景组件“BackGround”的(宽度/2) 得到手柄的运动半径进行条件限制
[实现代码]:
using UnityEngine;
using UnityEngine.EventSystems;
public class ControlHandle : MonoBehaviour,IPointerUpHandler,IPointerDownHandler{
public GameObject BackGround;
private bool isPress = false;
private Vector3 mStartPostion;
private Vector3 mEndPostion;
private float mWidth;
private void Start()
{
mWidth = BackGround.GetComponent<RectTransform>().rect.width / 2;
}
public void OnPointerDown(PointerEventData eventData)
{
isPress = true;
mStartPostion = Input.mousePosition;
InvokeRepeating("MyFunction", 0, 0.01f);
}
public void OnPointerUp(PointerEventData eventData)
{
isPress = false;
CancelInvoke("MyFunction");
InvokeRepeating("MyFunction2", 0, 0.01f);
}
private void MyFunction()
{
if (isPress)
{
mEndPostion = Input.mousePosition;
Vector3 dirt = mEndPostion - mStartPostion;
Vector3 targetDirt = dirt.normalized * mWidth;
if (dirt.magnitude <= mWidth)
targetDirt = dirt;
transform.localPosition = Vector3.Lerp(transform.localPosition, targetDirt, 0.5f);
}
}
private void MyFunction2() {
transform.localPosition = Vector3.Lerp(transform.localPosition, Vector3.zero, 0.1f);
if (transform.localPosition.magnitude < 0.1f)
CancelInvoke("MyFunction2");
}
}
[实现代码]:
(最简洁版)DOTween版:
using UnityEngine;
using UnityEngine.EventSystems;
using DG.Tweening;
public class ControlHandle : MonoBehaviour,IPointerUpHandler,IPointerDownHandler{
public GameObject BackGround;
private bool isPress = false;
private Vector3 mStartPostion;
private Vector3 mEndPostion;
private float mWidth;
private void Start()
{
mWidth = BackGround.GetComponent<RectTransform>().rect.width / 2;
}
public void OnPointerDown(PointerEventData eventData)
{
isPress = true;
mStartPostion = Input.mousePosition;
InvokeRepeating("MyFunction", 0, 0.01f);
}
public void OnPointerUp(PointerEventData eventData)
{
isPress = false;
CancelInvoke("MyFunction");
transform.DOLocalMove(new Vector3(0, 0, 0), 0.1f);
}
public void MyFunction()
{
if (isPress) {
mEndPostion = Input.mousePosition;
Vector3 dirt = mEndPostion - mStartPostion;
Vector3 targetDirt = dirt.normalized * mWidth;
if (dirt.magnitude <= mWidth)
targetDirt = dirt;
transform.DOLocalMove(targetDirt, 0.1f);
}
}
}