我有一个统一的精灵对象阵列。它们的大小取决于加载的图像。
我想把它们像平铺的地图一样并排组合成一幅图像。
我希望他们的布局像你正在形成一系列的图像,一个接一个。(注:不能一个接一个)
我怎么能做到这一点?
我合并的原因(只是为了那些想知道的人)是因为我使用的是polygon2d对撞机。因为当我同时使用多个对撞机时,会发生一些奇怪的行为,所以我决定在添加一个大型多边形对撞机之前,先合并图像。注意,这些事情发生在运行时。我不能仅仅创建一个大的图像并加载它,因为图像的顺序只是在运行时确定的。
我希望能得到一些帮助。谢谢。
最佳答案:
在Trutue2D类中有“PackTextures method”,但是因为它使你的阿特拉斯方框不能生成一组精灵,所以还有另一种方法来读取图像的像素并将它们设置为新的图像,在运行时做这件事非常昂贵,但给了你结果。
// your textures to combine
// !! after importing as sprite change to advance mode and enable read and write property !!
public Sprite[] textures;
// just to see on editor nothing to add from editor
public Texture2D atlas;
public Material testMaterial;
public SpriteRenderer testSpriteRenderer;
int textureWidthCounter = 0;
int width,height;
void Start () {
// determine your size from sprites
width = 0;
height = 0;
foreach(Sprite t in textures)
{
width += t.texture.width;
// determine the height
if(t.texture.height > height)height = t.texture.height;
}
// make your new texture
atlas = new Texture2D(width,height,TextureFormat.RGBA32,false);
// loop through your textures
for(int i= 0; i<textures.Length; i++)
{
int y = 0;
while (y < atlas.height) {
int x = 0;
while (x < textures[i].texture.width ){
if(y < textures[i].texture.height){
// fill your texture
atlas.SetPixel(x + textureWidthCounter, y, textures[i].texture.GetPixel(x,y));
}
else {
// add transparency
atlas.SetPixel(x + textureWidthCounter, y,new Color(0f,0f,0f,0f));
}
++x;
}
++y;
}
atlas.Apply();
textureWidthCounter += textures[i].texture.width;
}
// for normal renderers
if(testMaterial != null)testMaterial.mainTexture = atlas;
// for sprite renderer just make a sprite from texture
Sprite s = Sprite.Create(atlas,new Rect(0f,0f,atlas.width,atlas.height),new Vector2(0.5f, 0.5f));
testSpriteRenderer.sprite = s;
// add your polygon collider
testSpriteRenderer.gameObject.AddComponent<PolygonCollider2D>();
}