Android e LibGDX

De Aulas

Links relacionados: Programação para Dispositivos Móveis

Criando um Projeto via Libgdx Setup

Primeiro de tudo, certifique-se que o Android ADT está instalado, configurado e rodando corretamente no seu computador.

Para trabalhar com a LibGDX, há um aplicativo de fácil configuração e criação de um projeto baseado na LibGDX, chamado LibGDX Setup. Para a criação de um projeto, siga os seguintes passos:

  1. Download da LibGDX:
    1. Faça download do arquivo libgdx-X.X.X.zip em http://code.google.com/p/libgdx/downloads/list
    2. Utilizo neste tutorial a versão libgdx-0.9.8.zip
    3. Descompacte o arquivo, mas mantenha a versão zipada que você vai precisar dela.
  2. Configurando um projeto:
    1. Dentro da pasta que você descompactou, execute o arquivo gdx-setup-ui.jar com um duplo clique (ou via linha de comando java -jar gdx-setup-ui.jar).
    2. Clique no botão Create.
    3. Na parte esquerda, especifique as configurações do projeto e os tipos de plataformas das quais o projeto será criado.
    4. Na parte central, indique onde está o arquivo zipado que você baixou da LibGDX.
    5. Clique em Open the generation screen.
    6. Clique no botão Launch! e depois feche esse programa.
  3. Importando o projeto no Eclipse:
    1. Agora abra o Eclipse e importe o projeto gerado do seu workspace.
    2. Vá no menu File... Import... General... Existing Projects into Workspace.
    3. Clique em Browse e selecione a pasta contendo os projetos gerados.
    4. Selecione todos os projetos e clique em Finish.
  4. Observações: Um conjunto de informações e tutoriais encontram-se na parte de documentação do site do LibGDX e na Wiki da LibGDX


Hello World

Para fazer nosso primeiro programa , primeiro crie um projeto conforme acima citado, chamado Example01.

O projeto vai criar 4 pastas. Coloque os arquivos de fontes dentro da subpasta assets da pasta Example01-android.

Dentro do Eclipse, no projeto criado chamado Example01, abra o arquivo chamado Example01.java dentro de src e coloque o seguinte código lá dentro:

 1package com.kurasu.rei;
 2
 3import com.badlogic.gdx.ApplicationListener;
 4import com.badlogic.gdx.Gdx;
 5import com.badlogic.gdx.graphics.GL10;
 6import com.badlogic.gdx.graphics.g2d.BitmapFont;
 7import com.badlogic.gdx.graphics.g2d.SpriteBatch;
 8
 9public class Example01 implements ApplicationListener {
10	private SpriteBatch batch;
11	private BitmapFont font;
12	float w, h;
13
14	@Override
15	public void create() {
16		w = Gdx.graphics.getWidth();
17		h = Gdx.graphics.getHeight();
18
19		batch = new SpriteBatch();
20		font = new BitmapFont(Gdx.files.internal("verdana.fnt"),
21				Gdx.files.internal("verdana.png"), false);
22	}
23
24	@Override
25	public void dispose() {
26		batch.dispose();
27	}
28
29	@Override
30	public void render() {
31		Gdx.gl.glClearColor(0, 0, 0, 1);
32		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
33		font.setColor(0.0f, 0.0f, 1.0f, 1.0f);
34		font.setScale(0.7f);
35		batch.begin();
36		font.draw(batch, "Hello world my Android game world!", 1, h + 1);
37		batch.end();
38	}
39
40	@Override
41	public void resize(int width, int height) {
42	}
43
44	@Override
45	public void pause() {
46	}
47
48	@Override
49	public void resume() {
50	}
51}

Agora execute o projeto HelloWorld-desktop ou a versão para android no emulador.

Um Segundo Exemplo

Crie um novo projeto chamado 'Example02.

Baixe os arquivos de imagem e coloque na pasta assets do projeto Example02-android.

Copie o seguinte código para o arquivo Example02.java do projeto Example02.

 1package com.kurasu.rei;
 2
 3import com.badlogic.gdx.ApplicationListener;
 4import com.badlogic.gdx.Gdx;
 5import com.badlogic.gdx.graphics.GL10;
 6import com.badlogic.gdx.graphics.OrthographicCamera;
 7import com.badlogic.gdx.graphics.Texture;
 8import com.badlogic.gdx.graphics.g2d.SpriteBatch;
 9import com.badlogic.gdx.math.Vector3;
