Files
zeling_v2/Assets/_Game/Scripts/Camera/SpritePixelSnapper.cs
2026-05-19 11:50:21 +08:00

45 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using UnityEngine;
namespace BaseGames.Camera
{
/// <summary>
/// 精灵像素对齐组件。
///
/// 挂载在含 <see cref="SpriteRenderer"/> 的 GameObject 上(可与 Rigidbody2D 同节点)。
/// 每渲染帧在 LateUpdate+1000与 <see cref="CameraPixelSnapper"/> 同执行序)中,
/// 将 <c>transform.position</c> 四舍五入到最近像素网格,消除精灵移动时的亚像素模糊。
///
/// <para>
/// 与 <see cref="CameraPixelSnapper"/> 搭配使用时,须保持 <c>_pixelsPerUnit</c>
/// 与相机侧一致,使精灵和相机吸附到同一像素格,从而消除二者相对偏移造成的抖动。
/// </para>
/// <para>
/// Rigidbody2D 内部物理位置(<c>rb.position</c>)不受影响;
/// 仅 <c>transform.position</c>(用于渲染)被修正,最大偏差 ±0.5 / PPU。
/// 子节点HurtBox、GroundCheck 等)随父节点微小平移,但偏差在物理容差范围内,
/// 不影响碰撞检测精度。
/// </para>
/// </summary>
[DefaultExecutionOrder(1000)]
[AddComponentMenu("BaseGames/Camera/Sprite Pixel Snapper")]
public class SpritePixelSnapper : MonoBehaviour
{
[Tooltip("每世界单位像素数PPU。须与 CameraPixelSnapper 及精灵导入设置保持一致。\n" +
"常用值16粗像素风格、32标准像素风格。0 = 禁用对齐。")]
[Min(0f)]
[SerializeField] private float _pixelsPerUnit = 16f;
private void LateUpdate()
{
if (_pixelsPerUnit <= 0f) return;
float ppu = _pixelsPerUnit;
Vector3 pos = transform.position;
pos.x = Mathf.Round(pos.x * ppu) / ppu;
pos.y = Mathf.Round(pos.y * ppu) / ppu;
// Z 轴不参与像素对齐
transform.position = pos;
}
}
}