unity沿着给定三维向量方向生成半球体mesh
时间: 2023-05-23 07:02:06 浏览: 160
Unity向量按照某一点进行旋转
你可以使用以下代码来生成一个半球体 mesh。
```
using UnityEngine;
public class HalfSphere : MonoBehaviour {
public int segments = 12;
public float radius = 1f;
public Vector3 axis = Vector3.up;
void Start() {
Mesh mesh = new Mesh();
mesh.name = "Half Sphere";
Vector3[] vertices = new Vector3[segments * (segments / 2 + 1) + 1];
int[] triangles = new int[segments * (segments / 2) * 6];
Vector2[] uv = new Vector2[vertices.Length];
float segmentSize = Mathf.PI / segments;
float segmentAngle, radius2d, xz;
Vector3 pt;
int v = 0;
int t = 0;
// top point
vertices[0] = Vector3.up * radius;
uv[0] = Vector3.up;
for (int y = 1; y <= segments / 2; y++) {
segmentAngle = segmentSize * y;
radius2d = radius * Mathf.Cos(segmentAngle);
pt.y = radius * Mathf.Sin(segmentAngle);
for (int x = 0; x < segments; x++) {
xz = x * segmentSize;
pt.x = radius2d * Mathf.Sin(xz);
pt.z = radius2d * Mathf.Cos(xz);
vertices[v + 1] = pt;
uv[v + 1] = new Vector2(x / (float)segments, y / (float)(segments / 2));
v++;
if (y == 1) {
triangles[t] = 0;
triangles[t + 1] = v + 1;
triangles[t + 2] = v;
t += 3;
}
else if (x != 0) {
triangles[t] = v - segments - 1;
triangles[t + 1] = v - segments;
triangles[t + 2] = v;
t += 3;
}
if (x == segments - 1) {
triangles[t] = v - segments;
triangles[t + 1] = v - segments * 2 + 1;
triangles[t + 2] = v - segments + 1;
t += 3;
}
}
}
// bottom point
vertices[v + 1] = Vector3.down * radius;
uv[vertices.Length - 1] = Vector3.zero;
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uv;
mesh.RecalculateNormals();
transform.rotation = Quaternion.FromToRotation(Vector3.up, axis);
transform.GetComponent<MeshFilter>().mesh = mesh;
transform.GetComponent<MeshRenderer>().material = new Material(Shader.Find("Standard"));
}
```
使用这个脚本,你可以通过提供一个方向向量来生成半球体 mesh,如下:
```
public Vector3 direction = Vector3.forward;
void Start() {
Vector3 up = Vector3.up;
if (Mathf.Abs(Vector3.Dot(up, direction)) == 1) {
up = Vector3.right;
}
Vector3 axis = Vector3.Cross(direction, up).normalized;
transform.rotation = Quaternion.LookRotation(direction, axis);
HalfSphere halfSphere = gameObject.AddComponent<HalfSphere>();
halfSphere.axis = direction;
}
```
阅读全文