libGDX游戏开发之文理打包(八)
libGDX游戏开发之文理打包(八)
libGDX系列
,游戏开发有unity3D巴拉巴拉的,为啥还用java开发?因为我是Java程序员emm…国内用libgdx比较少,多数情况需要去官网和google找资料,相互学习的可以加我联系方式。
前言
TexturePacker,文理打包。我们为什么要对文理进行打包?
在OpenGL中,一个纹理被绑定,再执行绘制完成,另一个纹理被绑定,更多的绘制完成等等。绑定纹理的成本相对较高。
因此理想的做法是在一个较大的图像上存储许多较小的图像,绑定较大的纹理一次,然后多次绘制它的一部分。
libGDX 有一个TexturePacker类可以进行打包,也可以通过图形化界面工具打包:https://github.com/crashinvaders/gdx-texture-packer-gui
一、通过代码打包
首先添加依赖:
api "com.badlogicgames.gdx:gdx-tools:$gdxVersion"
创建一个目录将要打包的图片都放进去,注意命名规范,后面调用要用到的。
编写一个main执行打包:
import com.badlogic.gdx.tools.texturepacker.TexturePacker;
public class MyTexturePackage {
public static void main(String[] args) {
// 只支持".png", ".jpg", ".jpeg" 下面分别是输入目录,输出目录,输出的atlas名字
String inputDir="C:\\Users\\Administrator\\Desktop\\study\\game\\my-texture";
String outputDir="C:\\Users\\Administrator\\Desktop\\study\\game\\my-texture\\pack";
String packFileName="myPic";
TexturePacker.process(inputDir, outputDir, packFileName);
}
}
接下来放到资源文件中,加载调用,下面是一个demo:
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.ScreenUtils;
public class MyTexturePacker extends ApplicationAdapter {
private SpriteBatch batch;
private TextureAtlas atlas;
private TextureRegion gaoleng, meizi, pengzhang;
private Sprite xiang;
@Override
public void create() {
batch = new SpriteBatch();
atlas = new TextureAtlas(Gdx.files.internal("demo/myPic.atlas"));
// 通过名称获取
gaoleng = atlas.findRegion("gaoleng");
// 通过数组索引获取
meizi = atlas.getRegions().get(1);
pengzhang = atlas.findRegion("pengzhang");
xiang = atlas.createSprite("xiang");
}
@Override
public void render() {
ScreenUtils.clear(1, 0, 0, 1);
batch.begin();
batch.draw(gaoleng, 0, 0);
batch.draw(meizi, 0, 100);
batch.draw(pengzhang, 200, 0);
batch.draw(xiang, 300, 0);
batch.end();
}
@Override
public void dispose() {
// 防止内存溢出
batch.dispose();
atlas.dispose();
}
}
效果:
使用gdx-texture-packer-gui工具打包
2021-10-03 我用最新版是 4.10.1
使用gdx-texture-packer-gui工具打包,下载window版,我这里没能安装简体中文,估计是有bug,那就用英文版。下载安装后,运行,创建包:
填写输入输入和图片
右边的全局设置可以调整一些参数,我们不用管它,使用默认的,点击打包:
效果:
调用与上面的代码一致。
使用gdx-texture-packer-gui打包连续特效
使用gdx-texture-packer-gui比较方便,下面是打包连续特效的配置
打赏
创作不易,觉得内容不错就赏作者一杯咖啡吧!(恰饭)
后续我会出更多libgdx文章:寻路、寻路算法、打怪,以RPG的视角。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!