10
11public class Example02 implements ApplicationListener {
12	private OrthographicCamera camera;
13	private SpriteBatch batch;
14	private Texture desert;
15	private Texture target;
16	float w, h;
17	float x, y;
18
19	@Override
20	public void create() {
21		w = Gdx.graphics.getWidth();
22		h = Gdx.graphics.getHeight();
23		x = 0.0f;
24		y = 0.0f;
25
26		camera = new OrthographicCamera();
27		camera.setToOrtho(false, 800, 480);
28		batch = new SpriteBatch();
29
30		desert = new Texture(Gdx.files.internal("desert.png"));
31		target = new Texture(Gdx.files.internal("target.png"));
32	}
33
34	@Override
35	public void dispose() {
36		desert.dispose();
37		target.dispose();
38		batch.dispose();
39	}
40
41	@Override
42	public void render() {
43		Gdx.gl.glClearColor(0, 0, 0, 1);
44		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
45		camera.update();
46
47		// Process input
48		if (Gdx.input.isTouched()) {
49			Vector3 touchPos = new Vector3();
50			touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
51			camera.unproject(touchPos);
52			x = touchPos.x - target.getWidth() / 2;
53			y = touchPos.y - target.getHeight() / 2;
54		}
55
56		// Render
57		batch.setProjectionMatrix(camera.combined);
58		batch.begin();
59		batch.draw(desert, 0, 0);
60		batch.draw(target, x, y);
61		batch.end();
62	}
63
64	@Override
65	public void resize(int width, int height) {
66	}
67
68	@Override
69	public void pause() {
70	}
71
72	@Override
73	public void resume() {
74	}
75}

Exemplo 03

Crie um projeto chamado Example03 e coloque os arquivos deste exemplo na subpasta assets da pasta Example03-android.

