unity 鼠标拖带

Posted 81192

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity 鼠标拖带相关的知识,希望对你有一定的参考价值。

组场景时,经常需要获取鼠标(或者点击)开始结束时讯息(包括开始拖动时的事件以及对应的坐标),unity为我们提供了两个接口来实现相关方法之前在Unity基础命令中也提到过。

在此在重申一下,两个接口对应两个方法,即可以对应开始结束拖动时的事件,数据则为eventData中。

 public void OnBeginDrag(PointerEventData eventData)
public void OnEndDrag(PointerEventData eventData)

 

public class NewMove : MonoBehaviour,IBeginDragHandler,IEndDragHandler {

    private ScrollRect scrollRect;
    public Toggle[] toggleArr;
    //存储特定的位置坐标
    private float[] pageArr=new float[]{0,0.5f,1.0f};
    public void OnBeginDrag(PointerEventData eventData)
    {
       // Debug.Log("Begin:");
       // Debug.Log(eventData.position);
       //获取rect的初始坐标值
        Vector2 pos = scrollRect.normalizedPosition;
        Debug.Log("Begin:"+pos);
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        //Debug.Log("End:");
        //Debug.Log(eventData.position);
        //获取rect的拖动后的坐标值
        Vector2 pos = scrollRect.normalizedPosition;
        Debug.Log("End:"+pos);
        //获取rect拖动后的水平坐标值
        float posX = scrollRect.horizontalNormalizedPosition;
        int index = 0;
        //计算与特定点的偏差
        float offset = Math.Abs(pageArr[index] - posX);
        //与每一个坐标点进行比较,确定应该存在的位置
        //偏差最小的位置即为rect的位置点
        for(int i=0;i<pageArr.Length;i++)
        {
            float newOffset = Math.Abs(pageArr[i] - posX);
            if(newOffset<= offset)
            {
                index = i;
                offset = newOffset;
            }
        }
        scrollRect.horizontalNormalizedPosition = pageArr[index];
        toggleArr[index].isOn = true;
        Debug.Log("End:" + scrollRect.horizontalNormalizedPosition);
    }

 

以上是关于unity 鼠标拖带的主要内容,如果未能解决你的问题,请参考以下文章

unity3d里照相机跟随鼠标左右移动的代码怎么写

Unity3d C# 鼠标点击下物体,物体匀速旋转180°,要看到旋转过程,这个代码怎么写?

Unity 之 代码实现物体跟随鼠标移动

为啥unity3d进去之后没有鼠标?

unity 鼠标点击一个物体后再点击另一个物体

Unity 鼠标个性化