Unity中如何实现绘制Sin函数图像
在Unity中可以使用LineRenderer组件来绘制线条,通过添加Position,来添加线段的拐点,
------------------>
也就是说,绘制Sin函数图像只要采样Sin函数的不同点,然后赋值给LineRenderer即可。
实现过程:
首先在场景中创建一个空物体,添加LineRenderer组件,创建WaveDisplay脚本:
public class WaveDisplay : MonoBehaviour
{
LineRenderer lineRenderer;
public int posCount ; //采样点个数
public float frequency = .5f; //频率
public float amplitude = 1f; //振幅
// Start is called before the first frame update
void Start()
{
this.lineRenderer = GetComponent<LineRenderer>();
this.Draw();
}
void Draw()
{
float xStart = 0f;
float tau = 2 * Mathf.PI;
float xFinish = tau;
this.lineRenderer.positionCount = posCount;
for (int i = 0; i < posCount; i++) {
float progress = (float)i / (posCount - 1);
float x = Mathf.Lerp(xStart, xFinish, progress);
float y = amplitude * Mathf.Sin(tau * frequency * x);
this.lineRenderer.SetPosition(i, new Vector3(x, y, 0));
}
}
}
结果: