Translating between cartesian and screen coordinates

前端 未结 5 539
清歌不尽
清歌不尽 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:10

    You will always have the problem that the result could be off the screen -- either as a negative value, or as a value larger than the available screen size.

    Sometimes that won't matter: e.g., if your graphical API accepts negative values and clips your drawing for you. Sometimes it will matter, and for those cases you should have a function that checks if a set of screen coordinates is on the screen.

    You could also write your own clipping functions that try to do something reasonable with coordinates that fall off the screen (such as truncating negative screen coordinates to 0, and coordinates that are too large to the maximum onscreen coordinate). However, keep in mind that "reasonable" depends on what you're trying to do, so it might be best to hold off on defining such functions until you actually need them.


    In any case, as other answers have noted, you can convert between the coordinate systems as:

    cart.x = screen.x - width/2;
    cart.y = height/2 - screen.y;
    

    and

    screen.x = cart.x + width/2;
    screen.y = height/2 - cart.y;
    

提交回复
热议问题