如何在XNA中以其中心旋转3D立方体?

5

我尝试从中心而不是边缘旋转一个三维立方体。 这是我使用的代码。

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
1个回答

8

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

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

非常感谢您的宝贵帮助!但是现在我的立方体旋转并掉落了。每次循环时,立方体的Y位置都会减少。您有什么想法吗? - Mehdi Bugnard
好的,非常感谢您的帮助。我现在已经在描述中添加了完整的函数代码。 - Mehdi Bugnard
1
你正在重复使用前一帧的翻译(和缩放)。这样做会导致翻译累加,从而使你的立方体在不应该移动时移动。我认为将旋转、缩放和平移存储为向量而不是矩阵更有意义。这样做将更容易调试,并且您不会浪费任何计算来分解每个帧和立方体的矩阵。 - Lucius
谢谢你的所有帮助!你是对的。再次感谢。现在一切都正常了。 - Mehdi Bugnard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接