- Home /
Set Vertices to Ground
I'm trying to set all the vertices of plane to match the height of the terrain. At the moment, it sets about half the plane to some random Y value and ignores the other half. I can't seem to figure out what's going wrong here.
So far this is what I have:
using UnityEngine;
using UnityEditor;
using System.Collections;
public class GroundVertices : MonoBehaviour
{
[MenuItem("Tools/Ground Vertices")]
static void Init()
{
Mesh m = (Mesh)((MeshFilter)Selection.activeTransform.gameObject.GetComponent(typeof(MeshFilter))).sharedMesh;
Vector3[] verts = m.vertices;
for(int i = 0; i < verts.Length; i++)
{
verts[i] = new Vector3(verts[i].x, verts[i].y + 100f, verts[i].z);
RaycastHit ground = new RaycastHit();
if(Physics.Raycast(verts[i], Vector3.down, out ground))
{
Debug.Log(ground.point.y + ground.transform.tag);
verts[i].y = ground.point.y;
}
}
m.vertices = verts;
m.RecalculateNormals();
}
}
Comment
Best Answer
Answer by karl_ · Dec 20, 2011 at 10:41 PM
Turns out that the issue with half the verts flattening themselves was a red herring. The issue was that I was modifying local points, not world coordinates. Here is my solution:
using UnityEngine;
using UnityEditor;
using System.Collections;
public class GroundVertices : MonoBehaviour
{
[MenuItem("Tools/Ground Vertices")]
static void Init()
{
GameObject go = Selection.activeTransform.gameObject;
Mesh m = (Mesh)((MeshFilter)go.GetComponent(typeof(MeshFilter))).sharedMesh;
Vector3[] verts = m.vertices;
int layerMask = 1<<10;
for(int i = 0; i < verts.Length; i++)
{
Vector3 castFrom = go.transform.TransformPoint(verts[i]);
RaycastHit ground = new RaycastHit();
if(Physics.Raycast(castFrom, -Vector3.up, out ground, Mathf.Infinity,layerMask))
{
verts[i] = go.transform.InverseTransformPoint(ground.point);
}
}
m.vertices = verts;
m.RecalculateBounds();
m.RecalculateNormals();
m.Optimize();
}
}
Your answer
Follow this Question
Related Questions
How to make a procedural mesh that can be edited on a per- vertices basis 1 Answer
get terrain vertices? 2 Answers
Decaling! how to! Help! 2 Answers