欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity移动---鼠标控制物体在3D空间移动(地面和非地面)

程序员文章站 2024-03-15 20:12:54
...

我这里脚本挂在了摄像机上:

Unity移动---鼠标控制物体在3D空间移动(地面和非地面)

下面是脚本:

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

public class Test : MonoBehaviour
{

  private Vector3 currentPos;
    private Vector3 lastPos;
    private Vector3 deltaPos;
    private Vector3 tempHitPoint;//物体移动前的位置
    public string layerMask;//移动检测层
    public float Depth_Z;//不在平面上移动的摄像机看到物体位置深度
    //[HideInInspector]
    public GameObject MovingItem;//需要移动的物体

    private void Update()
    {
        ResetLastPos();
        ItemMove();
    }

    public void ItemMove()
    {
        if (MovingItem&&Input.GetMouseButton(0))//开始移动
        {
            MovingItem.layer = LayerMask.NameToLayer("Ignore Raycast");//物体不检测射线,避免挡住鼠标检测移动层
            StartCoroutine(ItemMove(MovingItem));
        }
        if (MovingItem && Input.GetMouseButtonUp(0))//停止移动
        {
            MovingItem.layer = LayerMask.NameToLayer("Default");//物体回到初始层
        }
    }

    public IEnumerator ItemMove(GameObject item)
    {
        Vector3 SpaceScreen = Camera.main.WorldToScreenPoint(Camera.main.transform.position);//屏幕上移动的深度
        while (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (item)
            {              
                currentPos = Input.mousePosition;
                if (lastPos != Vector3.zero)
                {                 
                    deltaPos = currentPos - lastPos;
                }

                lastPos = currentPos;
                Vector3 itemScreenPos = Camera.main.WorldToScreenPoint(item.transform.position);
                tempHitPoint = item.transform.position;//物体被鼠标移动前的位置
                ray = Camera.main.ScreenPointToRay(itemScreenPos + deltaPos);
            }
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, Mathf.Infinity, LayerMask.GetMask(layerMask)))
            {
                if (Vector3.Distance(tempHitPoint, hit.point) > 0.001f)//鼠标是否在拖动物体移动(拒绝鼠标按下不松不移动可是物体还颤抖)
                {
                    item.transform.position = hit.point;
                }
            }
            else
            {
                Vector3 MousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, SpaceScreen.z + Depth_Z);
                Vector3 TargetPos = Camera.main.ScreenToWorldPoint(MousePos);
                item.transform.position = TargetPos;              
            }

            yield return new WaitForFixedUpdate();
        }
    }

    /// <summary>
    /// 重置
    /// </summary>
    public void ResetLastPos()
    {
        if (Input.GetMouseButtonUp(0))
        {
            lastPos = Vector3.zero;
        }
    }
}

看下效果:

Unity移动---鼠标控制物体在3D空间移动(地面和非地面)

 

相关标签: 移动