Unity物体跟随鼠标拖动

using UnityEngine;
using UnityEngine.EventSystems;

public class Drag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public Transform targetTransform;

    public Camera targetCamera;

    void Awake()
    {
        if (targetTransform == null)
            targetTransform = transform;

        if (targetCamera == null)
            targetCamera = Camera.main;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {

    }

    public void OnDrag(PointerEventData eventData)
    {
        var z = Camera.main.WorldToScreenPoint(targetTransform.position).z;

        Vector3 screenPoint = eventData.position;
        screenPoint.z = z;

        targetTransform.position = targetCamera.ScreenToWorldPoint(screenPoint);
    }

    public void OnEndDrag(PointerEventData eventData)
    {

    }
}

你可能感兴趣的:(Unity物体跟随鼠标拖动)