欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

unity单指拖拽sprite

程序员文章站 2022-06-28 15:23:13
拖拽物体,注意要添加Collider。原理很简单,就是让目标跟随当前手指位置加上按下时手指和目标间的offset(偏移)。[RequireComponent(typeof(BoxCollider2D))]public class OneFingerDragMove : MonoBehaviour{ public Transform target; //拖拽目标 Vector3 offset; bool isInit; private void Start()...

拖拽物体,注意要添加Collider。原理很简单,就是让目标跟随当前手指位置加上按下时手指与目标间的offset(偏移)。

[RequireComponent(typeof(BoxCollider2D))]
public class OneFingerDragMove : MonoBehaviour
{
    public Transform target; //拖拽目标
    Vector3 offset;
    bool isInit;

    private void Start()
    {
        if (target == null)
            target = transform;
    }
    
    private void FixedUpdate()
    {
    	//防止和多指操作冲突
        if (Input.touchCount != 1)
            isInit = false;
        if (isInit)
            target.position = new Vector3(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).x, Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).y, 0) + offset;
    }

    private void OnMouseDown()
    {
        if (Input.touchCount == 1)
        {
            if (!isInit)
            {
                offset = target.position - new Vector3(Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).x, Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position).y, 0);
                isInit = true;
            }
        }
    }

    private void OnMouseUp()
    {
        isInit = false;
    }
}

本文地址:https://blog.csdn.net/qq_39162826/article/details/108586608