实现摇杆功能

搭建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);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值