Generated Mesh is rotating twice in unity

36 Views Asked by At

i am working on a project on creating your own complex 3d models(like probuilder but like an application) but when i try to rotate my generated mesh by say 90° it actually gets rotated by 180°. i cant seem to figure out why?

enter image description here

90° enter image description here

i want it to be rotated by 90 degree but it actually gets rotated by 180 degree

when i replace the mesh with any other predefined mesh(cube or cylinder) its works fine. so i think the problem is when i created the mesh. Edit:- i have pinpointed the problem in this code.this code modifies the mesh vertices according to the gameobject vertices so that i can deform the face when i move the vertex

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DeformFace : MonoBehaviour
{
    public Face face;
    public List<Vertex> sharedVertices=new List<Vertex>();
    Mesh mesh;
    public List<Vector3> meshVertices=new List<Vector3>();
    private void Start()
    {
        sharedVertices=face.sharedVertices;
        for (int i = 0; i < sharedVertices.Count; i++)
        {
            meshVertices.Add(sharedVertices[i].transform.position);
        }
        mesh =GetComponent<MeshFilter>().mesh;
    }

    private void Update()
    {
        DeformingFace();
    }

    public void DeformingFace()
    {
        for (int i = 0; i < sharedVertices.Count; i++)
        {
            meshVertices[i] = sharedVertices[i].transform.position-transform.position;
        }
        mesh.vertices = meshVertices.ToArray();
    }
}
2

There are 2 best solutions below

0
Kanoto On

It does that with all kind of mesh ? (triangle, square, cube, ...)

The only thing I can think of is that you're deforming the same vertices multiple times.

0
derHugo On

From what I can tell the issue is in DeformingFace.

I just assume the objects that provide the vertex positions are children of this object you are rotating

=> As your child objects as well as the mesh itself are all affected by your rotation what happens is that your rotation is applied twice

  • You rotate the parent -> all children are affected by the rotation
  • You rotate the parent -> The mesh is transformed by this rotation

Have in mind that Mesh.vertices are always in local space and then the Transform is applied to them. But

meshVertices[i] = sharedVertices[i].transform.position - transform.position;

is still a world space vector not taking the orientation of this parent object into account.

You should rather convert them to local space and do e.g.

meshVertices[i] = transform.InverseTransformPoint(sharedVertices[i].transform.position);

or - again assuming these are children of this object anyway this should be equivalent

meshVertices[i] = sharedVertices[i].transform.localPosition;