You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并多张纹理为单张?Minecraft克隆块纹理脚本赋值求助

Minecraft克隆游戏:纹理分配与纹理图集制作方案

一、纹理图集的必要性

把多张方块纹理合并成单张大图(纹理图集)是这类游戏的标准操作,既能减少GPU的Draw Call提升性能,也能通过统一的UV坐标快速给不同方块分配纹理。

二、制作纹理图集的两种方法

1. 手动制作(快速验证)

用Photoshop、GIMP等工具新建2的幂次尺寸的画布(比如256×256、512×512,GPU处理更高效),将所有方块纹理按固定尺寸(比如16×16,和Minecraft一致)整齐排列,记录每个纹理在图集中的位置(比如第1行第2列)。

2. 脚本自动生成(批量处理)

用Python+PIL库可以快速批量生成,示例代码:

from PIL import Image
import os
import json

# 配置参数
tile_size = 16  # 单张方块纹理尺寸
atlas_size = 256  # 图集总尺寸,需是tile_size的整数倍
texture_folder = "./block_textures/"  # 单个纹理存放路径

# 创建空图集
atlas = Image.new("RGBA", (atlas_size, atlas_size), (0,0,0,0))
current_x, current_y = 0, 0
uv_map = {}  # 记录每个纹理对应的UV范围

for file_name in os.listdir(texture_folder):
    if not file_name.endswith(".png"):
        continue
    # 加载并调整纹理尺寸
    tile = Image.open(os.path.join(texture_folder, file_name)).resize((tile_size, tile_size))
    # 粘贴到图集
    atlas.paste(tile, (current_x * tile_size, current_y * tile_size))
    # 计算UV坐标(0-1范围)
    uv_map[file_name] = (
        current_x / (atlas_size / tile_size),
        current_y / (atlas_size / tile_size),
        (current_x + 1) / (atlas_size / tile_size),
        (current_y + 1) / (atlas_size / tile_size)
    )
    # 移动到下一个位置
    current_x += 1
    if current_x * tile_size >= atlas_size:
        current_x = 0
        current_y += 1

# 保存图集和UV映射
atlas.save("block_atlas.png")
with open("uv_map.json", "w") as f:
    json.dump(uv_map, f)

三、给指定坐标的方块分配纹理

1. 建立坐标-纹理映射规则

先定义好哪些坐标对应哪些纹理,比如:

coord_texture_map = {
    (0, 0, 0): "stone.png",
    (0, 0, 1): "grass.png",
    # 补充更多坐标映射
}

2. 生成Chunk时绑定UV

在构建Chunk的网格数据时,对每个方块:

  • 根据它的坐标从coord_texture_map中找到对应的纹理名称;
  • 从uv_map中取出该纹理的UV范围;
  • 将方块每个面的顶点UV替换为这个范围(比如原本的(0,0)改为UV范围的左下角,(1,1)改为右上角)。

如果用Unity这类引擎,也可以通过材质的偏移和缩放实现,不用手动改UV:

// Unity示例:给单个方块设置纹理
float tileRatio = (float)tileSize / atlasSize;
Vector2 textureOffset = new Vector2(uvX * tileRatio, uvY * tileRatio);
Vector2 textureScale = new Vector2(tileRatio, tileRatio);
blockRenderer.material.mainTextureOffset = textureOffset;
blockRenderer.material.mainTextureScale = textureScale;

四、解决洋红色问题

洋红色是纹理未正确加载或UV错误的典型表现:

  • 确认纹理图集已正确赋值给材质,Shader支持纹理采样(避免用了不支持纹理的纯色Shader);
  • 检查UV坐标是否在0-1范围内,超出范围会触发默认的错误颜色;
  • 确保每个网格顶点都正确绑定了UV数据,没有遗漏。

内容的提问来源于stack exchange,提问作者pietro bertipaglia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:50:18