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

Unity相机沿Y轴移动时Tilemap渲染偏移问题求助

Unity Tilemap 相机移动后瓦片分离/精灵偏移问题

问题现象

  • 制作2D俯视场景时使用Tilemap,游戏启动渲染正常,但相机沿Y轴移动后出现两个问题:
    • 瓦片出现分离缝隙
    • Tilemap使用的精灵在Y轴方向出现1像素拉伸的偏移/裁剪错误
    • 移动前效果:移动前
    • 移动后效果:移动后
  • 参考Stack Overflow相关帖子时,发现直接修改Shader的Pixel Snap属性不可行,Unity提示需通过MaterialPropertyBlock修改该值

问题原因

  1. 亚像素渲染偏移:相机移动后,Tilemap的世界坐标与屏幕像素网格未严格对齐,GPU进行亚像素渲染时,导致瓦片边缘出现缝隙、精灵被错误拉伸
  2. 默认Shader未启用像素对齐:Unity自带的2D Tilemap Shader(如Sprites/Default)默认未开启Pixel Snap属性,无法自动将Tilemap的渲染坐标对齐到像素网格

解决方法

方法1:用MaterialPropertyBlock开启Pixel Snap

给Tilemap所在GameObject挂载以下脚本,动态设置Shader的像素对齐属性:

using UnityEngine;
using UnityEngine.Tilemaps;

[RequireComponent(typeof(TilemapRenderer))]
public class TilemapPixelSnap : MonoBehaviour
{
    private TilemapRenderer _tilemapRenderer;
    private MaterialPropertyBlock _propertyBlock;

    void Awake()
    {
        _tilemapRenderer = GetComponent<TilemapRenderer>();
        _propertyBlock = new MaterialPropertyBlock();
    }

    void Update()
    {
        _tilemapRenderer.GetPropertyBlock(_propertyBlock);
        // 启用Pixel Snap(对应Shader的_EnablePixelSnap属性)
        _propertyBlock.SetFloat("_EnablePixelSnap", 1);
        _tilemapRenderer.SetPropertyBlock(_propertyBlock);
    }
}

挂载后运行游戏,Tilemap会自动对齐像素网格,解决偏移和缝隙问题。

方法2:修改Tilemap材质参数(非共享材质可用)

如果Tilemap使用的是自定义材质而非默认共享材质:

  • 在材质面板找到Pixel Snap选项并勾选启用
  • 若面板无此选项,直接在材质的Keywords列表中添加PIXELSNAP_ON

方法3:相机强制像素对齐

给相机挂载以下脚本,确保相机位置始终对齐到像素单位(需根据你的场景像素比例调整参数):

using UnityEngine;

public class CameraPixelSnap : MonoBehaviour
{
    // 场景1世界单位对应像素数(例如1单位=16像素)
    public float pixelsPerUnit = 16f;

    void LateUpdate()
    {
        Vector3 pos = transform.position;
        // 计算对齐后的坐标,避免亚像素偏移
        float alignedX = Mathf.Round(pos.x * pixelsPerUnit) / pixelsPerUnit;
        float alignedY = Mathf.Round(pos.y * pixelsPerUnit) / pixelsPerUnit;
        transform.position = new Vector3(alignedX, alignedY, pos.z);
    }
}

从相机端解决坐标对齐问题,从根源避免Tilemap的渲染偏移。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:35:25