声明:
本系列文章使用的Libgdx版本均为0.99版本
Libgdx游戏开发交流群 323876830
代码写到这,有完美主义的人,该说了, 这代码也太烂了吧, 啥东西都充斥在一个类中,什么SpriteBatch,什么OrthographicCamera,还有该死的变换等逻辑,要是把这些能分开就好了,有一个单独的东西能够处理SpriteBatch和OrthographicCamera,不需要我自己来处理, 然后他可以添加对象, 这个对象呢, 可以自己在他的类中做逻辑。 哈哈。别担心。Libgdx早就想到了这一点,他提供了Stage舞台和Actor演员对象来分别处理这些。
把咱们的代码重构下,看看
public class FirstGame implements ApplicationListener
{
private Stage mStage;
@Override
public void create()
{
mStage = new Stage(800, 480);
mStage.addActor(new Player());
}
@Override
public void resize(int width, int height)
{
}
@Override
public void render()
{
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
mStage.act(Gdx.graphics.getDeltaTime());
mStage.draw();
}
@Override
public void pause()
{
// TODO Auto-generated method stub
}
@Override
public void resume()
{
// TODO Auto-generated method stub
}
@Override
public void dispose()
{
// 所有实现Disposable接口的都需要释放资源
mStage.dispose();
}
}
public class Player extends Actor
{
private Pixmap mPixmap;
private Texture mTexture;
private TextureRegion mTextureRegion;
private Sprite mSprite;
private float timer;
public Player()
{
mPixmap = new Pixmap(Gdx.files.internal("gremlins.png"));
mTexture = new Texture(mPixmap);
mTextureRegion = new TextureRegion(mTexture, 0, 0, 30, 30);
mSprite = new Sprite(mTextureRegion);
mSprite.setPosition(800 / 2, 480 / 2);
}
@Override
public void draw(SpriteBatch batch, float parentAlpha)
{
timer += Gdx.graphics.getDeltaTime();
// 1.移动
if (timer < 3)
{
// 每秒移动50像素
mSprite.translateX(50 * Gdx.graphics.getDeltaTime());
}
// 2.放缩
else if (timer > 3 && timer < 6)
{
// 每秒xy方向上放大1倍
mSprite.setPosition(800 / 2, 480 / 2);
mSprite.scale(1 * Gdx.graphics.getDeltaTime());
}
// 3.翻转
else if (timer > 6 && timer < 9)
{
// 每秒旋转90度
mSprite.setScale(1, 1);
mSprite.rotate(90 * Gdx.graphics.getDeltaTime());
}
else
{
timer = 0;
mSprite.setPosition(800 / 2, 480 / 2);
mSprite.setScale(1, 1);
mSprite.setRotation(0);
}
mSprite.draw(batch);
}
}
改过后,顿时感觉清爽多了, 不至于导致了类爆炸,而且各司其职, 非常简洁,而且Stage集成了不止这些,还有输入事件,分发事件等。 还是比较实用的。
转载请链接原文地址 http://blog.csdn.net/wu928320442/article/details/16940069