ces*_*eet 12 c# textures sprite texture2d unity-game-engine
我在Unity中有一组Sprite对象.它们的大小取决于加载的图像.我想将它们像平铺地图并排组合成一个图像.我希望它们的布局就像你正在形成一排图像,一个接一个.(注意:没有一个在另一个之上)我怎么能这样做?
我正在组合的原因(仅适用于那些想知道的人)是因为我正在使用polygon2D Collider.由于当我并排使用多个碰撞器时发生了一些奇怪的行为,我决定在添加一个大的多边形碰撞器之前组合图像.请注意,这些事情发生在运行时.我不能只创建一个大图像并加载,因为图像的顺序只在运行时确定.
我希望能得到一些帮助.谢谢.
在Texture2D类中有PackTextures方法,但由于它使你的atlas方形无法制作一行精灵,所以还有另一种方法可以通过读取图像的像素并将它们设置为新图像,这样做真的很贵在运行时但是给你结果.
// 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>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7341 次 |
| 最近记录: |