码迷,mamicode.com
首页 > 编程语言 > 详细

unity 鼠标拖带

时间:2017-07-01 17:15:40      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:相关   位置   code   math   div   一个   public   oat   mon   

组场景时,经常需要获取鼠标(或者点击)开始结束时讯息(包括开始拖动时的事件以及对应的坐标),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 鼠标拖带

标签:相关   位置   code   math   div   一个   public   oat   mon   

原文地址:http://www.cnblogs.com/llstart-new0201/p/7102561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!