2013-02-19 75 views
3

我尝试从其中心旋转3D立方体,而不是边缘。 这是我使用的代码。如何在其中心的XNA上旋转3D立方体?

public rotatemyCube() 
{ 
    ... 
    Matrix newTransform = Matrix.CreateScale(scale) * Matrix.CreateRotationY(rotationLoot) * Matrix.CreateTranslation(translation); 
    my3Dcube.Transform = newTransform; 
    .... 


public void updateRotateCube() 
{ 
    rotationLoot += 0.01f; 
} 

我的立方体旋转正常,但不是从中心旋转。这是解释我的问题的示意图。 enter image description here

,我需要这样的: enter image description here

我的完整代码

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; 
    } 
+1

之前申请的缩放,旋转和平移应用该中心立方体'Matrix.CreateTranslation翻译(-h,-H,-h)''那里是h'半立方体边长。 – Lucius 2013-02-19 17:27:22

回答

6

旋转矩阵绕坐标系的原点顶点。为了围绕某个点旋转,您必须将其作为原点。这可以通过简单地从形状中的每个顶点减去旋转点来完成。

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); 
+0

非常感谢您的宝贵帮助!但是现在我的魔方转身落下。随着环路的每次通过,立方体的Y位置都会减小。你有什么想法吗? – 2013-02-19 20:54:18

+0

恐怕我没有看到你的代码就看不出来。 – Lucius 2013-02-19 20:58:46

+0

好的,谢谢你的帮助。我现在在描述中添加了我的完整功能代码。 – 2013-02-19 21:05:13