Using matrices to perform translations/rotations

I’m having a bit of a problem using matrices to translate or rotate a point in 3D space, I’ve done this in maths before and the matrix I’m using should translate my point (newPos) by a set amount but basically it doesn’t! Depending on whether I use MultiplyPoint or MultiplyPoint3x4 I either get a zero vector or the same vector I started with :?:

Can anyone help here? My code (javascript) is:

var newPos = Vector3(sledX, 2.5, sledZ);

//1st translate to origin
var trans : Matrix4x4 = Matrix4x4.identity;
trans[3,0] = (-onTrack.transform.position.x);
trans[3,2] = (-onTrack.transform.position.z);

newPos = trans.MultiplyPoint3x4(newPos);

If this isn’t going to work, then I need an alternate way of rotating a point around the y-axis of a different point by X degrees, if anyone could suggest one?

Cheers

Matrices are column based not row based in unity. Threw me at first too.

Check out Transform.RotateAround as well as the other transform functions, will save you hassle.

cheers,
grant

according to the reference:
Matrix4x4 [int row, int column] : Access element at [row, column].

This implies that you place your translation in row 3, columns 0 and 2. That’s normally the projection part of a 4x4 matrix. Without having tested anything, I think using trans[0,3] and trans[2,3] instead should fix it.

Anyway, whether that fixes it or not, is there a particular reason you cannot add a child transform ‘Rotator’ to onTrack (that performs the rotation) and yet another child ‘Orbit’ to ‘Rotator’ that contains the translation? Anything placed inside the ‘Orbit’ transform would then rotate around onTrack. That would eliminate the need for matrix calculus altogether. Anyway, I’m not sure what you’re trying to accomplish, so it may not be a solution.

Ah, that’ll be why my matrices aren’t working then! Right, I’ll give it another try that way.

As for the Transform.RotateAround, that would have worked fantastically but I need to rotate a Vector3 rather than a Transform so it didn’t help :frowning: Is there any way to do this?

Thanks for your help though!

Never mind, I managed to fix the matrices :smile: happy

The above replies are correct in that translation in Unity’s Matrix4x4 is set in column 3, not row 3. There are a number of other ways to do this besides setting the matrix values manually, though.

You could use Matrix.TRS to create a translation, rotation, scale matrix in one go, for example.

You can also rotate a transform around an arbitrary point with Transform.RotateAround. This is a very quick way to do the type of rotation you mentioned, and if you intend to be applying your calculated vector to a transform anyway it’s probably the easiest.

If you’re moving vertices around in a mesh, however, it’s probably best to stick with the Matrix4x4, since creating a dummy transform to calculate the positions of multiple vertices would be kind of silly.

Edit: Doh! Reply too late, nothing new added.