教程总目录: http://blog.csdn.net/zqiang_55/article/details/50878524
已经介绍了这么多容器类来加载图片,下面出场的的是Sprite,也就是精灵类,这个可以说是集大成者,里面封装了更多的方法来操作纹理。
Sprite可以保存几何属性,大小(size, width, height),位置(position) 和旋转中心点(origin).
精灵总是一个矩形,而且绘制起点也是左下角
下面说说在实际中经常使用到的几个方法
/** Sets the position where the sprite will be drawn. If origin, rotation, or scale are changed, it is slightly more efficient
* to set the position after those operations. If both position and size are to be changed, it is better to use
* {@link #setBounds(float, float, float, float)}. */
public void setPosition (float x, float y)
/** Sets the position relative to the current position where the sprite will be drawn. If origin, rotation, or scale are
* changed, it is slightly more efficient to translate after those operations. */
public void translate (float xAmount, float yAmount)
/** Place origin in the center of the sprite */
public void setOriginCenter()
// 下面这个方法经常来用作碰撞检测
/** Returns the bounding axis aligned {@link Rectangle} that bounds this sprite. The rectangles x and y coordinates describe its
* bottom left corner. If you change the position or size of the sprite, you have to fetch the triangle again for it to be
* recomputed.
*
* @return the bounding Rectangle */
public Rectangle getBoundingRectangle ()
测试代码
Sprite sprite, sprite2;
SpriteBatch batch;
float rotation = 2;
Rectangle rec, rec2;
@Override
public void create() {
sprite = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")));
sprite2 = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")));
// 设置(320, 240)为sprite的中心点,并且以它为中心绘制
sprite.setCenter(320, 240);
sprite.setOriginCenter(); // 设置旋转中心在中心
rec = sprite.getBoundingRectangle(); // 后面做碰撞检测用
sprite2.setSize(60, 60); // 设置精灵大小为40*40
batch = new SpriteBatch();
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
float dt = Gdx.graphics.getDeltaTime();
rotation += dt / 360;
sprite.rotate(rotation);
// 每秒钟移动20
sprite2.translate(20 * dt, 20 * dt);
rec2 = sprite2.getBoundingRectangle();
if (rec2.overlaps(rec)) {
System.out.println("conflict");
sprite.setAlpha(0.5f);
sprite2.setAlpha(1.0f);
sprite2.setScale(2.0f);
}
batch.begin();
sprite.draw(batch);
sprite2.draw(batch, 0.8f);
batch.end();
}
@Override
public void dispose() {
sprite.getTexture().dispose();
sprite2.getTexture().dispose();
batch.dispose();
}