Android Games: HelloWorld2

De Aulas

Links relacionados: Jogos Digitais

Recursos

Classe MyGdxGame

package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class MyGdxGame extends ApplicationAdapter {
    SpriteBatch batch;
    Texture img[][];
    BitmapFont font;
    float x, y;
    int speed = 5;
    int w, h, W, H;
    int dir, step;
    int count;
    int max = 5;

    @Override
    public void create() {
        W = Gdx.graphics.getWidth();
        H = Gdx.graphics.getHeight();
        batch = new SpriteBatch();
        img = new Texture[4][2];
        for (int dir = 0; dir < 4; dir++) {
            for (int step = 0; step < 2; step++) {
                img[dir][step] = new Texture(
                        "avatar." + dir + "." + step + ".png");
            }
        }
        w = img[0][0].getWidth();
        h = img[0][0].getHeight();
        font = new BitmapFont(
                Gdx.files.internal("verdana.fnt"),
                Gdx.files.internal("verdana.png"),
                false);
    }

    public void andar() {
        count++;
        if (count > max) {
            count = 0;
            step = step == 1 ? 0 : 1;
        }
    }

    public void execute() {
        if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
            dir = 3;
            x -= speed;
            andar();
        } else if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
            dir = 1;
            x += speed;
            andar();
        }
        if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
            dir = 2;
            y += speed;
            andar();
        } else if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
            dir = 0;
            y -= speed;
            andar();
        }
        if (Gdx.input.isKeyJustPressed(Input.Keys.X)) {
            speed++;
        } else if (Gdx.input.isKeyJustPressed(Input.Keys.Z)) {
            if (speed > 0) speed--;
        }
        if (x < 0) x = 0;
        if (y < 0) y = 0;
        if (x > W - w) x = W - w;
        if (y > H - h) y = H - h;
    }

    @Override
    public void render() {
        execute();
        Gdx.gl.glClearColor(0, 0.5f, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        String text = "Hello(" + speed + "): " + x + ", " + y;
        font.draw(batch, text, 1, H);
        batch.draw(img[dir][step], x, y);
        batch.end();
    }

    @Override
    public void dispose() {
        batch.dispose();
        for (int dir = 0; dir < 4; dir++) {
            for (int step = 0; step < 2; step++) {
                img[dir][step].dispose();
            }
        }
    }
}