适用情景:主角带着光环,光环用一张贴图,要贴在地面上,并且随地面凹凸起伏
//代码
using UnityEngine;
using System.Collections; [RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class test : MonoBehaviour {
private MeshFilter mFilter;
private Mesh mMesh; public int QuadNum = 1;
public float QuadLength = 1; // Use this for initialization
void Start () {
mFilter = gameObject.GetComponent<MeshFilter>();
mMesh = new Mesh();
mFilter.sharedMesh = mMesh;
mMesh.MarkDynamic(); var quadNum = QuadNum * 2;
var ptNum = quadNum + 1;
var h_len = QuadNum * QuadLength;
var len = h_len * 2; var vertices = new Vector3[ptNum * ptNum];
var uv = new Vector2[ptNum * ptNum];
var triangle = new int[QuadNum * 2 * QuadNum * 2 * 6]; var offset = new Vector3(-h_len, 0, -h_len); for (int j = 0; j < ptNum; j++)
{
for (int i = 0; i < ptNum; i++)
{
int idx = j*ptNum+i;
uv[idx] = new Vector2(i * 1.0f / ptNum, j * 1.0f / ptNum);
}
} int it = 0;
for (int j = 0; j < quadNum; j++)
{
for (int i = 0; i < quadNum; i++)
{
int quadId = j * quadNum + i;
int p0 = quadId + j;
int p1 = p0 + ptNum;
int p2 = p1 + 1;
int p3 = p0 + 1; triangle[it++] = p0;
triangle[it++] = p1;
triangle[it++] = p2; triangle[it++] = p0;
triangle[it++] = p2;
triangle[it++] = p3;
}
} mMesh.vertices = vertices;
mMesh.uv = uv;
mMesh.triangles = triangle;
} // Update is called once per frame
protected virtual void Update () { var quadNum = QuadNum * 2;
var ptNum = quadNum + 1;
var h_len = QuadNum * QuadLength;
var len = h_len * 2; var vertices = new Vector3[ptNum * ptNum]; var offset = new Vector3(-h_len, 0, -h_len); var ray = new Ray(Vector3.down, Vector3.down);
var hit = new RaycastHit();
for (int j = 0; j < ptNum; j++)
{
for (int i = 0; i < ptNum; i++)
{
int idx = j * ptNum + i;
var pt = new Vector3(i * QuadLength, 0, j * QuadLength); ray.origin = transform.localToWorldMatrix.MultiplyPoint3x4(pt) + new Vector3(0, 10, 0);
if (Physics.Raycast(ray, out hit, 100))
{
pt = transform.worldToLocalMatrix.MultiplyPoint3x4(hit.point);
} vertices[i + j * ptNum] = pt;
}
} mMesh.vertices = vertices; } }