我正在尝试使用具有各种动作状态的png文件制作动画。我的问题是,渲染时图片彼此重叠。有解决方案,我只能显示一张照片吗? 我使用LibGDX库。
@Override public void show()
{
batch = new SpriteBatch();
img = new Texture("core/assets/ghosty.png");
regions = TextureRegion.split(img, 32, 32);
sprite = new Sprite (regions[0][0]);
Timer.schedule(new Timer.Task(){
@Override
public void run(){
frame++;
if (frame>27){
frame = 0;
if (zeile ==1){
zeile = 0;
}
else
{
zeile = 1;
}
}
sprite.setRegion(regions[zeile][frame]);
}
}, 0, 1/20f);
}
@Override public void render(float delta)
{
//stage.draw();
batch.begin();
sprite.draw(batch);
batch.end();
}
答案 0 :(得分:0)
您不需要额外的Timer任务和Sprite,而是需要Animation<>
。
以下是渲染动画的一个小示例:
private SpriteBatch batch;
private Texture img;
private Animation<TextureRegion> animation;
private TextureRegion[][] regions;
private Array<TextureRegion> frames;
@Override
public void show() {
batch = new SpriteBatch();
img = new Texture(Gdx.files.internal("ghosty.png")); //Get Texture from asset folder
regions = TextureRegion.split(img, 32, 32);
frames = new Array<TextureRegion>();
int rows = 5, columns = 5; //How many rows and columns the region have
//Fill Frames array with the regions of Texture
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
frames.add(regions[i][j]);
}
}
//Create Animation. 0.1f is the time how long a frame will occur,
//is the animation to fast set this number to a higher value
//so the single frames will stay for a longer time
animation = new Animation<TextureRegion>(0.1f, frames, Animation.PlayMode.LOOP);
}
private float stateTime = 0;
@Override
public void render(float delta) {
//Clear the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//update state time so animation will go further
stateTime += delta;
batch.begin();
//Draw the current frame
batch.draw(animation.getKeyFrame(stateTime), 50, 50);
batch.end();
}
希望这会对您有所帮助。
一种运行动画的更有效,更简便的方法是使用TextureAtlas
而不是Texture
。这是使用TextureAtlas的示例:Libgdx Animation not working