Files
MinFt/Client/Assets/Scripts/UIExtend/TMP_Text_Curved.cs
2026-04-27 12:07:32 +08:00

69 lines
2.6 KiB
C#

using TMPro;
using UnityEngine;
[RequireComponent(typeof(TMP_Text))]
public class TMP_Text_Curved : MonoBehaviour
{
public TMP_Text m_TextComponent;
public float height = 1;
public float allWidth = 800;
public float radian_angle = 30f;
private void OnValidate()
{
if (m_TextComponent == null)
{
m_TextComponent = GetComponent<TMP_Text>();
}
SetTextCurved();
}
private void Awake()
{
if (m_TextComponent == null)
{
m_TextComponent = GetComponent<TMP_Text>();
}
}
private void LateUpdate()
{
SetTextCurved();
}
void SetTextCurved()
{
m_TextComponent.ForceMeshUpdate();
TMP_TextInfo textInfo = m_TextComponent.textInfo;
if (textInfo == null) return;
int characterCount = textInfo.characterCount;
if (characterCount == 0) return;
Quaternion rotation;
Vector3 center;
var charInfo = textInfo.characterInfo[characterCount - 1];
Vector3[] vertices;
int vertexIndex;
for (int i = 0; i < characterCount; i++)
{
charInfo = textInfo.characterInfo[i];
if (!charInfo.isVisible) continue;
vertices = textInfo.meshInfo[charInfo.materialReferenceIndex].vertices;
vertexIndex = charInfo.vertexIndex;
center = (vertices[vertexIndex + 0] + vertices[vertexIndex + 1] + vertices[vertexIndex + 2] + vertices[vertexIndex + 3]) / 4;
float angle = center.x < 0 ? vertices[vertexIndex + 0].x / allWidth : vertices[vertexIndex + 3].x / allWidth;
rotation = Quaternion.Euler(0, 0, -angle * radian_angle);
vertices[vertexIndex + 0] = rotation * (vertices[vertexIndex + 0] - center) + center;
vertices[vertexIndex + 1] = rotation * (vertices[vertexIndex + 1] - center) + center;
vertices[vertexIndex + 2] = rotation * (vertices[vertexIndex + 2] - center) + center;
vertices[vertexIndex + 3] = rotation * (vertices[vertexIndex + 3] - center) + center;
Vector3 offset = Vector3.up * (Mathf.Cos(angle * Mathf.PI) - 1f) * height;
vertices[vertexIndex + 0] += offset;
vertices[vertexIndex + 1] += offset;
vertices[vertexIndex + 2] += offset;
vertices[vertexIndex + 3] += offset;
}
for (int i = 0; i < textInfo.meshInfo.Length; i++)
{
var meshInfo = textInfo.meshInfo[i];
meshInfo.mesh.vertices = meshInfo.vertices;
m_TextComponent.UpdateGeometry(meshInfo.mesh, i);
}
}
}