In my scene I have a plane with a sphere resting on it. I have the vertices changing colour as the sphere moves across the plane. As soon as I try to move the plane instead of moving the sphere it stops working (I need it this way for a different project). Even moving the plane a tiny amount stops the vertices changing colour. I suspect its something to do with the vertex locations being different when the plane is moved. Heres the code I’m using:
using UnityEngine;
using System.Collections;
//[ExecuteInEditMode]
public class Plane : MonoBehaviour {
public Vector3 contactPoint;
public Vector3 nearestVert;
float h, v;
Mesh mesh;
Vector3[] verts;
Vector3 vertPos;
Color[] colors;
// Use this for initialization
void Start () {
mesh = GetComponent<MeshFilter>().mesh;
}
// Update is called once per frame
void Update () {
verts = mesh.vertices;
colors = mesh.colors;
//v = Input.GetAxis("Vertical");
//h = Input.GetAxis("Horizontal");
//transform.Translate(h*0.2f, 0, v*0.2f);
nearestVert = NearestVertexTo(contactPoint);
Debug.Log("NearestVert: " + nearestVert);
for( int i = 0; i < verts.Length; i++)
{
if(verts *== nearestVert)*
-
{* -
Debug.Log("Collision Yo");*
_ colors = Color.red;_
* }*
* }*
* mesh.colors = colors;*
* mesh.vertices = verts;*
* mesh.RecalculateBounds();*
* mesh.RecalculateNormals();*
* }*
* public Vector3 NearestVertexTo(Vector3 point)*
* {*
* // convert point to local space*
* point = transform.InverseTransformPoint(point);*
* float minDistanceSqr = Mathf.Infinity;*
* Vector3 nearestVertex = Vector3.zero;*
* // scan all vertices to find nearest*
* foreach (Vector3 vertex in mesh.vertices)*
* {*
* Vector3 diff = point-vertex;*
* float distSqr = diff.sqrMagnitude;*
* if (distSqr < minDistanceSqr)*
* {*
* minDistanceSqr = distSqr;*
* nearestVertex = vertex;*
* }*
* }*
* // convert nearest vertex back to world space*
* return transform.TransformPoint(nearestVertex);*
* }*
* void OnCollisionStay(Collision collision) {*
* foreach (ContactPoint contact in collision.contacts) {*
* Debug.DrawRay(contact.point, Vector3.up, Color.green, 4, false);*
* contactPoint = contact.point;*
* }*
* }*
}
Any pointers on how I could move forward from here? What I need is the plane to move, the sphere to be stationary and the vertices to still change colour.
Thanks