团结EditorWindow - 在sceen视图中找到鼠标位置

时间:2019-02-02 12:34:01

标签: c# visual-studio unity3d

我一直在使用Google,并试图找到一个答案。但是我什么也没想出来。

private static void OnSceneGUI(SceneView sceneView)
{
    // var mousePos = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
    // Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
    Ray ray = Camera.current.ScreenPointToRay(Event.current.mousePosition);
    Debug.Log("Screen: " + ray);
}

这是我想出现在,找到鼠标的位置。

It seems that the X is always right, but the Y and Z is following the zoom of the camera, not the mousePos on screen.

我的目标是找到mousePos,然后将playerPos重置为我的鼠标所在的位置。

[MenuItem("MyMenu/DevTools/ResetPlayer #r")]
private static void ResetPlayer()
{
    var player = GameObject.Find("Player");
    Transform playerPos = player.GetComponent<Transform>();
    Vector3 reset = new Vector3(-7, 0, 0);

    playerPos.position = reset;
}

目前,我只想出了如何重设到固定位置。

我在这个编辑器非常新的编码,所以我感谢所有帮助我能! :)

1 个答案:

答案 0 :(得分:1)

好的,所以终于弄清楚了该怎么做! 我只是在这里分享我的结果,以防将来有人被卡住。 :)

static Vector3 resets;
private static void OnSceneGUI(SceneView sceneView)
{
    Vector3 distanceFromCam = new Vector3(Camera.main.transform.position.x, 
                                                Camera.main.transform.position.y, 
                                                    0);
    Plane plane = new Plane(Vector3.forward, distanceFromCam);

    Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
    float enter = 0.0f;

    if (plane.Raycast(ray, out enter))
    {
        //Get the point that is clicked
        resets = ray.GetPoint(enter);
        //Debug.Log("Mouse Pos" + resets);
    }
}

这是按钮和快捷键的快捷键。

[MenuItem("MyMenu/DevTools/ResetPlayer #r")]
private static void ResetPlayer()
{
    var player = GameObject.Find("Player");                                     // Find Player GameObject.
    Transform playerPos = player.GetComponent<Transform>();                     // Get the Transform from PlayerGO and make it to a Transform playerPos.
    //Vector3 resets = new Vector3(-7, 0, 0);                                    // Define the hardcoded position you want to reset the player to.                              

    playerPos.position = resets;                                                // Set playerPos to a hardcoded position.
}