我在 Unity 中有一系列 Sprite 对象。它们的大小根据加载的图像而变化。
我想将它们像平铺地图一样并排组合成一张图像。
我希望它们的布局就像您正在形成一行图像一样,一个接一个。 (注意:不是一个在另一个之上)
我怎样才能做到这一点?
我之所以进行组合(仅针对那些想知道的人)是因为我使用的是 Polygon2D Collider。由于当我并排使用多个碰撞器时会发生一些奇怪的行为,因此我决定在添加一个大型多边形碰撞器之前先组合图像。请注意,这些事情发生在运行时。我不能只创建一个大图像并加载它,因为图像的顺序仅在运行时确定。
我希望在这方面得到一些帮助。谢谢。
有PackTextures方法 http://docs.unity3d.com/ScriptReference/Texture2D.PackTextures.html在Texture2D类中,但是由于它使你的图集成为正方形,所以你不能制作一行精灵,所以还有另一种方法可以通过读取图像的像素并将它们设置为新图像来实现,在运行时执行起来非常昂贵,但给出你这个结果。
// Your textures to combine
// !! After importing as sprite change to advance mode and enable read and write property !!
public Sprite[] textures;
public Texture2D atlas; // Just to see on editor nothing to add from editor
public Material testMaterial;
public SpriteRenderer testSpriteRenderer;
int textureWidthCounter = 0;
int width,height;
private void Start () {
width = 0;
height = 0;
foreach(var t in textures) {
width += t.texture.width;
if (t.texture.height > height)
height = t.texture.height;
}
atlas = new Texture2D(width,height, TextureFormat.RGBA32,false);
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)
atlas.SetPixel(x + textureWidthCounter, y, textures[i].texture.GetPixel(x, y)); // Fill your texture
else atlas.SetPixel(x + textureWidthCounter, y,new Color(0f,0f,0f,0f)); // Add transparency
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
var 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>();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)