# 2d coordinates vs x/y screen positioning

I have a 2d top-down view tile map game, that generates random color tiles (water colors) as you move the character. I've been positioning elements on screen using the x/y coords (finding a way to generate new tiles as the player moves was no picnic, but I did it).

My problem is that I want to establish an actual map-level coordinate system, so the player knows where they are. I'd prefer to just count a first "spawn" area as 0,0 and then count from there.

How should I handle doing that? The problem with x/y is that it's relative to the window frame. I have code that detects when the character reaches the edge of the window, and it "freezes" the player, and moves the map instead.

Whatever system I use, I'll need to be able to add code that can check for other nearby entities.

Screen coordinates (SC) should be derived from world coordinates (WC). So if the player is in WC space at 2000, 3000, and the screen is only 640x480, a quick modulo will tell you what coordinate the player is relative to the fixed-screen system you mentioned. So, the SC in the example I have setup is therefore

2000 % 640 = 80
3000 % 480 = 120


So your SC are now 80, 120. This will always generate you a "grid" as broken up by the screen resolution. You can substitute the resolution of your screen with instead the square area of your grid. So if you have 10x15 tiles of 20px by 20px each, then the math is pretty simple.

To have the coordinate system start at 0, 0 where the player is, the screen coordinates would need to be shifted to allow 0, 0 be the center of the screen (instead of the top-left corner, which is what would happen if you used modulo). So feel free to adjust as necessary. Otherwise no other fancy mathematics is necessary. Just remember that modulo in Java does not work in the most convenient way. If you wanted -4 % 5 to return 4, you should do the following

newX = Math.abs(-4) % 5;
if(-4 < 0)
newX *= -1;


This will preserve the modulo rules we want and keep the negative the way it should. I believe otherwise Java just returns 0 for all negative numbers when used with modulo.

• The "character" the user moves around the map is drawn with relative (to the pane) x/y coordinates. The player moves around inside the game screen, but once he reaches around 150px from the window edges, we move the map instead so the guy doesn't go off-screen. My problem is that I want a way to determine "world coordinates" - but have no idea how to determine where 0,0 is. – BotskoNet May 29 '13 at 22:56
• 0, 0 shouldn't have to be defined anywhere. Assume the player is at 0, 0. Whenever the player moves in any direction, that is the new position that character is at relative to 0, 0. Trying to establish a literal origin point shouldn't be necessary so long as everything is relative to some theoretical 0, 0 point. – kurtzbot Jun 2 '13 at 19:04