Translating between cartesian and screen coordinates

前端 未结 5 599
清歌不尽
清歌不尽 2020-12-28 18:42

For my game I need functions to translate between two coordinate systems. Well it\'s mainly math question but what I need is the C++ code to do it and a bit of explanation h

5条回答
  •  难免孤独
    2020-12-28 19:23

    The basic algorithm to translate from cartesian coordinates to screen coordinates are

    screenX = cartX + screen_width/2
    screenY = screen_height/2 - cartY
    

    But as you mentioned, cartesian space is infinite, and your screen space is not. This can be solved easily by changing the resolution between screen space and cartesian space. The above algorithm makes 1 unit in cartesian space = 1 unit/pixel in screen space. If you allow for other ratios, you can "zoom" out or in your screen space to cover all of the cartesian space necessary.

    This would change the above algorithm to

    screenX = zoom_factor*cartX + screen_width/2
    screenY = screen_height/2 - zoom_factor*cartY
    

    Now you handle negative (or overly large) screenX and screenY by modifying your zoom factor until all your cartesian coordinates will fit on the screen.

    You could also allow for panning of the coordinate space too, meaning, allowing the center of cartesian space to be off-center of the screen. This could also help in allowing your zoom_factor to stay as tight as possible but also fit data which isn't evenly distributed around the origin of cartesian space.

    This would change the algorithm to

    screenX = zoom_factor*cartX + screen_width/2 + offsetX
    screenY = screen_height/2 - zoom_factor*cartY + offsetY
    

提交回复
热议问题