This post is just a quick reminder to myself and for anyone else who’s brain seems to freeze when it comes to moving vertices / vector3 positions around in code for whatever reason without using a transform component, in this post i’m not going to write about any of the complexities or inner workings behind the readily available Unity3d Matrix functions, but the code below has proved usefull when writing import functions for 3d mesh/models. I’m sure there are quicker methods and i’d love to hear about them.
The code below takes a Vector3 (position.x,position.y,position.z) and translates, rotates and scales it according to your own input using a matrix (exactly like the Unity3d Transform in the inspector) you could run the code in a loop multiplying a sequence of vector3[] vertices through it and offset your mesh from its original (pivot point)/origin if you so wished. The code is a short example written in c#:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//original point Vector3 v=new Vector3(10,50,0); //Starting vector3 world position; //your transform data, currently set as no translate, no scale, no rotate Vector3 t=new Vector3(0,0,0); //translate point v by this; Vector3 s=new Vector3(1,1,1); //scale point v by this; Vector3 r=new Vector3(0,0,0); //rotate point v by this (degrees); Quaternion q=Quaternion.identity; //create zero rotation q; q.eulerAngles = r; //convert vector 3 degree rotation to quaternion; //Create a new transform matrix with the transform data we have set above; Matrix4x4 m= Matrix4x4.TRS(t,q,s); v=m.MultiplyPoint3x4(v); //get new position for v by muliplying by matrix; // or place in a for-loop and operate the transform on a number of vertices:- // v[i]=m.MultiplyPoint3x4(v[i]); |
aaaa m8 was looking everywhere for something like this!!!
nice work!!
i am sure that this is going to become an essencial little script for a lot of stuff
i write in javascript so here a translate version for anyone who needs it!
var v = Vector3(10,50,0);
var t = Vector3(0,0,0);
var s = Vector3(1,1,1);
var r = Vector3(0,0,0);
var q = Quaternion.identity;
q.eulerAngles = r;
var m= Matrix4x4.TRS(t,q,s);
v = m.MultiplyPoint3x4(v);