quality-control/Assets/Scripts/Grid Units/GridUnit.cs

55 lines
1.4 KiB
C#
Raw Permalink Normal View History

2024-08-17 11:34:29 +00:00
using UnityEngine;
using UnityEditor;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using static Grid;
using Color = UnityEngine.Color;
[ExecuteAlways]
[SelectionBase]
[DisallowMultipleComponent]
public class GridUnit : MonoBehaviour
{
2024-08-18 16:42:01 +00:00
public int3 Size = new(1, 1, 1);
private Vector3 SizeInMeters => new(Size.x * CellSize, Size.y * CellSize, Size.z * CellSize);
2024-08-17 11:34:29 +00:00
public float3 CenterOffset;
2024-08-18 16:42:01 +00:00
[SerializeField, HideInInspector] private int3 cachedSize = new(1, 1, 1);
[SerializeField, HideInInspector] private float3 cachedOffset;
private bool isDirty => transform.hasChanged ||
!all(cachedOffset != CenterOffset) ||
2024-08-17 11:34:29 +00:00
!all(cachedSize == Size);
2024-08-18 16:42:01 +00:00
#if UNITY_EDITOR
2024-08-17 11:34:29 +00:00
public void Update()
{
if (!isDirty)
{
return;
}
2024-08-18 16:42:01 +00:00
2024-08-17 11:34:29 +00:00
SnapUnit(transform, Size, CenterOffset);
transform.hasChanged = false;
2024-08-18 16:42:01 +00:00
2024-08-17 11:34:29 +00:00
cachedOffset = CenterOffset;
cachedSize = Size;
}
[DrawGizmo(GizmoType.InSelectionHierarchy)]
private static void DrawGizmo(GridUnit unit, GizmoType type)
{
Transform t = unit.transform;
quaternion rotation = t.rotation;
var position = (float3)t.position + mul(rotation, unit.CenterOffset);
2024-08-18 16:42:01 +00:00
2024-08-17 11:34:29 +00:00
Gizmos.color = Color.white;
Gizmos.matrix = Matrix4x4.TRS(position, rotation, Vector3.one);
Gizmos.DrawWireCube(Vector3.zero, unit.SizeInMeters);
}
#endif
2024-08-18 16:42:01 +00:00
}