在Java中使用LibGdx制作Sprite Sheet动画
我在这里有一些代码,它获取一个精灵工作表,并通过获取图像的长度和宽度并按行和列对其进行细分来将其划分为单独的精灵。这个,适用于我的测试精灵工作表,但不是我实际上要用于我的游戏的那个。
我的动画课在这里:
package Simple;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.g2d.Animation;
public class RunningMan {
private Texture texture;
private TextureRegion[] walkFrames;
private Animation walkAnimation;
private float stateTime = 0f;
private TextureRegion currentFrame;
int rows = 5;
int cols = 6;
public RunningMan(Texture texture) {
this.texture = texture;
TextureRegion[][] tmp = TextureRegion.split(texture, texture.getWidth() / cols, texture.getHeight() / rows); // split the sprite sheet up into its 30 different frames
walkFrames = new TextureRegion[rows * cols];
int index = 0;
for(int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
walkFrames[index++] = tmp[i][j]; // Put the 30 frames into a 1D array from the 2d array
}
}
walkAnimation = new Animation(0.06f, walkFrames); // initialize the animation class
stateTime = 0f;
}
public void draw(Batch batch) {
stateTime += Gdx.graphics.getDeltaTime(); // stateTime is used to determine which frame to show
if(stateTime > walkAnimation.getAnimationDuration()) stateTime -= walkAnimation.getAnimationDuration(); // when we reach the end of the animation, reset the stateTime
currentFrame = walkAnimation.getKeyFrame(stateTime); // Get the current Frame
batch.draw(currentFrame,50,50); // draw the frame
}
}
我要运行动画的类在这里:
package Simple;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Animation extends ApplicationAdapter {
SpriteBatch batch;
RunningMan man;
@Override
public void create () {
batch = new SpriteBatch();
man = new RunningMan(new Texture(Gdx.files.internal("WalkingMan.png")));
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
man.draw(batch);
batch.end();
}
}
当我使用WalkingMan.png时,代码可以完美地工作。但当我使用任何其他精灵工作表时,例如WalkingWomen an.jpg(我并不担心这个工作表不透明),当相应地调整列和行时,对齐方式是关闭的。有什么建议吗?
WalkingMan.png
WalkingWoman.jpg
解决方案
动画类似乎通过假定精灵工作表图像中的所有帧都均匀分布来将源图像拆分为多个帧。因此,对于WalkingMan图像,512x512px的原始图像被分割成30帧,每帧85.33px宽(512/6列),102.4px高(512/5行)。
如果如您所说,调整WalkingWomen图像的列数和行数(1300x935),您将得到36帧,每帧宽144.44px(1300/9列),高233.75px(935/4行)。
问题是,WalkingWomen精灵的每个帧的间隔不均匀。如果将第一帧从图像中拆分出来,则会得到如下结果:
see how her foot is cut off on the right
WalkingMan图像将每个图像放置在一个大小相同的边界框内的精灵工作表中。您只需确保WalkingWomen床单的每一帧都以相同的方式均匀分布。
相关文章