Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How rotate a 3D cube at its center XNA?

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. enter image description here

And i need this: enter image description here

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;
    }
like image 913
Mehdi Bugnard Avatar asked Feb 19 '13 16:02

Mehdi Bugnard


1 Answers

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.

three drawings showing a roataed cube from the top

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

Matrix transformation = Matrix.CreateTranslation(-rotationCenter)
    * Matrix.CreateScale(scaling) 
    * Matrix.CreateRotationY(rotation) 
    * Matrix.CreateTranslation(position);
like image 178
Lucius Avatar answered Oct 21 '22 05:10

Lucius