94 lines
2.4 KiB
C#
94 lines
2.4 KiB
C#
using System.Collections.Generic;
|
|
using Ichni;
|
|
using TMPro;
|
|
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
|
|
public class SimpleGridController : MonoBehaviour
|
|
{
|
|
public Camera targetCamera => EditorManager.instance.cameraManager.currentCamera;
|
|
|
|
[Header("Settings")]
|
|
public Material gridMaterial;
|
|
public GameObject textPrefab; // 预制体需要挂载 TextMeshPro
|
|
public Transform textParent;
|
|
|
|
[Header("Grid Logic")]
|
|
public bool showCoordinates = true;
|
|
public float baseGridSize = 1.0f;
|
|
[Range(10f, 1000f)] public float drawDistance = 100f;
|
|
|
|
|
|
// --- 内部状态 ---
|
|
private MeshRenderer _renderer;
|
|
private Material _instancedMat;
|
|
private float _currentSpacing = 1.0f;
|
|
|
|
void Start()
|
|
{
|
|
|
|
InitMesh();
|
|
|
|
_renderer = GetComponent<MeshRenderer>();
|
|
if (gridMaterial)
|
|
{
|
|
_instancedMat = new Material(gridMaterial);
|
|
_renderer.material = _instancedMat;
|
|
}
|
|
|
|
|
|
}
|
|
|
|
void LateUpdate()
|
|
{
|
|
if (!targetCamera) return;
|
|
|
|
Vector3 camPos = targetCamera.transform.position;
|
|
|
|
// 1. 网格跟随相机 (无限大地板)
|
|
transform.position = new Vector3(camPos.x, 0, camPos.z);
|
|
|
|
// 2. 计算层级 (1m / 10m / 100m)
|
|
CalculateGridLevel(camPos.y);
|
|
|
|
// 3. 更新 Shader
|
|
if (_instancedMat)
|
|
{
|
|
_instancedMat.SetFloat("_GridSpacing", _currentSpacing);
|
|
_instancedMat.SetFloat("_FadeDist", drawDistance);
|
|
}
|
|
|
|
|
|
}
|
|
|
|
private void CalculateGridLevel(float camHeight)
|
|
{
|
|
float absH = Mathf.Abs(camHeight);
|
|
float step = baseGridSize;
|
|
|
|
// 简单的自适应逻辑:根据高度决定网格密度
|
|
if (absH > 15f) step *= 10f;
|
|
if (absH > 150f) step *= 10f;
|
|
|
|
_currentSpacing = step;
|
|
}
|
|
|
|
|
|
private void InitMesh()
|
|
{
|
|
MeshFilter mf = GetComponent<MeshFilter>();
|
|
Mesh mesh = new Mesh();
|
|
// 覆盖视野的大 Quad
|
|
float size = 2000f;
|
|
Vector3[] vertices = new Vector3[4]
|
|
{
|
|
new Vector3(-size, 0, -size), new Vector3(size, 0, -size),
|
|
new Vector3(-size, 0, size), new Vector3(size, 0, size)
|
|
};
|
|
mesh.vertices = vertices;
|
|
mesh.triangles = new int[6] { 0, 2, 1, 2, 3, 1 };
|
|
mesh.uv = new Vector2[4] { Vector2.zero, Vector2.right, Vector2.up, Vector2.one };
|
|
mesh.RecalculateBounds();
|
|
mf.mesh = mesh;
|
|
}
|
|
} |