`

libgdx简单入门

阅读更多
最近一直想找个android的游戏引擎来研究,但是资源少、大多都不太出名,找了半天,发现libgdx还算不错,于是照着官网的例子,运行了下helloworld示例,发现这个引擎还不错,代码相对来说不算复杂,而且功能也算强大(虽然对3d的支持好像很弱),入门也容易。
这个helloworld是官方自带的,主要由两个类组成,一个是HelloWorldAndroid:
public class HelloWorldAndroid extends AndroidApplication {
	@Override
	public void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initialize(new HelloWorld(), false);
	}
}

这个类首先继承AndroidApplication,然后通过initialize方法初始化场景应用。initialize的内部会完成整个游戏的初始化工作,涉及到各种资源的载入,如input、audio、files、graphics等等,这些都是整个游戏引擎的基本组件。
下面再看看这个示例的核心代码类HelloWorld类:
public class HelloWorld implements ApplicationListener {
	SpriteBatch spriteBatch;
	Texture texture;
	BitmapFont font;
	Vector2 textPosition = new Vector2(100, 100);
	Vector2 textDirection = new Vector2(1, 1);

	@Override
	public void create () {
		Log.v("====create======", "===="+new Date());
		font = new BitmapFont();
		font.setColor(Color.RED);
		texture = new Texture(Gdx.files.internal("data/badlogic.jpg"));
		spriteBatch = new SpriteBatch();
	}

	@Override
	public void render () {
		int centerX = Gdx.graphics.getWidth() / 2;
		int centerY = Gdx.graphics.getHeight() / 2;

		Gdx.graphics.getGL10().glClear(GL10.GL_COLOR_BUFFER_BIT);

		// more fun but confusing :)
		// textPosition.add(textDirection.tmp().mul(Gdx.graphics.getDeltaTime()).mul(60));
		textPosition.x += textDirection.x * Gdx.graphics.getDeltaTime() * 60;
		textPosition.y += textDirection.y * Gdx.graphics.getDeltaTime() * 60;

		if (textPosition.x < 0) {
			textDirection.x = -textDirection.x;
			textPosition.x = 0;
		}
		if (textPosition.x > Gdx.graphics.getWidth()) {
			textDirection.x = -textDirection.x;
			textPosition.x = Gdx.graphics.getWidth();
		}
		if (textPosition.y < 0) {
			textDirection.y = -textDirection.y;
			textPosition.y = 0;
		}
		if (textPosition.y > Gdx.graphics.getHeight()) {
			textDirection.y = -textDirection.y;
			textPosition.y = Gdx.graphics.getHeight();
		}

		spriteBatch.begin();
		spriteBatch.setColor(Color.WHITE);
		spriteBatch.draw(texture, centerX - texture.getWidth() / 2, centerY - texture.getHeight() / 2, 0, 0, texture.getWidth(),
			texture.getHeight());
		font.draw(spriteBatch, "Hello World!", (int)textPosition.x, (int)textPosition.y);
		spriteBatch.end();
	}

	@Override
	public void resize (int width, int height) {
		spriteBatch.getProjectionMatrix().setToOrtho2D(0, 0, width, height);
		textPosition.set(0, 0);
	}
.....


这个类的代码其实并不复杂,最主要内容就是SpriteBatch类的使用,这个类有点类似事务的提交,先把图形规定好,然后用end提交时才真正的开始画。不过这个类的render是一个非常关键的方法,默认情况下,libgdx会一直不断的调用此方法以实现动画效果。至于怎么实现鄙人找了下源代码,看了个把小时还是没发现,初步估计可能是通过本地库实现的。至于libgdx的坐标方向与android系统自带的有些不一样,android本身默认是以左上角为原点,而libgdx则是左下角为原点,向上为y轴,向右为x轴。

这个例子代码可从官方下载,效果如下:




还有一个问题需要注意,那就是libgdx加载的图片的尺寸必须是2的n次方,不然会有错。
如里要想在屏幕上画出中文字体的话,见这篇文章:
http://www.cnblogs.com/htynkn/archive/2011/11/11/libgdx_3.html
  • 大小: 64.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics