You have three coordinate systems, all using x,y.
- The grid/block coordinates. Each block is gridsize X gridsize pixels.
- The world coordinates. These are grid coordinates multiplied by
gridsize
.
- The screen coordinates. These are world coordinates minus the camera position
(locationx,locationy)
You're asking how to tidy up the code. I think the way to start is to be use a naming convention so that you know for each x,y variable, which of these three coordinates you're using. For example, you have thex = -(int)locationx+(x*gridsize)
. The x
here is in grid coordinates, locationx
is the camera position in world coordinates, and thex
is in screen coordinates. When you multiply grid coordinates by gridsize
, you get world coordinates, so x*gridsize
in world coordinates. When you subtract the camera position from world coordinates, you get screen coordinates, so thex
is in screen coordinates.
Consider renaming your x, y
to grid_x, grid_y
and your thex, they
to screen_x, screen_y
and your locationx, locationy
to camera_x, camera_y
.
The second piece of code, dealing with cursors, is similarly transforming coordinate systems. The mouse position is in screen coordinates. The first line is finding the world coordinates for the cursor. Since we know that world - camera = screen, it follows from algebra that world = screen + camera. And that's what your code does: it adds the camera (locationx,locationy) to the screen (mouse) to get world coordinates (cursor): cursorx=(int)locationx+(int)GameInput.mousex
The second line there is cursorx=(int)cursorx/gridsize
. What does it do? It's taking the world coordinates from the previous line and converting it into grid coordinates. We know that grid coordinates multiplied by gridsize
is world coordinates. Therefore world coordinates divided by gridsize
produces grid coordinates.
The third line there is cursorx=-(int)locationx+(cursorx*gridsize)
. You're taking the grid coordinates from the previous line and multiplying by gridsize
, so that produces world coordinates. You then subtract the camera location, so that produces screen coordinates.
So my suggestion for those three lines of code is to be clear about which coordinate system it is:
cursorx_world = (int)locationx + (int)GameInput.mousex;
cursorx_grid = (int)cursorx_world / gridsize;
cursorx_screen = -(int)locationx + (cursorx_grid*gridsize);
To make it even clearer, you might consider using a Point class that lets you handle both x and y at once, so that you don't have to duplicate this code. You could write methods such as toWorld
and toScreen
to make it easier to read this kind of code.
Optimization of this part of the code is unlikely to make any difference. I'd strive for clarity over microoptimizations. (Also, I don't see a way to make those three lines much faster.)