这是我的old question
这是我的脚本:
[ExecuteInEditMode]
public class TestMouseDragObjectInSceneMonoBehaviour : MonoBehaviour
{
private GameObject _cube;
private GameObject cube
{
get
{
if (!_cube)
{
var c = Resources.Load<GameObject>("Obj/Cube");
_cube = Instantiate(c);
}
return _cube;
}
}
private void OnEnable()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
private void OnSceneGUI(SceneView sceneview)
{
var ev = Event.current;
if (ev.type == EventType.MouseMove)
{
var ray = HandleUtility.GUIPointToWorldRay(ev.mousePosition);
var hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, 100))
{
cube.transform.position = hit.point;
Debug.Log(Vector3.Distance(ev.mousePosition, hit.point));
}
else
{
var ptr = ray.GetPoint(100);
cube.transform.position = ptr;
}
}
}
private void OnDisable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
}
Vector3 GetMousePos(Event ev)
{
return GUIUtility.ScreenToGUIPoint(ev.mousePosition);
}
}
以上代码将导致对象突然变大,如果我的交点是地面点,场景视图中的对象大小应该稳定,我想我没有得到地面点,而是其他交点,如何解决? / p>
答案 0 :(得分:3)
引起问题的原因:射线有时会投射在立方体上。
要修复它,您至少有两个选择:
1)将多维数据集的图层更改为'ignoreRayCast',或将平面的指定图层蒙版传递给Physics.Raycast(...)
2)创建一个Plane来代表您的“地面”,使用其“ Raycast(...)”成员方法代替Physics.Raycast(...)
答案 1 :(得分:0)
感谢@Zhang Qi,我通过确保对象层像“ cube.layer = LayerMask.NameToLayer("Ignore Raycast")
”那样“忽略射线广播”来解决它
以下是我的完整代码:
using UnityEditor;
using UnityEngine;
namespace Draft
{
[ExecuteInEditMode]
public class TestMouseDragObjectInSceneMonoBehaviour : MonoBehaviour
{
private GameObject _cube;
private GameObject cube
{
get
{
if (!_cube)
{
var c = Resources.Load<GameObject>("Obj/Cube");
_cube = Instantiate(c);
}
return _cube;
}
}
private void OnEnable()
{
SceneView.onSceneGUIDelegate += OnSceneGUI;
}
private void OnSceneGUI(SceneView sceneview)
{
var ev = Event.current;
if (ev.type == EventType.MouseMove)
{
cube.layer = LayerMask.NameToLayer("Ignore Raycast");
// Vector2 mousePos = Event.current.mousePosition;
// mousePos.y = sceneview.camera.pixelHeight - mousePos.y;
// var ray = sceneview.camera.ScreenPointToRay(mousePos);
var ray = HandleUtility.GUIPointToWorldRay(ev.mousePosition);
// cube.transform.position = ptr;
var hit = new RaycastHit();
if (Physics.Raycast(ray, out hit, 5))
{
cube.transform.position = hit.point;
// Debug.Log(Vector3.Distance(ev.mousePosition, hit.point));
}
else
{
var ptr = ray.GetPoint(5);
cube.transform.position = ptr;
}
}
}
private void OnDisable()
{
SceneView.onSceneGUIDelegate -= OnSceneGUI;
}
Vector3 GetMousePos(Event ev)
{
return GUIUtility.ScreenToGUIPoint(ev.mousePosition);
}
}
}