unity3D技术分享Unity教程合集

Unity物体跟随鼠标拖动

2017-03-22  本文已影响607人  2b75747cf703
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)
    {

    }
}
上一篇下一篇

猜你喜欢

热点阅读