- Home /
Question by
Chocolade · Apr 11, 2017 at 02:56 PM ·
c#scripting problemscript.
How can i change vertex posiiton to push it back -1 on z ?
This is how i find the vertex
int findVertex(Vector3 v)
{
Vector3[] vertices = transform.GetComponent<MeshFilter>().mesh.vertices;
for(int i = 0; i < vertices.Length; i++)
{
if (vertices[i] == v)
{
return i;
}
}
return -1;
}
Then onmousedown
void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 1000.0f))
{
int[] triangles = transform.GetComponent<MeshFilter>().mesh.triangles;
if (hit.triangleIndex != -1 && (hit.triangleIndex * 3) < triangles.Length)
{
int hitTri = hit.triangleIndex;
//get neighbour
Vector3[] vertices = transform.GetComponent<MeshFilter>().mesh.vertices;
Vector3 p0 = vertices[triangles[hitTri * 3 + 0]];
Vector3 p1 = vertices[triangles[hitTri * 3 + 1]];
Vector3 p2 = vertices[triangles[hitTri * 3 + 2]];
float edge1 = Vector3.Distance(p0, p1);
float edge2 = Vector3.Distance(p0, p2);
float edge3 = Vector3.Distance(p1, p2);
Vector3 shared1;
Vector3 shared2;
if (edge1 > edge2 && edge1 > edge3)
{
shared1 = p0;
shared2 = p1;
}
else if (edge2 > edge1 && edge2 > edge3)
{
shared1 = p0;
shared2 = p2;
}
else
{
shared1 = p1;
shared2 = p2;
}
v1 = findVertex(shared1);
v2 = findVertex(shared2);
changeVertexPosition(v1);
changeVertexPosition(v2);
}
}
}
}
And changeVertexPosition
void changeVertexPosition(int index)
{
Mesh mesh = transform.GetComponent<MeshFilter>().mesh;
mesh.vertices[index].z = -10;
transform.GetComponent<MeshFilter>().mesh.vertices[index] = new Vector3(0, 0, -10);
}
First i tried only mesh.vertices[index].z = -10; but it didn't change anything so i tried transform.GetComponent().mesh.vertices[index] = new Vector3(0, 0, -10); but didn't change anything else either.
Comment
Answer by danmw3 · Apr 11, 2017 at 03:06 PM
I would suggest passing in the current x and y values of the vertex when creating the new Vector3
mesh.vertices[index] = new Vector3(mesh.vertices[index].x, mesh.vertices[index].y, mesh.vertices[index].z);
If that continues to not work look into passing the method parameters by reference. For information on passing by reference and how it works refer to the link below.
https://msdn.microsoft.com/en-us/library/14akc2c7(v=vs.140).aspx