我试图使用线渲染器在2d中使用中点平分法绘制山峰。所以我的想法是在山的左半部分然后在右半部分使用中点平分算法。但是结果却没有做到我想要的。这座山看起来不像是倒抛物线。
以下是代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DrawMountain : MonoBehaviour
{
public Color c1 = Color.yellow;
public Color c2 = Color.red;
public int lengthOfLeftLineRenderer = 10;
public int lengthOfRightLineRenderer = 10;
float start_x_left = -200f;
float end_x_left = -100f;
float start_x_right = -100f;
float end_x_right = 0f;
// Start is called before the first frame update
void Start()
{
float[] heightsLeft = new float[10];
float[] heightsRight = new float[10];
LineRenderer lineRenderer = gameObject.AddComponent<LineRenderer>();
lineRenderer.material = new Material(Shader.Find("Sprites/Default"));
lineRenderer.widthMultiplier = 0.5f;
lineRenderer.positionCount = lengthOfLeftLineRenderer;
// A simple 2 color gradient with a fixed alpha of 1.0f.
/* float alpha = 1.0f;
Gradient gradient = new Gradient();
gradient.SetKeys(
new GradientColorKey[] { new GradientColorKey(c1, 0.0f), new GradientColorKey(c2, 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(alpha, 0.0f), new GradientAlphaKey(alpha, 1.0f) }
);
lineRenderer.colorGradient = gradient; */
int left = 0;
int right = 9;
heightsLeft[left] = -77;
heightsLeft[right] = 0;
currentVertex = startVertex;
MidPointBisection(left, right,heightsLeft);
heightsRight[left] = 0;
heightsRight[right] = -77;
MidPointBisection(left, right,heightsRight);
DrawLine(heightsLeft, heightsRight);
}
void MidPointBisection(int left, int right, float[] heights)
{
int middle = (left + right) / 2;
if (middle == left) return;
heights[middle] = (heights[left] + heights[right]) / 2;
MidPointBisection(left, middle,heights);
MidPointBisection(middle, right,heights);
}
void DrawLine(float[] heightsLeft, float[] heightsRight)
{
LineRenderer lineRenderer = GetComponent<LineRenderer>();
var t = Time.time;
//lineRenderer.SetPosition(0, new Vector3(start_x + i * 5f, heights[i], 0.0f));
for (int i = 0; i < lengthOfLeftLineRenderer; i++)
{
lineRenderer.SetPosition(i, new Vector3(start_x_left +i*10f, heightsLeft[i], 0.0f));
}
for (int i = 0; i < lengthOfRightLineRenderer; i++)
{
lineRenderer.SetPosition(i, new Vector3(start_x_right + i * 10f, heightsRight[i], 0.0f));
}
}
}