[resolved] How to use Matrix4x4.TRS to rotate vertices?

Hi,

I want to rotate all the vertices of a mesh so that it is always looking at another object.
I believe its possible, but I am not sure how to use Matrix4x4.TRS to rotate the vertices.

I have my vertices, a vector to look at, how do I apply this to the matrix? I am not sure what the
Quaternion rotation should be to define the rotation.

i am coding in C# by the way.
Thanks in advance.

Multiply vertices by object space rotation matrix.
This is an example how manipulate mesh`s vertices and normals.

Add this script to empty GO, select Look at Target and source mesh.

using UnityEngine;

[ExecuteInEditMode]
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]

public class RotateVertices : MonoBehaviour {

    Mesh prevSourceMesh = null;
    public Mesh SourceMesh;

    Mesh m;
    Vector3[] sourceVertices;
    Vector3[] sourceNormals;
    Vector3[] mVertices;
    Vector3[] mNormals;


    void SetMesh() {
        sourceVertices = SourceMesh.vertices;
        sourceNormals = SourceMesh.normals;
        mVertices = new Vector3[sourceVertices.Length];
        mNormals = new Vector3[sourceVertices.Length];
        m = Instantiate(SourceMesh) as Mesh;
        GetComponent<MeshFilter>().sharedMesh = m;
    }


    public Transform LookAtTarget;
  
    // Update is called once per frame
    void Update () {
        if (SourceMesh != prevSourceMesh) {
            prevSourceMesh = SourceMesh;
            SetMesh();
        }

        if (LookAtTarget == null  ) {
            return;
        }

        Vector3 dirToTarget = LookAtTarget.position - transform.position;
        Matrix4x4 worldRotation = Matrix4x4.TRS(transform.position, Quaternion.LookRotation(dirToTarget, transform.up), Vector3.one);
        Matrix4x4 objSpaceRotation = transform.worldToLocalMatrix * worldRotation;

        for (int v = 0; v<mVertices.Length; v++) {
            mVertices[v] = objSpaceRotation.MultiplyPoint3x4(sourceVertices[v]);
            mNormals[v] = objSpaceRotation.MultiplyVector(sourceNormals[v]);
        }
        m.vertices = mVertices;
        m.normals = mNormals;
        m.RecalculateTangents();
        m.RecalculateBounds();

        Debug.DrawLine(transform.position, LookAtTarget.position, Color.blue);
    }
}
3 Likes