Mouse position in World Space Canvas

Mouse position in World Space Canvas

I’m working on a project that has a map with a tooltip that appears when the user hovers over certain elements.

I had no problems implementing this when using a Canvas with a Screen Space Render Mode. Basically, we can assign the Input.mousePosition coordinates directly to the tooltip position.

tooltip.transform.position = Input.mousePosition;

Or, if we want to use the localPosition, it’s a matter of converting the coordinates into the tooltip local space using the Transform.InverseTransformPoint method.

tooltip.transform.localPosition = transform.InverseTransformPoint(Input.mousePosition);

So far so good.

The problem was that I also needed this map to work in a Canvas with a World Space Render Mode. When using this new Canvas, the mouse coordinates just don’t match. It took me a while to find out to convert them into canvas space.

But, it happens to be easy, since Unity already gives us the following methods that do this:

So here is a final method that I used to get the mouse coordinates:

private Vector3 GetMouseCoordsInCanvas(Camera camera, bool worldCanvas)
{
    if (!worldCanvas) { return Input.mousePosition; }

    // If the canvas render mode is in World Space,
    // We need to convert the mouse position into this rect coords.
    RectTransformUtility.ScreenPointToWorldPointInRectangle(
        transform as RectTransform,
        Input.mousePosition,
        camera,
        out Vector3 mousePosition);
    return mousePosition;
}

If you want to see a working example of this, please check the example CanvasTooltip in my unity-examples repo.