public Transform start; // 轨迹起点
public Transform end; // 轨迹终点
public float height = 5f; // 曲线最大高度
public int segmentCount = 50; // 轨迹分段数(越高越平滑)
public float lineWidth = 0.1f; // 线条宽度
private LineRenderer lineRenderer; // 用于绘制曲线的组件
void Start()
{
// 获取或初始化LineRenderer组件
lineRenderer = GetComponent<LineRenderer>();
// 设置线条宽度
lineRenderer.startWidth = lineWidth;
lineRenderer.endWidth = lineWidth;
// 设置材质
lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
// 设置颜色渐变
lineRenderer.startColor = Color.blue;
lineRenderer.endColor = Color.green;
// 设置轨迹点数量
lineRenderer.positionCount = segmentCount + 1;
StartCoroutine(AnimateCurve());
}
//private void Update()
//{
// // 当起点或终点移动时自动更新曲线(动态更新)
// if (start.hasChanged || end.hasChanged)
// {
// DrawCurve();
// start.hasChanged = end.hasChanged = false;
// }
//}
//慢慢延伸的曲线(固定起点与终点)
IEnumerator AnimateCurve()
{
lineRenderer.positionCount = 0;
for (int i = 0; i <= segmentCount; i++)
{
lineRenderer.positionCount = i + 1;
float t = i / (float)segmentCount;
Vector3 point = Vector3.Lerp(start.position, end.position, t);
point.y += height * Mathf.Sin(t * Mathf.PI);
lineRenderer.SetPosition(i, point);
yield return new WaitForSeconds(0.03f);
}
}
void DrawCurve()
{
Vector3 startPos = start.position;
Vector3 endPos = end.position;
// 生成每个轨迹点
for (int i = 0; i <= segmentCount; i++)
{
float t = i / (float)segmentCount; // 插值比例 [0,1]
// 使用正弦函数模拟高度变化(非标准抛物线)
//float y = height * Mathf.Sin(t * Mathf.PI);
// 标准抛物线方程
float y = height * 4 * t * (1 - t);
// 线性插值基础位置 + 高度偏移
Vector3 point = Vector3.Lerp(startPos, endPos, t);
point.y += y;
// 设置线段点位置
lineRenderer.SetPosition(i, point);
}
}
}
bezierLine