方法一 : 在Update中调用摇杆移动方法
// 范围圈
[HideInInspector]
public Image scopeImag;
// 移动圈
[HideInInspector]
public Image moveImag;
// 获取范围圈和移动的差值
[HideInInspector]
public Vector3 offset;
void Start () {
// 查找范围圈
scopeImag = GameObject.Find("Canvas/ScopeImage").GetComponent<Image>();
// 查找移动圈
moveImag = GameObject.Find("Canvas/ScopeImage/MoveImage").GetComponent<Image>();
}
void Update () {
// 摇杆移动方法
RockerMove();
// 旋转注视
Quaternion qua = Quaternion.LookRotation(new Vector3(offset.normalized.x, 0, offset.normalized.y));
// 人物旋转
transform.rotation = qua;
// 人物移动
transform.Translate(new Vector3(offset.normalized.x,0,offset.normalized.y) * Time.deltaTime * 5,Space.World);
}
/// <summary>
/// 摇杆移动物体
/// </summary>
public void RockerMove() {
// 开启摇杆移动物体协程
StartCoroutine(IeRockerMove());
}
// 限制移动的范围
public int restrict;
/// <summary>
/// 摇杆移动物体协程
/// </summary>
/// <returns></returns>
IEnumerator IeRockerMove() {
while (Input.GetMouseButton(0))
{
// 获取范围圈和移动的差值
offset = Input.mousePosition - scopeImag.transform.position;
// 判断差值是否大于限制范围
if (offset.magnitude > restrict)
{
// 差值大于限制范围,把差值归一化
offset = offset.normalized * restrict;
}
// 给移动圈赋值 = 范围圈的位置 + 差值
moveImag.transform.position = scopeImag.transform.position + offset;
yield return 0;
}
// 移动圈复位 = 范围圈的中心
moveImag.transform.position = scopeImag.transform.position;
// 把差值归0,防止移动圈回归范围圈中心点时,物体还在一直移动
offset = Vector3.zero;
}
方法二:
1.在UI上面添加Event Trigger组件,添加Event Trigger的点击事件
2.场景中必须要有Event System 和Standlone Input Module组件
3.UI上添加Event Trigger组件,场景中要有Event System 和Standlone Input Module组件.三个缺一不可