No arquivo Example03.java do projeto Example03 no Eclipse, coloque o seguinte código:

  1package com.kurasu.rei;
  2
  3import com.badlogic.gdx.ApplicationListener;
  4import com.badlogic.gdx.Gdx;
  5import com.badlogic.gdx.Input.Peripheral;
  6import com.badlogic.gdx.audio.Sound;
  7import com.badlogic.gdx.graphics.GL10;
  8import com.badlogic.gdx.graphics.OrthographicCamera;
  9import com.badlogic.gdx.graphics.Texture;
 10import com.badlogic.gdx.graphics.g2d.BitmapFont;
 11import com.badlogic.gdx.graphics.g2d.SpriteBatch;
 12import com.badlogic.gdx.math.Vector3;
 13
 14public class Example03 implements ApplicationListener {
 15	private OrthographicCamera camera;
 16	private SpriteBatch batch;
 17	private Texture background;
 18	private Texture avatar[][];
 19	private BitmapFont fontVerdana;
 20	private BitmapFont fontVerdanaShadow;
 21	private float w, h;
 22	private int toX, toY;
 23	private int x, y;
 24	private int step;
 25	private int direction;
 26	private int half = 0;
 27	private final int DOWN = 2;
 28	private final int RIGHT = 1;
 29	private final int UP = 0;
 30	private final int LEFT = 3;
 31	private Sound touchSound;
 32	private Sound music;
 33	private boolean touch = false;
 34	private boolean accel = false;
 35	private float accelX = 0;
 36	private float accelY = 0;
 37
 38	@Override
 39	public void create() {
 40		w = (int) Gdx.graphics.getWidth(); // / 2;
 41		h = (int) Gdx.graphics.getHeight(); // / 2;
 42
 43		accel = Gdx.input.isPeripheralAvailable(Peripheral.Accelerometer);
 44
 45		fontVerdana = new BitmapFont(Gdx.files.internal("verdana.fnt"),
 46				Gdx.files.internal("verdana.png"), false);
 47		fontVerdana.setColor(1.0f, 1.0f, 1.0f, 1.0f);
 48		fontVerdanaShadow = new BitmapFont(
 49				Gdx.files.internal("verdana-24-shadow.fnt"),
 50				Gdx.files.internal("verdana-24-shadow.png"), false);
 51		fontVerdanaShadow.setColor(0.5f, 1.0f, 0.5f, 1.0f);
 52
 53		avatar = new Texture[4][2];
 54		for (int i = 0; i < 4; i++) {
 55			for (int j = 0; j < 2; j++) {
 56				avatar[i][j] = new Texture(Gdx.files.internal("avatar." + i
 57						+ "." + j + ".png"));
 58			}
 59		}
 60		background = new Texture(Gdx.files.internal("grass.png"));
 61
 62		touchSound = Gdx.audio.newSound(Gdx.files.internal("touch.wav"));
 63		music = Gdx.audio.newSound(Gdx.files.internal("rain.mp3"));
 64		long id = music.play();
 65		music.setLooping(id, true);
 66
 67		camera = new OrthographicCamera();
 68		camera.setToOrtho(false, 800, 480);
 69		camera.setToOrtho(false, w, h);
 70		batch = new SpriteBatch();
 71		toX = 10;
 72		toY = 10;
 73		x = 0;
 74		y = 0;
 75		step = 0;
 76		half = (int) avatar[direction][step].getWidth() / 2;
 77		direction = DOWN;
 78	}
 79
 80	private boolean colision(int x, int y, int x1, int y1, int x2, int y2) {
 81		if (halfColision(x, x1, x2) && halfColision(y, y1, y2)) {
 82			return true;
 83		}
 84		return false;
 85	}
 86
 87	private boolean halfColision(int v, int v1, int v2) {
 88		if ((v > v1) && (v < v2)) {
 89			return true;
 90		}
 91		return false;
 92	}
 93
 94	private void move() {
 95		boolean changed = false;
 96		int distance = 20;
 97		if (accel) {
 98			accelY = (int) Gdx.input.getAccelerometerX() * -5;
 99			accelX = (int) Gdx.input.getAccelerometerY() * 5;
100		}
101		int width = (int) avatar[direction][step].getWidth();
102		int height = (int) avatar[direction][step].getHeight();
103		if (!halfColision(x + (width / 2), toX, toX + width)) {
104			if (x < toX) {
105				x += distance;
106				direction = RIGHT;
107			} else {
108				x -= distance;
109				direction = LEFT;
110			}
111			changed = true;
112		} else if (!halfColision(y + (height / 2), toY, toY + height)) {
113			if (y < toY) {
114				y += distance;
115				direction = DOWN;
116			} else {
117				y -= distance;
118				direction = UP;
119			}
120			changed = true;
121		}
122		if (accel && !changed) {
123			if (accelX >= 10) {
124				x += accelX;
125				toX = x;
126				direction = RIGHT;
127				changed = true;
128			} else if (accelX <= 10) {
129				x += accelX;
130				toX = x;
131				direction = LEFT;
132				changed = true;
133			}
134			if (accelY >= 10) {
135				y += accelY;
136				toY = y;
137				direction = UP;
138				changed = true;
139			} else if (accelY <= 10) {
140				y += accelY;
141				toY = y;
142				direction = DOWN;
143				changed = true;
144			}
145			changed = true;
146		}
147		if (x < 0) {
148			x = 0;
149			toX = x;
150			changed = false;
151		} else if (x > (w - 64)) {
152			x = (int) w - 64;
153			toX = x;
154			changed = false;
155		}
156		if (y < 0) {
157			y = 0;
158			toY = y;
159			changed = false;
160		} else if (y > (h - 64)) {
161			y = (int) h - 64;
162			toY = y;
163			changed = false;
164		}
165		if (changed) {
166			step = (step == 0) ? 1 : 0;
167		}
168	}
169
170	@Override
171	public void dispose() {
172		batch.dispose();
173		touchSound.dispose();
174		music.stop();
175		music.dispose();
176		for (int i = 0; i < 4; i++) {
177			for (int j = 0; j < 2; j++) {
178				avatar[i][j].dispose();
179			}
180		}
181		background.dispose();
182	}
183
184	@Override
185	public void render() {
186		Gdx.gl.glClearColor(1, 1, 1, 1);
187		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
188		camera.update();
189
190		// Process input
191		if (Gdx.input.isTouched()) {
192			Vector3 touchPos = new Vector3();
193			touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
194			camera.unproject(touchPos);
195			toX = (int) touchPos.x;
196			toY = (int) touchPos.y;
197			if (!touch) {
198				touchSound.play();
199			}
200			touch = true;
201		} else {
202			touch = false;
203		}
204		move();
205
206		// Render
207		batch.setProjectionMatrix(camera.combined);
208		batch.begin();
209		batch.draw(background, 0, 0);
210
211		// fontVerdana.setColor(1.0f, 1.0f, 1.0f, 1.0f);
212		fontVerdana.draw(batch, ": " + x + ", " + toX + ", " + w, 10, 200);
213		fontVerdanaShadow
214				.draw(batch, ": " + y + ", " + toY + ", " + h, 10, 100);
215		fontVerdanaShadow.draw(batch,
216				": accelXY(" + accelX + ", " + accelY + ")", 10, 300);
217
218		batch.draw(avatar[direction][step], x, y);
219		batch.end();
220		try {
221			Thread.sleep(20);
222		} catch (Exception e) {
223			e.printStackTrace();
224		}
225	}
226
227	@Override
228	public void resize(int width, int height) {
229	}
230
231	@Override
232	public void pause() {
233	}
234
235	@Override
236	public void resume() {
237	}
238}

Exercícios

Tendo como base os exemplos apresentados, faça um pequeno jogo utilizando os recursos de touch, movimentação, animação, sons. E, se possível, acelerômetro.