搭建UI
创建两个UI->Image
创建一个Cube
具体实现
摇杆模块
using UnityEngine;
using UnityEngine.EventSystems;
//1.给按钮注册拖拽事件,让按钮能够跟随手指移动
//2.限制按钮的移动范围
public class Joy : MonoBehaviour,IDragHandler,IPointerUpHandler,IPointerDownHandler
{
public Transform imageBtn;//移动的按钮
public RectTransform borderTF;//按钮的父物体
private bool homing = false;//按钮是否正在恢复原位
public Vector2 tarDir;//摇杆的方向向量
private bool isOnDrag = false;//是否正在拖拽
public void OnDrag(PointerEventData eventData)
{
Vector2 locPos;
//参数1:父物体的坐标
//参数2:转换的点的位置
//参数3:当前Canvas的相机模式
//参数4:转换后的位置信息
//将屏幕点转换为UI坐标---localPos
RectTransformUtility.ScreenPointToLocalPointInRectangle(borderTF, eventData.position, eventData.enterEventCamera, out locPos);
//让按钮跟随鼠标移动
imageBtn.localPosition = locPos;
//限制按钮的移动范围 ---模长=70
imageBtn.localPosition = Vector2.ClampMagnitude(imageBtn.localPosition, 75);
}
public void OnPointerDown(PointerEventData eventData)
{
homing = false;//按下时禁止按钮恢复原位
isOnDrag = true;
}
public void OnPointerUp(PointerEventData eventData)
{
//imageBtn.localPosition = Vector2.zero;
homing = true;//松手时让按钮恢复原位
isOnDrag = false;
}
void Update()
{
if (homing)
{
//让按钮恢复到原位
imageBtn.localPosition = Vector2.Lerp(imageBtn.localPosition, Vector2.zero, Time.deltaTime * 8);
}
if (isOnDrag)
{
//当正在拖拽时,获取方向信息
tarDir = imageBtn.localPosition.normalized;
}
else{
//松手时 方向归零
tarDir = Vector2.zero;
}
}
}
cube模块
public class JoyTarget : MonoBehaviour
{
Joy joy;
void Start()
{
//拿到Joy脚本组件
joy = FindObjectOfType<Joy>();
}
void Update()
{
if (joy.tarDir.magnitude > 0)
{
//控制物体转向->始终跟摇杆方向保持一致
transform.rotation = Quaternion.LookRotation(new Vector3(joy.tarDir.x, 0, joy.tarDir.y));
//控制物体向前移动
transform.Translate(Vector3.forward * Time.deltaTime * 8);
}
}
}