x


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();
    }
}
more ▼

asked Dec 20 '11 at 07:33 PM

karl_ gravatar image

karl_
2.4k 41 53 69

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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();
    }
}
more ▼

answered Dec 20 '11 at 10:41 PM

karl_ gravatar image

karl_
2.4k 41 53 69

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1467
x1355
x139
x59

asked: Dec 20 '11 at 07:33 PM

Seen: 537 times

Last Updated: Dec 20 '11 at 10:41 PM