如何用LibGDX的TextureAtlas创建动画?加载动画路径错误怎么解决?
用LibGDX的TextureAtlas创建动画&路径错误排查指南
我来帮你搞定这个问题,先从完整的动画创建流程说起,再针对性解决你遇到的路径错误~
一、TextureAtlas创建动画的完整步骤
1. 先搞定图集资源
首先你得用LibGDX自带的TexturePacker工具,把你的动画帧打包成.pack配置文件和对应的.png图集文件。这俩文件一定要放在你的项目assets目录下(看你Eclipse里的结构,这部分你应该已经做好了,有walk.pack和walk.png对吧?)
2. 正确加载TextureAtlas
这一步是很多人踩坑的地方!你必须先把图集加载进来,才能去拿里面的帧。代码要这么写:
TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("walk.pack"));
划重点:Gdx.files.internal()的根目录就是assets,所以路径直接写"walk.pack"就行,别加assets/前缀,加了就会报路径错误!
3. 创建Animation对象
加载完图集后,就可以用atlas.findRegions()获取一组连续命名的帧,再生成动画:
// 每0.5秒切换一帧,循环播放 Animation<TextureRegion> walk_up = new Animation<>(0.5f, atlas.findRegions("walk_up"), PlayMode.LOOP);
这里要注意:"walk_up"是你打包时给动画帧设置的前缀名——比如你原来的帧叫walk_up_0.png、walk_up_1.png,前缀就是walk_up,TextureAtlas会自动把这些同前缀的帧归为一组。
二、你的代码错误排查
结合你Eclipse的情况,你的问题大概率出在这几个地方:
- 漏了加载Atlas的步骤:你只写了创建动画的代码,但没先加载
walk.pack对吧?必须先执行TextureAtlas atlas = new TextureAtlas(...),再调用atlas.findRegions()。 - 图集里的区域名称不匹配:打开你的
walk.pack文件看看,里面的帧是不是叫walk_up_0、walk_up_1?如果打包时前缀写错了(比如写成walkUp),那atlas.findRegions("walk_up")肯定找不到。 - 没把assets设为资源文件夹:右键Eclipse里的
assets文件夹,选Build Path -> Use as Source Folder,不然项目找不到你的资源文件。
三、完整可运行示例代码
给你一个完整的小例子,你可以对照着改自己的代码:
public class MyAnimationDemo extends ApplicationAdapter { private TextureAtlas atlas; private Animation<TextureRegion> walkUpAnim; private float stateTime; private SpriteBatch batch; @Override public void create() { // 1. 加载图集 atlas = new TextureAtlas(Gdx.files.internal("walk.pack")); // 2. 创建动画 walkUpAnim = new Animation<>(0.5f, atlas.findRegions("walk_up"), PlayMode.LOOP); stateTime = 0; batch = new SpriteBatch(); } @Override public void render() { // 清屏 Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // 累计时间,用来计算当前帧 stateTime += Gdx.graphics.getDeltaTime(); TextureRegion currentFrame = walkUpAnim.getKeyFrame(stateTime, true); // 绘制动画 batch.begin(); batch.draw(currentFrame, Gdx.graphics.getWidth()/2 - currentFrame.getRegionWidth()/2, Gdx.graphics.getHeight()/2 - currentFrame.getRegionHeight()/2); batch.end(); } @Override public void dispose() { // 记得释放资源 atlas.dispose(); batch.dispose(); } }
内容的提问来源于stack exchange,提问作者Odd-Harald Myhren
相关产品推荐
相关产品推荐

