- Home /
Mesh collider on procedurally generated mesh
Hi,
I'm having a problem assigning my mesh a collider.
I've tweaked the CrumpleMesh scene (from the procedural examples package) and now have a flat plane that, on run time, is deformed by Perlin noise. I can assign the mesh itself a collider but this does not follow the contours of the deformed mesh (e.g. the hills and troughs).
So- in light of the above, what would be the best way of assigning a collider to my mesh after it has been deformed (I imagine I need to add something to the script, but can't quite work out what).
FYI, I'm using the C# version of the script:
using UnityEngine;
using System.Collections;
using Graphics.Tools.Noise;
using Graphics.Tools.Noise.Primitive;
using Graphics.Tools.Noise.Filter;
public class CrumpleMesh : MonoBehaviour {
public float scale = 1f;
public float speed = 0f;
public bool recalculateNormals = false;
private Vector3[] _baseVertices;
private IModule3D _noise;
//seed
private Mesh _mesh;
static private System.Random _rnd = new System.Random(999);
/// <summary>
///
/// </summary>
void Start () {
_mesh = GetComponent<MeshFilter>().mesh;
}//end Start
/// <summary>
///
/// </summary>
void Update () {
if (_noise == null){
CreatePrimitive();
}//end if
if (_baseVertices == null){
_baseVertices = _mesh.vertices;
}//end if
Vector3[] vertices = new Vector3[_baseVertices.Length];
float timex = Time.time * speed + 1.2584f;
float timey = Time.time * speed + 40.6584f;
float timez = Time.time * speed + 1.6518f;
for (int i = 0; i < vertices.Length; i++){
Vector3 vertex = _baseVertices[i];
vertex.x += _noise.GetValue(timex + vertex.x, timex + vertex.y, timex + vertex.z) * scale;
vertex.y += _noise.GetValue(timey + vertex.x, timey + vertex.y, timey + vertex.z) * scale;
vertex.z += _noise.GetValue(timez + vertex.x, timez + vertex.y, timez + vertex.z) * scale;
vertices[i] = vertex;
}//end for
_mesh.vertices = vertices;
if(recalculateNormals){
_mesh.RecalculateNormals();
}//end if
_mesh.RecalculateBounds();
}//end Update
/// <summary>
///
/// </summary>
private void CreatePrimitive(){
SimplexPerlin primitive = new SimplexPerlin();
primitive.Seed = (int)(_rnd.Next() * _rnd.Next());
SinFractal filter = new SinFractal();
filter.OctaveCount = 10f;
filter.Primitive3D = primitive;
_noise = primitive;
}//end CreatePrimitive
}//end class
Thank you for any responses.
Answer by Eric5h5 · Dec 15, 2011 at 12:13 AM
Copy the generated mesh to the meshcollider's mesh. i.e., GetComponent<MeshCollider>().mesh = _mesh;
. Keep in mind that updating a mesh collider is very slow, and not actually something you want to do in Update.