2013-02-19 48 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