- Home /
Canvas Scaler - scaleFactor
Hey,
I am slightly confused by the nature of canvas.scaleFactor and the Canvas Scaler. I am converting from world to canvas coordinates. Let me show you two code examples:
1. My Initial Attempt
public static Vector2 WorldToCanvasPoint(
this Canvas canvas,
Vector3 worldPosition,
Camera camera = null)
{
if (camera == null)
camera = Camera.main;
var screenPosition = camera.WorldToScreenPoint(worldPosition);
return new Vector2(
(screenPosition.x - (Screen.width * 0.5f)) * canvas.scaleFactor,
(screenPosition.y - (Screen.height * 0.5f)) * canvas.scaleFactor);
}
2. What Worked
public static Vector2 WorldToCanvasPoint(
this Canvas canvas,
Vector3 worldPosition,
Camera camera = null)
{
if (camera == null)
camera = Camera.main;
var screenPosition = camera.WorldToScreenPoint(worldPosition);
var scaler = canvas.GetComponentInParent<CanvasScaler>();
var guiScale = 1.0f;
if (Mathf.Approximately(scaler.matchWidthOrHeight, 0.0f))
guiScale = scaler.referenceResolution.x / (float)Screen.width;
else if (Mathf.Approximately(scaler.matchWidthOrHeight, 1.0f))
guiScale = scaler.referenceResolution.y / (float)Screen.height;
return new Vector2(
(screenPosition.x - (Screen.width * 0.5f)) * guiScale,
(screenPosition.y - (Screen.height * 0.5f)) * guiScale);
}
I would have expected scaleFactor to work in the same manner as the second code snippet above. I would appreciate it if someone is able to explain why the scaleFactor approach does not work and therefore what scaleFactor actually represents and its intended usage.
Also I was originally using a scaler in "expand" screen match mode. In order for this to work I of course need to use the "match width or height" screen match mode which means I do not have a methodology for the "expand" mode (or "shrink"). Again I would be very grateful for an explanation as I cannot find this information described clearly anywhere.
Thanks in advance for your time...
Mark