unity 拖动cube 2D屏幕坐标转3D世界坐标

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

public class MouseDrag : MonoBehaviour 
{
    public Transform tfOriginPanel;
    public Transform tfColliderParent;
    public Text txtHorizontal;
    public Text txtVertical;

    Vector3 startPos;
    Vector3 endPos;
    Vector3 offset;

    bool isStop;
    public bool IsStop {
        get { 
            return isStop; 
        } 
        set {
            isStop = value;
            if (!isStop)
            {
                //外部禁止移动放开时,重新设置一下起点
                startPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
            }
            
        }            
    }

    void Start()
    {
        
    }

    private void Update()
    {        
        if (isStop)
            return;

        if (Input.GetMouseButtonDown(0))
        {
            startPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
        }
        if (Input.GetMouseButton(0))
        {
            endPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
            //计算偏移量
            offset = endPos - startPos;
            //让cube按照x,z轴移动
            offset = new Vector3(offset.x, 0, offset.y);
            //让cube移动
            tfOriginPanel.position += offset;
            tfColliderParent.position = tfOriginPanel.position;
            //这一次拖拽的终点变成了下一次拖拽的起点
            startPos = endPos;
        }
    }

    Vector3 MyScreenPointToWorldPoint(Vector3 ScreenPoint, Transform target)
    {
        //得到物体在主相机的某个方向
        Vector3 dir = (target.position - Camera.main.transform.position);
        //计算投影
        Vector3 norVec = Vector3.Project(dir, Camera.main.transform.forward);
        return Camera.main.ViewportToWorldPoint(
        new Vector3(
        ScreenPoint.x / Screen.width,
        ScreenPoint.y / Screen.height,
        norVec.magnitude
        )
        );
    }

    /*
     * 可选,用下面两个事件时,屏蔽掉update里的所有代码,且只能拖动物体本身
    private void OnMouseDown()
    {
        startPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
    }

    private void OnMouseDrag()
    {
        endPos = MyScreenPointToWorldPoint(Input.mousePosition, tfOriginPanel);
        //计算偏移量
        offset = endPos - startPos;
        //让cube按照x,z轴移动
        offset = new Vector3(offset.x, 0, offset.y);
        //让cube移动
        tfOriginPanel.position += offset;
        tfColliderParent.position = tfOriginPanel.position;
        //这一次拖拽的终点变成了下一次拖拽的起点
        startPos = endPos;
    }
    */
}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值