地图绘制:创建一个Plane挂上地形的脚本。
wh是地图的顶点数,本次地形的绘制需要用到柏林噪声算法。
柏林噪声:一个噪声函数基本上是一个种子随机发生器。它需要一个整数作为参数,然后根据这个参数返回一个随机数。如果你两次都传同一个参数进来,它就会产生两次相同的数。这条规律非常重要,否则柏林函数只是生成一堆垃圾。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Terrain : MonoBehaviour
{
public Texture2D texture;
public int wh = 128;
float wid;
float hid;
public float p = 0.1f;
public Color gao = Color.blue;
public Color di = Color.green;
// Start is called before the first frame update
void Start()
{
VertexHelper vh = new VertexHelper();
texture = new Texture2D(wh, wh);
for (int x = 0; x < wh; x++)
{
for (int z = 0; z < wh; z++)
{
float noise = Mathf.PerlinNoise((x + wh * wid) * p, (z + wh * hid) * p);
float y = noise * 4;
Color color = Color.Lerp(gao, di, noise);
texture.SetPixel(x, z, color);
float ux = (float)x / (float)wh;
float uy = (float)z / (float)wh;
vh.AddVert(new Vector3(x, y, z), color, new Vector2(ux, uy));
if (x<wh-1 && z<wh-1)
{
vh.AddTriangle(x * wh + z, x * wh + z + 1, (x + 1) * wh + z + 1);
vh.AddTriangle(x * wh + z, (x + 1) * wh + z + 1, (x + 1) * wh + z);
}
}
}
texture.Apply();
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshRenderer>().material.mainTexture = texture;
GetComponent<MeshCollider>().sharedMesh = mesh;
}
// Update is called once per frame
void Update()
{
}
}
绘制球体:
创建一个空对象,如图:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CreatQiu : MonoBehaviour
{
float r = 3;
float anger;
public int n;
public Texture2D texture;
// Start is called before the first frame update
void Start()
{
VertexHelper vh = new VertexHelper();
anger = (2 * Mathf.PI) / n;
for (int i = 0; i < n/2+1; i++)
{
float r0 = Mathf.Sin(anger * i) * r;
float y = Mathf.Cos(anger * i) * r;
float uy = (float)(i) / (n / 2 + 1);
for (int j = 0; j < n; j++)
{
float x = Mathf.Sin(anger * j) * r0;
float z = Mathf.Cos(anger * j) * r0;
float ux = (float)(j) / n;
vh.AddVert(new Vector3(x, y, z), Color.white, new Vector2(ux, uy));
if (j==n-1)
{
float x0 = Mathf.Sin(anger * 0) * r0;
float z0 = Mathf.Cos(anger * 0) * r0;
vh.AddVert(new Vector3(x0, y, z0), Color.white, new Vector2(1, uy));
}
if (i<n/2)
{
vh.AddTriangle((i + 1) * (n + 1) + j, i * (n + 1) + j + 1, i * (n + 1) + j);
vh.AddTriangle((i + 1) * (n + 1) + j, (i + 1) * (n + 1) + j + 1, i * (n + 1) + j + 1);
}
}
}
Mesh mesh = new Mesh();
vh.FillMesh(mesh);
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshCollider>().sharedMesh = mesh;
GetComponent<MeshRenderer>().material.mainTexture = texture;
}
}