【问题标题】:Loading sprite with asset manager LibGDX使用资产管理器 LibGDX 加载精灵
【发布时间】:2015-02-03 10:10:39
【问题描述】:

如何使用 .assets.load("file", file.type) 加载精灵,在这种情况下,精灵的文件类型应该是什么?

【问题讨论】:

    标签: libgdx sprite assets


    【解决方案1】:

    我猜,您通常不会直接加载 Sprite,而是加载它的是 Texture 并从中创建一个 Sprite
    因此,您调用assets.load("file", Texture.class),然后使用您加载的Texture 创建一个Sprite
    Sprite sprite = new Sprite(asstes.get("file", Texture.class))

    但我建议你使用TextureAtlas 而不是Texture
    TextureAtlas 是某种“纹理集合”,它基本上是一个大 Texture,它本身包含所有单个 Textures。
    您可以使用 assets.load("atlas", TextureAtlas.class)
    加载它 并使用: TextureAtlas atlas = assets.get("atlas", TextureAtlas.class).
    然后您可以像这样创建您的Sprite
    Sprite sprite = atlas.createSprite("spriteName");

    要创建TextureAtlas,您可以使用TexturePacker

    【讨论】:

      【解决方案2】:

      不建议直接加载精灵。当 Android 上发生上下文丢失时,它将释放加载的资源占用的内存。因此,在上下文丢失后直接访问您的资产会立即使恢复的应用程序崩溃。

      为防止出现上述问题,您应该使用 AssetManager 加载和存储资源,如纹理、位图字体、平铺贴图、声音、音乐等。通过使用 AssetManager,您只需加载每个资产一次。

      我推荐的做法如下:

      // load texture atlas
      final String spriteSheet = "images/spritesheet.pack";
      assetManager.load(spriteSheet, TextureAtlas.class);
      // blocks until all assets are loaded
      assetManager.finishedLoading();
      // all assets are loaded, we can now create our TextureAtlas object
      TextureAtlas atlas = assetManager.get(spriteSheet);
      
      // (optional) enable texture filtering for pixel smoothing
      for (Texture t: atlas.getTextures())
          t.setFilter(TextureFilter.Linear, TextureFilter.Linear);
      
      // Create AtlasRegion instance according the given <atlasRegionName>
      final String atlasRegionName = "regionName";
      AtlasRegion atlasRegion = atlas.findRegion(atlasRegionName);
      
      // adjust your sprite position and dimensions here
      final float xPos = 0;
      final float yPos = 0;
      final float w = asset.getWidth();
      final float h = asset.getHeight();
      
      // create sprite from given <atlasRegion>, with given dimensions <w> and <h>
      // on the position of the given coordinates <xPos> and <yPos>
      Sprite spr = new Sprite(atlasRegion, w, h, xPos, yPos);
      

      【讨论】:

      • 您可以直接从TextureAtlasatlas.createSprite(spritename) 创建它,而不是从AtlasRegion 创建一个新的Sprite。另外TextureFilter可以在TexturePacker的配置中设置,所以是为整个TextureAtlas设置的。
      • 这个答案不太正确。 libgdx 中的纹理在有或没有 AssetManager 的情况下都会自动管理,因此在上下文丢失后会自动重新加载。
      • 在 libgdx 中,您可以拥有托管和非托管纹理。因此,您确实可以通过确保自动管理纹理来避免使用 AssetManager。这是从 FileHandle 加载纹理时的情况,但是如果它们是从 Pixmap 加载的,则您必须在 resume()resize() 方法中手动重新加载它们。为了避免这种头痛,我建议使用AssetManager
      猜你喜欢
      • 2017-09-09
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 2012-09-05
      • 2023-03-23
      • 1970-01-01
      • 2016-09-14
      相关资源
      最近更新 更多