Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void CreateMeshCollider(){
- meshCollider = new Mesh();
- List<PosIndPolygon> posInPolygon = new List<PosIndPolygon>();
- List<int> triIndex = new List<int>();
- //In the next loop we use shoelace formula to know the orientation of the polygon
- //https://en.wikipedia.org/wiki/Shoelace_formula
- float s = 0f;
- for(int i=0;i<verts.Length-1;i++){
- PosIndPolygon aux;
- aux.pos = verts[i];
- aux.ind = i;
- posInPolygon.Add(aux);
- s+=verts[i].x*(verts[(i+1)%(verts.Length-1)].z-verts[(i-1+verts.Length-1)%(verts.Length-1)].z);
- }
- while(posInPolygon.Count>threshold){
- int k = Random.Range(0,posInPolygon.Count);
- bool triangleObtained = false;
- while(!triangleObtained){
- int ind1 = (k-(int)Mathf.Sign(s)*1+posInPolygon.Count)%posInPolygon.Count;
- int ind2 = (k+posInPolygon.Count)%posInPolygon.Count;
- int ind3 = (k+(int)Mathf.Sign(s)*1+posInPolygon.Count)%posInPolygon.Count;
- //Asumimos que los vectores se encuentran en el plano XZ
- Vector3 v1 = posInPolygon[ind2].pos-posInPolygon[ind1].pos;
- Vector3 v2 = posInPolygon[ind3].pos-posInPolygon[ind2].pos;
- float f = Mathf.Atan2(v2.z,v2.x)-Mathf.Atan2(v1.z,v1.x);
- if(f<0f) f+= 2F*Mathf.PI;
- triangleObtained = true;
- if(f<=Mathf.PI && f>0f){
- for(int i=0;i<posInPolygon.Count;i++){
- if(i!=ind1 && i!=ind2 && i!=ind3){
- if(CheckIfPointInTriangle(posInPolygon[ind1].pos,posInPolygon[ind2].pos,posInPolygon[ind3].pos,posInPolygon[i].pos)){
- triangleObtained = false;
- break;
- }
- }
- }
- }else{
- triangleObtained = false;
- }
- if(triangleObtained){
- triIndex.Add(posInPolygon[ind1].ind);
- triIndex.Add(posInPolygon[ind2].ind);
- triIndex.Add(posInPolygon[ind3].ind);
- posInPolygon.RemoveAt(ind2);
- }else{
- k++;
- k%=posInPolygon.Count;
- }
- }
- }
- meshCollider.vertices = verts;
- meshCollider.SetIndices(triIndex.ToArray(),MeshTopology.Triangles,0);
- collider.sharedMesh = meshCollider;
- }
- //https://blogs.msdn.microsoft.com/rezanour/2011/08/07/barycentric-coordinates-and-point-in-triangle-tests/
- public bool CheckIfPointInTriangle(Vector3 A, Vector3 B, Vector3 C, Vector3 P)
- {
- // Prepare our barycentric variables
- Vector3 u = B-A;
- Vector3 v = C-A;
- Vector3 w = P-A;
- Vector3 vCrossW = Vector3.Cross(v, w);
- Vector3 vCrossU = Vector3.Cross(v, u);
- // Test sign of r
- if (Vector3.Dot(vCrossW, vCrossU) < 0)
- return false;
- Vector3 uCrossW = Vector3.Cross(u, w);
- Vector3 uCrossV = Vector3.Cross(u, v);
- // Test sign of t
- if (Vector3.Dot(uCrossW, uCrossV) < 0)
- return false;
- // At this point, we know that r and t and both > 0.
- // Therefore, as long as their sum is <= 1, each must be less <= 1
- float denom = uCrossV.magnitude;
- float r = vCrossW.magnitude / denom;
- float t = uCrossW.magnitude / denom;
- return (r + t <= 1);
- }
Advertisement
Add Comment
Please, Sign In to add comment