02 marzo 2008

Scrolling Horizontal

Para crear un Scrolling de izquierda a derecha a partir de un mapa representado en un matriz.
1.- Imagenes
Tile 1

Tile 2

Tile 3

Tile 4

2.- Codigo
Crear un hilo en el cual colocaremos lo siguiente
2.1- Declaraciones
private int indice_in, indice, xTiles, yTiles, sleep;
private Image[] tile = new Image[5];
int map[][] = {
{1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 2, 1, 1, 1, 1,1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1},
{1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}};

2.2.- Metodo run
Metodo que DEBE implementarse en un hilo

public void run() {
iniciar();
while (true) {
indice_in += 4;
if (indice_in >= 16) {
indice_in = 0;
indice--;
}
if (indice <>
indice = map[0].length - 1;
indice_in = 0;
}
repaint();
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println(e.toString());
}
}
}

2.3.- Metodo paint
Metodo que pinta las imagenes en pantalla
public void paint(Graphics g) {
int x = 0, y = 0, t = 0;
int i, j;
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(200, 200, 0);
for (i = 0; i < xTiles; i++) {
int a = (indice + i) % map[0].length;
for (j = 0; j < yTiles; j++) {
t = map[j][a];
y = j * 16;
x = (i - 1) * 16 + indice_in;
g.drawImage(tile[t], x, y, Graphics.LEFT | Graphics.TOP);
}
}
}

3.- Video-Demo
La implementacion se realizo para un dispositivo movil, y resulto algo asi.