How rotate a 3D cube at its center XNA?

c#, matrix, rotation, transform, xna

Solution

A rotation matrix rotates vertices around the origin of the coordinate system. In order to rotate around a certain point you have to make it the origin. This can be done by simply subtracting the rotation point from every vertex in the shape.

var rotationCenter = new Vector3(0.5f, 0.5f, 0.5f);

Matrix transformation = Matrix.CreateTranslation(-rotationCenter)
    * Matrix.CreateScale(scaling) 
    * Matrix.CreateRotationY(rotation) 
    * Matrix.CreateTranslation(position);

Problem

I try to rotate a 3D cube on itself from its center, not the edge. Here is my code used. ``` public rotatemyCube() { ... Matrix newTransform = Matrix.CreateScale(scale) * Matrix.CreateRotationY(rotationLoot) * Matrix.CreateTranslation(translation); my3Dcube.Transform = newTransform; .... public void updateRotateCube() { rotationLoot += 0.01f; } ``` My cube rotate fine, but not from the center. Here is a schematic that explains my problem. And i need this: my complete code ``` private void updateMatriceCubeToRotate() { foreach (List<instancedModel> ListInstance in listStructureInstance) { foreach (instancedModel instanceLoot in ListInstance) { if (my3Dcube.IsAloot) { Vector3 scale; Quaternion rotation; Vector3 translation; //I get the position, rotation, scale of my cube my3Dcube.Transform.Decompose(out scale,out rotation,out translation); var rotationCenter = new Vector3(0.1f, 0.1f, 0.1f); //Create new transformation with new rotation Matrix transformation = Matrix.CreateTranslation(- rotationCenter) * Matrix.CreateScale(scale) * Matrix.CreateRotationY(rotationLoot) * Matrix.CreateTranslation( translation); my3Dcube.Transform = transformation; } } } //Incremente rotation rotationLoot += 0.05f; } ```

Original source