我必须使用单个图像统一创建 2D map 。所以,我有一个 .png 文件,其中包含 5 个不同的部分,我必须从中创建一张 map ,并且不允许裁剪图像。那么,如何仅使用一张图像创建此 map 。
我对 Unity 有点陌生,我尝试搜索但没有找到我想要的东西。还尝试过使用 Pallet 进行tilemap,但无法弄清楚如何仅提取图像的一部分。
最佳答案
您可以在代码中根据给定的纹理动态创建各种 Sprite 。
您可以使用 Sprite.Create
定义给定 Texture2D
的哪一部分用于 Sprite提供rect
在给定图像的像素坐标中。但请记住,在统一纹理坐标中从左下角开始。
示例将给定的纹理像素坐标片段用于附加的 UI.Image
组件:
[RequireComponent(typeof(Image))]
public class Example : MonoBehaviour
{
// your texture e.g. from a public field via the inspector
public Texture2D texture;
// define which pixel coordinates to use for this sprite also via the inspector
public Rect pixelCoordinates;
private void Start()
{
var newSprite = Sprite.Create(texture, pixelCoordinates, Vector2.one / 2f);
GetComponent<Image>().sprite = newSprite;
}
// called everytime something is changed in the Inspector
private void OnValidate()
{
if (!texture)
{
pixelCoordinates = new Rect();
return;
}
// reset to valid rect values
pixelCoordinates.x = Mathf.Clamp(pixelCoordinates.x, 0, texture.width);
pixelCoordinates.y = Mathf.Clamp(pixelCoordinates.y, 0, texture.height);
pixelCoordinates.width = Mathf.Clamp(pixelCoordinates.width, 0, pixelCoordinates.x + texture.width);
pixelCoordinates.height = Mathf.Clamp(pixelCoordinates.height, 0, pixelCoordinates.y + texture.height);
}
}
或者你可以创建一种管理器类来生成所有需要的 Sprite 一次,例如在像这样的列表中
public class Example : MonoBehaviour
{
// your texture e.g. from a public field via the inspector
public Texture2D texture;
// define which pixel coordinates to use for this sprite also via the inspector
public List<Rect> pixelCoordinates = new List<Rect>();
// OUTPUT
public List<Sprite> resultSprites = new List<Sprite>();
private void Start()
{
foreach(var coordinates in pixelCoordinates)
{
var newSprite = Sprite.Create(texture, coordinates, Vector2.one / 2f);
resultSprites.Add(newSprite);
}
}
// called everytime something is changed in the Inspector
private void OnValidate()
{
if (!texture)
{
for(var i = 0; i < pixelCoordinates.Count; i++)
{
pixelCoordinates[i] = new Rect();
}
return;
}
for (var i = 0; i < pixelCoordinates.Count; i++)
{
// reset to valid rect values
var rect = pixelCoordinates[i];
rect.x = Mathf.Clamp(pixelCoordinates[i].x, 0, texture.width);
rect.y = Mathf.Clamp(pixelCoordinates[i].y, 0, texture.height);
rect.width = Mathf.Clamp(pixelCoordinates[i].width, 0, pixelCoordinates[i].x + texture.width);
rect.height = Mathf.Clamp(pixelCoordinates[i].height, 0, pixelCoordinates[i].y + texture.height);
pixelCoordinates[i] = rect;
}
}
}
示例:
我有 4 个 Image
实例并配置了它们,因此 pixelCooperative
是:
- imageBottomLeft:
X=0、Y=0、W=100、H=100
- imageTopLeft:
X=0、Y=100、W=100、H=100
- imageBottomRight:
X=100,Y=0,W=100,H=100
- imageTopRight:
X=100,Y=100,W=100,H=100
我使用的纹理是386 x 395
,所以我在这里没有使用全部纹理(只是添加了 Sprite 将要使用的帧)
因此,当点击“播放”时,将创建以下 Sprite :
关于c# - 如何使用单个图像统一创建二维 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57777823/