I try to implement a litte tile based ‘engine’ but by now the scrolling is really a mess.
The main loop is a simple
public void loop() {
long lastLoopTime = System.nanoTime();
while (true) {
long delta = System.nanoTime() - lastLoopTime;
lastLoopTime = System.nanoTime();
logic(delta);
draw();
}
}
the logic(delta) is also rather simple
public void logic(long delta) {
if (keys[KeyEvent.VK_SHIFT]) { dx = 640; dy = 480;}
else { dx = 2*64; dy = 2*48; }
if (keys[KeyEvent.VK_LEFT]) map.scroll((-delta * dx) / ONE_SECOND, 0);
if (keys[KeyEvent.VK_RIGHT]) map.scroll((delta * dx) / ONE_SECOND, 0);
if (keys[KeyEvent.VK_UP]) map.scroll(0, (-delta * dy) / ONE_SECOND);
if (keys[KeyEvent.VK_DOWN]) map.scroll(0, (delta * dy) / ONE_SECOND);
}
public void scroll(double dx, double dy) {
screenAnchor.x += dx;
screenAnchor.y += dy;
// prevent form leaving the map ....
}
where ONE_SECOND is on sec in nano secs (thus 100010001000) and dx/dy the moving speed in pixel/sec and screenAnchor a point representing the first viewable point in worldspace…
and finally draw() just calls the map.render method in a double buffered enviroment created with createBufferStrategy(2);
public void draw() {
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.setColor(Color.CYAN);
g.fillRect(0,0,WIDTH,HEIGHT);
map.render(g);
fps.display(g);
g.dispose();
strategy.show();
}
public void render(Graphics2D g) {
int tiles_x = screenSpace.width / tileSize.width;
int tiles_y = screenSpace.height / tileSize.height;
int sa_x = (int)screenAnchor.x;
int sa_y = (int)screenAnchor.y;
int ox = sa_x / tileSize.width;
int oy = sa_y / tileSize.height;
for(int y=0;y<tiles_y+1;y++) {
for(int x=0;x<tiles_x+1;x++) {
g.drawImage(map[oy+y][ox+x].image,
x * tileSize.width - sa_x % tileSize.width,
y * tileSize.height - sa_y % tileSize.height,
null);
}
}
}
If you wanna see what i mean with ‘sloppy’ there is a webstart
Maybe you can tell me what happens wrong with my code 