Unity物体跟随鼠标拖动

作者: 2b75747cf703 | 来源:发表于2017-03-22 11:26 被阅读607次
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物体跟随鼠标拖动

    本文链接:https://www.haomeiwen.com/subject/mnqonttx.html