- Home /
distance between raycast hit and vertex
I am trying to find the distance between a raycast hit point and vertices on a mesh. When I click the mouse button my character sends out a raycast which hits an object, once this happens I put the vertices in the object into a list. Now I want to find the distance between each vertex and the hit.point of the raycast.
Code:
using UnityEngine;
using System.Collections;
public class DistanceTest : MonoBehaviour {
RaycastHit hit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if(Input.GetMouseButtonDown(0)){
if (Physics.Raycast(transform.position, fwd, out hit, 100.0F)) {
distance();
}
}
}
void distance(){
MeshFilter mf = hit.collider.GetComponent<MeshFilter>();
Mesh mesh = mf.mesh;
Vector3[] vertices = mesh.vertices;
print(vertices.Length);
int i = 0;
while(i < vertices.Length){
print(Vector3.Distance(transform.InverseTransformPoint(vertices[i]), transform.InverseTransformPoint(hit.point)));
i++;
}
}
}
So? What's your question? You get an error message? Something doesn't work?
it reports that the distance between the hit point and the object is over 1000 meters while the actual distance is no more than 10 meters. it seems to think that the vertices are around the middle of the scene whereas they are not.
Answer by Nimred · Oct 25, 2015 at 02:07 PM
The vertices would be stored in local space, not world space. You should either use InverseTransformPoint on the hit point but not the vertex, to compare positions in local space; Or use TransformPoint on the vertex but not the hit point to compare positions in world space.
This partially works, but the distance is 3 to 5 meters away, when it should range from 0 to 10.
Ah, I notice that you are also using "transform" with InverseTransformPoint. However, you should be converting to the local space of the object you hit, not the local space of your script object. Therefore, use hit.collider.transform ins$$anonymous$$d of just transform.
If this still does not work, please post the updated code so we can see what's wrong.