using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class MeshDeformer : MonoBehaviour
{
public MeshFilter meshFilter;
private Mesh mesh;
public GameObject nearest, contactPoint;
MeshCollider meshCollider;
void Start()
{
meshFilter = GetComponent<MeshFilter>();
mesh = meshFilter.mesh;
meshCollider = GetComponent<MeshCollider>();
}
void OnCollisionEnter(Collision col)
{
deformMesh(col);
}
void deformMesh(Collision collision)
{
bool[] isProcessed = new bool[mesh.vertexCount];
Vector3[] tempVerticies = new Vector3[mesh.vertexCount];
tempVerticies = mesh.vertices;
ContactPoint[] contacts = collision.contacts;
string collidingVertexes = "";
foreach (ContactPoint c in contacts)
{
Vector3 localpoint = contactPoint.transform.InverseTransformPoint(c.point);
int nearestVertexId = getNearestVertexId(localpoint);
if (!isProcessed[nearestVertexId])
{
isProcessed[nearestVertexId] = true;
collidingVertexes += nearestVertexId + ";";
tempVerticies[nearestVertexId] += contactPoint.transform.InverseTransformDirection(collision.relativeVelocity.normalized)/50;
}
}
Debug.Log("Colliding vertexId: "+ collidingVertexes);
mesh.vertices = tempVerticies;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
meshFilter.sharedMesh = mesh;
meshCollider.sharedMesh = null;
meshCollider.sharedMesh = mesh;
}
int getNearestVertexId(Vector3 point)
{
float min = Mathf.Infinity;
int minId = -1;
for (int i = 0; i < mesh.vertexCount; i++)
{
float dist = (point - mesh.vertices[i]).magnitude;
if (dist < min)
{
min = dist;
minId = i;
}
}
return minId;
}
}
What's wrong? I want all verticies connected.
I didn't notice any changes after
mesh.RecalculateNormals();
mesh.RecalculateBounds();
It looks like triangle map is going wrong? I tryied to update triangle map in the end of function, but had no effect. I think I don't understand some base principles of mesh edditing and make this mistake