- Home /
Trouble with positions of vertices
So I scripted a mesh, which looks like this:
(Yellow spheres are the vertices)(I named it "Ground")
I only need the drawn upside part of the mesh for this question
I also added a mesh collider to it and then created a new gameobject with a rigidbody attached to it.
They collide fine
I want to create a new vertex at exactly the position where they collided. So I used the OnCollisionStay()
function:
void OnCollisionStay(Collision collision)
{
ContactPoint contact = collision.contacts[0];
if (contact.otherCollider.name == "Ground")
{
//Process of collision vertex creation
newVertices = new Vector3[mesh.vertexCount + 1];
for (int i = 0; i < mesh.vertexCount; i++)
{
newVertices[i] = mesh.vertices[i];
}
//sets the position of the new vertex
newVertices[mesh.vertexCount] = contact.point;
//applies changes
mesh.vertices = newVertices;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
}
}
But I can't seem to get what I did wrong
Instead of creating the vertex exactly where the collision happened, they spawn in wrong places. (See below)
My guess is, that it has to do with the local and world spaces. I already tried different ways like using the transform.TransformPoint()
and similar to convert the contact point I created to relevant coordinates, but nothing.
What did I do wrong? Can you help me?
Answer by Bunny83 · Apr 17, 2017 at 09:52 PM
Vertex positions are defined in local space of the object while a hit point is a worldspace position. In order to use the hit point as vertex position you have to transform the worldspace position into localspace. This is done by using "InverseTransformPoint" of the transform of your mesh object.
Note that the hit point doesn't need to be at the exact vertex position of the other mesh. Mesh colliders could collide edge on edge or vertex on surface. We don't know for what purpose you need those points but keep that in mind.
edit
Also note that you can't change a MeshCollider mesh "on the fly". You either have to destroy and reattach a MeshCollider component in order to update the actual collider, or set it's sharedMesh first to null and then back to your mesh. At least that used to work.
InverseTransformPoint was the function I needed. I will also keep in $$anonymous$$d, that I have to update my $$anonymous$$eshColliders. Thank you very much
Your answer
Follow this Question
Related Questions
Unity 2d position of squares in different units than size. 0 Answers
Multiple Cars not working 1 Answer
Locations not registering as equal 1 Answer
Distribute terrain in zones 3 Answers