unity抛物线的制作
1.先来看效果
2.创建一个空物体,加上LineRenderer组件,再把脚本挂上即可,新建两个cube作为起点和终点,拖到脚本上,运行即可看到效果
代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SeletParabola : MonoBehaviour { public GameObject startPoint; //起点 public GameObject endPoint; //终点 public int lineSegmentNum = 50; public float heightFloat = 0.5f; //抛物线的高度 private LineRenderer lineRenderer; private List<Vector3> listLines = new List<Vector3>(); void Start() { lineRenderer = GetComponent<LineRenderer>(); lineRenderer.positionCount = lineSegmentNum; DrawParabola(); } void DrawParabola() { listLines.Clear(); Vector3 start = startPoint.transform.position; Vector3 end = endPoint.transform.position; float step = 1f / lineSegmentNum; for (int i = 1; i <= lineSegmentNum; i++) { float t = step * i; Vector3 lineposition = CalculateParabola(start, end, t, heightFloat); listLines.Add(lineposition); //lineRenderer.SetPosition(i - 1, lineposition); } lineRenderer.SetPositions(listLines.ToArray()); } public Vector3 CalculateParabola(Vector3 start, Vector3 end, float t, float heigh) { Vector3 height = Vector3.up * (end - start).magnitude * heigh; Vector3 midPoint = (start + end) * 0.5f + height; Vector3 P0 = start; Vector3 P1 = midPoint; Vector3 P2 = end; float u = 1 - t; float tt = t * t; float uu = u * u; Vector3 p = uu * P0; p += 2 * u * t * P1; p += tt * P2; return p; } }
3.扩展 (如果想要流动的抛物线,需要一张贴图,然后代码设置材质球的uv)
贴图如下
贴图设置
代码设置参数:
private float aa; private void Update() { aa += Time.deltaTime; lineRenderer.material.SetTextureOffset("_MainTex", new Vector2(-aa,0)); }
效果如下
本次就这么多了,喜欢的话,关注一下吧,感谢