Hey,
I’ve just about completed the code that renders a map to the JFrame but I can’t seem to figure out how to make the map scroll as the player moves along it. I’ve got everything else working as far as I know (not rendering what’s outside the view, rendering tiles, etc…).
Could someone take a look at the code below and see if you can see what I might need to do to get the map to move with the player? I’m taking out the huge switch statement but the main code will be below.
package valkryst.area.map;
import java.awt.Graphics;
import valkryst.area.Area;
import valkryst.area.AreaLoader;
import valkryst.area.map.tile.GrassTile;
import valkryst.area.map.tile.VoidTile;
import valkryst.core.graphics.Frame;
import valkryst.entity.Player;
/**
* This class adds the map to the pixel array that will be rendered onto the screen.
*
* @author Valkryst
* --- Last Edit 11-Oct-2013
*/
public class RenderMap {
private static VoidTile voidTile = new VoidTile();
private static GrassTile grassTile = new GrassTile();
/**
* Renders the map to the canvas.
* @param g The graphics object to use to render things to the canvas with.
* @param area The area that the player is currently in.
* @param p The player.
* @param width The width of the canvas.
* @param height The height of the canvas.
*/
public static void render(final Graphics g, final Area area, final Player p, final int width, final int height) {
if(width > 0 && height > 0) { // If there is no room on the screen to render the map then don't bother rendering it.
for(int y = 0 + (int)p.getTileY() - 1; y < (int)p.getTileY() + (height >> 5) + 2; y++) {
for(int x = 0 + (int)p.getTileX() - 1; x < (int)p.getTileX() + (width >> 5) + 2; x++) {
try {
switch(AreaLoader.toArray()[y].substring(x, x+1)) {
case "A": {
g.drawImage(grassTile.getTileImage(), x * 32 * Frame.SCALE, y * 32 * Frame.SCALE, null);
break;
}
// Cut out about a hundred lines of switch statement.
default: {
g.drawImage(voidTile.getTileImage(), x * 32 * Frame.SCALE, y * 32 * Frame.SCALE, null);
}
}
} catch(Exception e) {
continue;
}
}
}
}
}
}
The player moves in pixels and every time the player moves 32 pixels the tileX and tileY change.
tileX and tileY represent where the player is on the map.
height and width are the height and width of the canvas.
Thanks for any replies.