- Home /
How do you account for Canvas Scaler match width or height mode set to 0.5 when trying to get the mouse click coordinates in canvas space?
Hi, Short description My image doesn't go where I click. Here's a video: https://youtu.be/u-xWNVt2LJM
Detailed description I am trying to put a small white image in the position the mouse clicks. In the following setup:
Setup Canvas - Render Mode: ScreenSpace - Overlay Pixel perfect ticked Canvas Scaler - UI Scale Mode: Scale Width or Height Reference resolution: 1920x1080 Screen Match Mode: Match Width Or Height Match: 0.5 Reference Pixels Per Unit: 100
I have an image attached to the canvas as child, anchored to the bottom left.
I have the following method I use to change Input.mousePosition to canvas space position that I apply to my image.
Vector2 UnscalePosition(Vector2 vec) { Vector2 referenceResolution = canvasScaler.referenceResolution; Vector2 currentResolution = new Vector2(Screen.width, Screen.height); float widthRatio = currentResolution.x / referenceResolution.x; float heightRatio = currentResolution.y / referenceResolution.y; float ratio = Mathf.Lerp(heightRatio, widthRatio, canvasScaler.matchWidthOrHeight); return vec / ratio; }
...
Vector2 startPos = UnscalePosition(Input.mousePosition);
mousePosImg.anchoredPosition = startPos;
It places the image correctly where I click when the aspect ratio is 16:10 or 16:9 (very close to the reference resolution), but it doesn't when the height is very large and the width is very small (i.e. 300x900). Unity has a strange explanation to what happens when matchWidthOrHeight is 0.5: https://docs.unity3d.com/2018.1/Documentation/ScriptReference/UI.CanvasScaler-matchWidthOrHeight.html
How do you correctly bring Input.mousePosition in canvas space in this context?
Answer by eexxoo · Apr 15 at 10:17 AM
I only needed to divide Input.mousePosition by canvas.scaleFactor. :)