Android Games: LetsMove

De Aulas

Links relacionados: Jogos Digitais

Vídeo Demonstrativo

Recursos

Classe MyGdxGame

 1package com.mygdx.game;
 2
 3import com.badlogic.gdx.ApplicationAdapter;
 4import com.badlogic.gdx.Gdx;
 5import com.badlogic.gdx.Input;
 6import com.badlogic.gdx.graphics.GL20;
 7import com.badlogic.gdx.graphics.Texture;
 8import com.badlogic.gdx.graphics.g2d.SpriteBatch;
 9
10public class MyGdxGame extends ApplicationAdapter {
11	private static final int SPEED = 5;
12	private SpriteBatch batch;
13	private Texture img;
14	private float x = 0;
15	private float y = 0;
16	private int h, w;
17	private boolean accel;
18
19	@Override
20	public void create() {
21		accel = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
22		w = Gdx.graphics.getWidth();
23		h = Gdx.graphics.getHeight();
24		batch = new SpriteBatch();
25		img = new Texture("sphere.png");
26	}
27
28	private void execute() {
29		// Verifies if accelerometer is available and use then.
30		float accelY = 0;
31		float accelX = 0;
32		if (accel) {
33			accelY = Gdx.input.getAccelerometerX() * 10;
34			accelX = Gdx.input.getAccelerometerY() * 10;
35		}
36		// Move object using keyboard and accelerometer
37		if ((accelY > 20) || (Gdx.input.isKeyPressed(Input.Keys.DOWN))) {
38			y -= SPEED;
39		} else if ((accelY < -20) || (Gdx.input.isKeyPressed(Input.Keys.UP))) {
40			y += SPEED;
41		}
42		if ((accelX > 20) || (Gdx.input.isKeyPressed(Input.Keys.RIGHT))) {
43			x += SPEED;
44		} else if ((accelX < -20) || (Gdx.input.isKeyPressed(Input.Keys.LEFT))) {
45			x -= SPEED;
46		}
47		// moving using touch or mouse
48		if (Gdx.input.isTouched()) {
49			x = Gdx.input.getX() - img.getWidth() / 2;
50			y = Gdx.graphics.getHeight() - Gdx.input.getY() - img.getHeight() / 2;
51		}
52		// Does not let the object leave the screen
53		if (x < 0) {
54			x = 0;
55		}
56		if (x + img.getWidth() > w) {
57			x = w - img.getWidth() - 1;
58		}
59		if (y < 0) {
60			y = 0;
61		}
62		if (y + img.getHeight() > h) {
63			y = h - img.getHeight() - 1;
64		}
65	}
66
67	@Override
68	public void render() {
69		execute();
70		Gdx.gl.glClearColor(0, 0.5f, 0, 1);
71		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
72		batch.begin();
73		batch.draw(img, x, y);
74		batch.end();
75	}
76
77	@Override
78	public void dispose() {
79		batch.dispose();
80		img.dispose();
81	}
82}