【问题标题】:How rotate a 3D cube at its center XNA?如何在其中心 XNA 旋转 3D 立方体?
【发布时间】:2013-02-04 10:01:01
【问题描述】:

我尝试从中心而不是边缘旋转 3D 立方体。 这是我使用的代码。

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


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

我的立方体可以很好地旋转,但不是从中心旋转。这是解释我的问题的示意图。

我需要这个:

我的完整代码

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

【问题讨论】:

  • 在应用缩放、旋转和平移之前,应用使立方体居中的平移Matrix.CreateTranslation(-h, -h, -h),其中h 是立方体边长的一半。

标签: c# matrix xna rotation transform


【解决方案1】:

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

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 位置随着循环的每次通过而减小。你有什么想法吗?
  • 好的,非常感谢您的帮助。我现在在描述中添加了我的完整功能代码。
  • 您正在重用前一帧的平移(和缩放)。通过这样做,翻译加起来,因此你的立方体在不应该移动的时候移动。我认为将旋转、缩放和平移存储为向量而不是矩阵会更有意义。调试起来会容易得多,而且您不会浪费任何计算来分解每个帧和立方体的矩阵。
  • 是的,谢谢大家!你说的对。再次感谢。现在一切正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 2012-05-13
  • 1970-01-01
相关资源
最近更新 更多