Distance between two points, different screen resolutions

I’m using Vector3.Distance to find distance between two points

My base resolution is 1600*2560, the distance works fine, but if I change resolution to 1440x…, or even to 720x… Vector3.Distane returns shorted distance then it is, e.g. wrong number.

What can be the problem? The parent is set to “stretch”, can it cause the problem? It’s a bit weird.

What I noticed that the distance get shortened exactly by times the resolution was shortened. For example, width of 1600 reduced to 720, e.g. ratio 1600/720 = 2.22, and the distance on the resolution 720x… will be shortened by 2.2 ratio. Should it be like that?

Do you call Vector3.Distance for points on screen, or in the game world? The game world should be unaffected by the resolution, as that is merely a ‘window to look through’. However, comparing points on the screen, the distance may be affected by the resolution. So in that case normalize the values first to some internal fake resolution, of say 720p, and then calculate the distance based on that.

If your points within a Canvas and render mode is Screen Space then you can use

as multiplier.

How can I use it? *Canvas.scaleFactor throws an error

You need a reference to the root canvas.
Like
Canvas canvas = transform.root.GetComponent<Canvas>();
or assign it manually in inspector. And then
canvas.scaleFactor

1 Like

Thank you, it works, while it needs slight correction, the distance should be divided by scalerFactor

float distance = Vector2.Distance(anchor1.position, anchor2.position);
float scaleFactor = transform.root.GetComponent<Canvas>().scaleFactor;
float finalOffset = distance / scaleFactor;
viewRect.sizeDelta = new Vector2(viewRect.sizeDelta.x, finalOffset);