I’m attempting to create a mesh deformation script. My approach to this is to access each vertice in an object and then move it a certain amount based off its distance from the colliding object and the direction its being hit from. This is what I tried (the script is on the projectile that is supposed to be deforming the mesh that its hitting):
void OnCollisionEnter (Collision collision) {
Mesh mesh = collision.transform.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
int i = 0;
while (i < vertices.Length) {
float distance = Vector3.Distance(vertices*, collision.transform.position);*
-
if(distance > hitRadius) return;*
-
float vertMove = distance/hitRadius;*
-
Vector3 localDirection = transform.position - collision.transform.position;*
vertices += (localDirection * vertMove);
* i++;*
* }*
* mesh.vertices = vertices;*
* mesh.RecalculateBounds();*
* }*
The problem is that it doesn’t do anything until the hitRadius is larger than the object, and then on collision, it moves the whole object. What am I doing wrong here?
EDIT
Okay so after doing some research on the forums, BigMisterB wrote this script (corrected by me):
using UnityEngine;
using System.Collections;
public class MeshDeform : MonoBehaviour {
* public Vector3 relativeVelocity;*
* void Update () {*
_ transform.Translate(relativeVelocity * Time.deltaTime);_
* }*
* void OnCollisionEnter (Collision collision) {*
* MeshFilter mf = collision.collider.GetComponent();*
* Mesh mesh = mf.mesh;*
* Vector3[] vertices = mesh.vertices;*
* Vector3 hitPoint = transform.InverseTransformPoint(collision.contacts[0].point);*
* float hitRadius = relativeVelocity.magnitude;*
* Vector3 hitDir = transform.InverseTransformDirection(-collision.contacts[0].normal);*
* int i = 0;*
* while (i < vertices.Length) {*
_ float distance = Vector3.Distance(vertices*, hitPoint);
Vector3 dir = (vertices - hitPoint);
if(dir.magnitude < hitRadius){
float amount = 1 - dir.magnitude / hitRadius;
Vector3 vertMove = hitDir * amount;
vertices += vertMove;
}
i++;
}*_
* mesh.vertices = vertices;*
* mesh.RecalculateBounds();*
* }*
}
So the script works now, but unfortunately the wrong vertices are being affected. For some reason, when I hit the object, the vertices completely opposite of the vertices that are hit are affected. Any ideas why that happens?