Search code examples
unity-game-enginepositionmouse

Unity mouse position to world position but just the Y pos


Hello I am making a small game in the Unity game engine and now I cant get it done just to get the y position of my mouse to be converted to the world y position. Any ideas to solve this?(Programming in c#)


Solution

  • Keep in mind that the mouse position is a 2D point, but you are projecting into a 3D world. As such, the Y coordinate of the mouse depends on the Z coordinate of the position in the world. Or in other words, the height will be different depending on the depth of the point in world space. If you want to get the position at a certain depth you can just do:

    Vector3 mousePos = Input.mousePosition;
    mousePos.z = <depth>;
    float y = Camera.main.ScreenToWorldPoint(mousePos).y;
    

    Or you can project a Ray into the world and use the position of the first thing it hits as the depth to sample at:

    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit))
    {
        float y = hit.point.y;
    }
    

    Note that this approach assumes the Ray will hit something.