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

Unity实现物体跟随鼠标移动

程序员文章站 2024-03-16 23:01:34
...

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

public class test1 : MonoBehaviour
{
public InputField input;
RaycastHit hit;//碰撞信息
Ray ray;//发射的射线
Transform dragGameObject; //将要拖动的物体
Transform DragGameObject
{
get { return dragGameObject; }
set
{
dragGameObject = value;

    }
}

Vector3 ModelPartPos = new Vector3();//临时变量,存储点击零件的原始位置
Vector3 targetScreenPoint; //目标对象的屏幕坐标
Vector3 dragPosition, dragEulerAngle;//临时变量,存储点击零件的原始位置和方向
bool isClickCube;

// Update is called once per frame
void Update()
{

    On3DObjectOperation();

}
private void On3DObjectOperation()
{

    if (DragGameObject == null)
    {

        //EventSystem.current.IsPointerOverGameObject  判断鼠标是否点击在UI上
        if (Input.GetMouseButton(0))
        {

            if (CheckGameObject())
            {
                dragPosition = DragGameObject.position;
                dragEulerAngle = DragGameObject.eulerAngles;
            }
        }
    }

    //点击鼠标右键,物体回到原始位置
    if (Input.GetMouseButtonDown(2))
    {
        //这里,同样适用于2D,如果是2D,需要修改状态
        if (DragGameObject != null)
        {
            if (DragGameObject.gameObject.layer == LayerMask.NameToLayer("Cube"))
            {
                ////加载的零件
                //UIEventControl.Single.HiddedStateUI();
                //RemoveCurrentGameObj();
            }
            else
            {
                //部分
                DragGameObject.position = dragPosition;
                DragGameObject.eulerAngles = dragEulerAngle;
                DragGameObject = null;
                isClickCube = false;
            }
        }
    }

    if (isClickCube)
    {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetScreenPoint.z);
        Vector3 curWorldPoint = Camera.main.ScreenToWorldPoint(curScreenPoint);
        DragGameObject.position = curWorldPoint;
    }
}
bool CheckGameObject()
{
    if (DragGameObject == null)
    {

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        //射线碰撞层为canDrag
        if (Physics.Raycast(ray, out hit))
        {

            isClickCube = true;
            DragGameObject = hit.collider.gameObject.transform;//点击到的物体
            ModelPartPos = DragGameObject.position;//存储点击到物体的原始位置
            targetScreenPoint = Camera.main.WorldToScreenPoint(DragGameObject.position);//目标对象的屏幕坐标(将世界坐标转为屏幕坐标)
            return true;
        }
    }

    return false;
}

}