I have written the following code as the level rendering part of a game engine I am writing. I am very happy how it works but as it is the background / level graphics made up of individual blocks it needs to be quick.
What it does it look take the graphics from a resource loaded elsewhere and scales it onto the block if it is in the viewing window.
Blocksize
is the size of the blocks and can be increased of decreased and is used to scale the blocks to give the Zoom in and out effect.
How can I improve this code both in terms of speed and shorten it to improve readability?
public void render(Graphics g){
//Ensure player co-ords updated
camerax=playerx-(gamewidth/2);
cameray=playery-(gameheight/2);
int blockwidth=blocksize-2;
//Draw coloured blocks
int screenx=-(int)camerax-blocksize;
for (int x=0;x<sizex;x++){
screenx+=blocksize;
if (screenx>-blocksize && screenx<gamewidth){
int screeny=-(int)cameray-blocksize;
for (int y=0;y<sizey;y++){
screeny+=blocksize;
if (screeny>-blocksize && screeny<gameheight){
if (tiles[x][y][0]>0){
g.drawImage(levelgraphics, screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null);
} else {
g.setColor(new Color( tiles[x][y][1]));
g.fillRect(screenx,screeny,blockwidth,blockwidth);
g.setColor(Color.WHITE);
g.drawString(String.valueOf(x+y*sizex), screenx+5,screeny+20);
}
}
}
}
}
//world - camera = screen, algebra that world = screen + camera
//Add camerax to mouse screen co-ords to convert to world co-ords.
int cursorx_world=(int)camerax+(int)GameInput.mousex;
int cursorx_grid=(int)cursorx_world/blocksize; // World Co-ords / gridsize give grid co-ords
int cursorx_screen=-(int)camerax+(cursorx_grid*blocksize);
//Add cameray to mouse screen co-ords to convert to world co-ords.
int cursory_world=(int)cameray+(int)GameInput.mousey;
int cursory_grid=(int)cursory_world/blocksize;
int cursory_screen=-(int)cameray+(cursory_grid*blocksize);
//Draw on screen cursor
if (cursorx_grid>=0 && cursory_grid>=0 && cursorx_grid<sizex && cursory_grid<sizey){
//if (detect(cursorx_grid,cursory_grid)){
//if (tiles[cursorx_grid][cursory_grid][0]>1){
g.setColor(Color.yellow);
g.drawRect(cursorx_screen,cursory_screen,blockwidth,blockwidth);
//}
}
//Draw on screen map
for (int x=0;x<sizex;x++){
for (int y=0;y<sizey;y++){
g.setColor(new Color((int) tiles[x][y][1]));
g.fillRect(mapx+x*mapsize, mapy+y*mapsize, mapsize, mapsize);
}
}
//Outline
g.drawRect(mapx,mapy,mapsize*sizex ,mapsize*sizey );
//Map location box
g.setColor(Color.RED);
g.drawRect(mapx+mapsize*((int)camerax/blocksize),mapy+mapsize*((int)cameray/blocksize),(gamewidth/blocksize)*mapsize ,(gameheight/blocksize)*mapsize );
}
The last bit of the code adds a map onto the screen and pops a scaled box on it so players can see what part of the map they are looking at.