Unity实现物体跟随鼠标移动

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;
}

}

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值