using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class Drag : MonoBehaviour
{
    public Camera mainCamera;


    private Vector3 offset2D;
    private Vector3 mDeep;
    Vector3 temp;


    void Start()
    {
        mDeep = mainCamera.WorldToScreenPoint(transform.position);
        print("mDeep:" + mDeep);
        print(transform.position);
    }
    /*
     * Vector3 mDeep= mainCamera.WorldToScreenPoint(target.transform.position)
     * 参数是三维坐标系的参数
     * mDeep 的 x 和 y 对应的是 target 在二维屏幕中的位置,z对应的是 target 与 mainCamera 之间的深度
     * 
     *  Vector3 result = mainCamera.ScreenToWorldPoint(Input.mousePosition + offset2D + new Vector3(0, 0, mDeep.z));
     *  参数的 x 和 y 确定的是 在二维屏幕中的位置,z 代表的是深度
     *  参数 mDeep.z 反映的其实是深度
     * */


    void OnMouseDown()
    {
        //  计算出在屏幕上的误差
        temp = Vector3.zero;
        temp = mainCamera.WorldToScreenPoint(transform.position);
        offset2D = new Vector3(temp.x, temp.y, -0) - Input.mousePosition;
    }


    void OnMouseDrag()
    {
        //  记得加上深度
        transform.position = mainCamera.ScreenToWorldPoint(Input.mousePosition + offset2D + new Vector3(0, 0, mDeep.z));
    }

}

精简一下:

Unity实现拖拽功能

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2021-06-06
  • 2021-12-10
  • 2021-12-23
猜你喜欢
  • 2021-10-05
  • 2021-12-22
  • 2021-06-27
  • 2019-01-05
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案