World to Screen Coordinate Transform

• 10-02-2012
synhyborex
World to Screen Coordinate Transform
Regarding the transformation itself, it's not a problem. However, where I continually run into trouble is when i need to preserve the aspect ratio if the screen size changes. In other words, if I have a 640x480 screen, whatever I render there needs to look the same in terms of ratios no matter what the screen size changes to.

I understand that I do not need to mess with how I change my y-coordinates for this preservation (because math), but I can't quite figure out how to do it with the x-coordinates.

Here's the function.

Code:

```float world_to_pixel_x(float height, float width, float x){   //x *= width/height;   float d = (width-1)/2;   float c = d;   //return (c*x+d)*(width/height);   return c*x+d; //adjust for scaling }```
Width is currently 640, height is 480.

As of now, it will translate properly, adjusting the origin to the center of the screen, but if I were to change the numbers on width and height around, the rendered image would be stretched and look terrible.

The two pieces of commented code are two things I've tried, both to no avail. The first one (x *= width/height;) works in the sense that it preserves aspect ratio, but it varies from size to size, since the stretch is determined by the ratio (about 1.333 in this case). The second one works in that the size of the object's shape is constant through any change in the window size, but it is displaced from the origin. Both segfault if there is a significant difference between the width and height (i.e. width = 640, height = 200).

Any help would be appreciated :)
• 10-03-2012
oogabooga
Can you give examples of what you want to do?

E.g., What should the answers be for these?

height=480, width=640, x=100

height=480, width=640, x=200

height=640, width=480, x=100

height=640, width=480, x=200
• 10-03-2012
VirtualAce
If you wish to support any resolution you should work in normalized coordinates. Each object position is specified as a value from 0.0 to 1.0. That way if an object is at 0.5, 0.5 on 640 x 480 or 1600 x 900 it will be in the middle of the screen in both cases. Note that the width and height of the object should also be expressed in normalized values. So if the object is 20% of the width of the screen its width will be 0.20f. I have used this approach in commercial applications to good effect and was able to support layout and rendering of objects in any resolution that the device supported.

As to distortion of objects between 4:3, 16:9 and 16:10 ratios there is no way to account for that. An object or bitmap built for 16:9 will never look correct on 4:3 and vice versa. If it is vector art you can multiply the horizontal and vertical points by coefficients based on the aspect ratio and it should work ok. But for pre-built assets it is usually not possible nor plausible to convert correctly between all aspect ratios.