Hrolgar
Hrolgar

Reputation: 115

Unity EditorWindow - find mouse position in sceen view

I've been googling and trying to find an answer to this. But I've come up with absolutely nothing.

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

This is what I've come up with now, to find the mouse position.

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.

My goal is to find mousePos and then reset playerPos to where my mouse is.

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

For now I've only figured out how to reset to a fixed position.

I am very new in this editor coding, so I appreciate all help I can get! :)

Upvotes: 3

Views: 4904

Answers (1)

Hrolgar
Hrolgar

Reputation: 115

Alright, so finally figured out how to do this! I'll just share my results here in case someone else is stuck on this in the future. :)

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

And here is the shortcut for the button and keybinding.

[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.
}

Upvotes: 4

Related Questions