这篇文章主要为大家详细介绍了unity实现鼠标拖住3D物体,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了unity实现鼠标拖住3D物体的具体代码,供大家参考,具体内容如下
把该脚本直接挂在要拖拽的物体上即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ModelDrages : MonoBehaviour
{
//发射射线的摄像机
private Camera cam;
//射线碰撞的物体
private GameObject go;
//射线碰撞物体的名字
public static string btnName;
private Vector3 screenSpace;
private Vector3 offset;
private bool isDrage = false;
// Use this for initialization
void Start ()
{
cam = Camera.main;
}
// Update is called once per frame
void Update ()
{
//整体初始位置
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
//从摄像机发出到点击坐标的射线
RaycastHit hitInfo;
if (isDrage == false)
{
if(Physics .Raycast (ray,out hitInfo))
{
//划出射线 只有在Scene视图中才能看到
Debug.DrawLine(ray.origin, hitInfo.point);
go = hitInfo.collider.gameObject;
print(btnName);
screenSpace = cam.WorldToScreenPoint(go.transform.position);
offset = go.transform.position - cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z));
//物体的名字
btnName = go.name;
//组件的名字
}
else
{
btnName = null;
}
}
if(Input.GetMouseButton(0))
{
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
Vector3 currentPosition = cam.ScreenToWorldPoint(currentScreenSpace) + offset;
if (btnName != null)
{
go.transform.position = currentPosition;
}
isDrage = true;
}
else
{
isDrage = false;
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程学习网。
织梦狗教程
本文标题为:unity实现鼠标拖住3D物体


基础教程推荐
猜你喜欢
- C# 解析XML和反序列化的示例 2023-04-14
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- Unity shader实现高斯模糊效果 2023-01-16