在xna中定位3d对象

时间:2010-07-11 14:26:20

标签: 3d xna cube primitive

我对xna开发很新,并希望通过将位置向量传递给构造函数来定位来自Primitives3D sample的Cubes。不幸的是它不起作用..相反它只是旋转arround .. < / p>

这就是我如何修改cubeprimitive类的代码:

  public class CubePrimitive : GeometricPrimitive
{
    public Vector3 position;

    /// <summary>
    /// Constructs a new cube primitive, using default settings.
    /// </summary>
    public CubePrimitive(GraphicsDevice graphicsDevice)
        : this(graphicsDevice, 1, new Vector3(-3,0,0))
    {
    }

    /// <summary>
    /// Constructs a new cube primitive, with the specified size.
    /// </summary>
    public CubePrimitive(GraphicsDevice graphicsDevice, float size, Vector3 posi)
    {
        this.position = posi;

        // A cube has six faces, each one pointing in a different direction.
        Vector3[] normals =
        {
            new Vector3(0, 0, 1),
            new Vector3(0, 0, -1),
            new Vector3(1, 0, 0),
            new Vector3(-1, 0, 0),
            new Vector3(0, 1, 0),
            new Vector3(0, -1, 0),
        };

        // Create each face in turn.
        foreach (Vector3 normal in normals)
        {
            // Get two vectors perpendicular to the face normal and to each other.
            Vector3 side1 = new Vector3(normal.Y, normal.Z, normal.X);
            Vector3 side2 = Vector3.Cross(normal, side1);

            // Six indices (two triangles) per face.
            AddIndex(CurrentVertex + 0);
            AddIndex(CurrentVertex + 1);
            AddIndex(CurrentVertex + 2);

            AddIndex(CurrentVertex + 0);
            AddIndex(CurrentVertex + 2);
            AddIndex(CurrentVertex + 3);

            // Four vertices per face.
            AddVertex(posi+(normal - side1 - side2) * size / 2, normal);
            AddVertex(posi + (normal - side1 + side2) * size / 2, normal);
            AddVertex(posi + (normal + side1 + side2) * size / 2, normal);
            AddVertex(posi + (normal + side1 - side2) * size / 2, normal);
        }

        InitializePrimitive(graphicsDevice);
    }
}

你能告诉我如何正确修改它吗? ..提前谢谢:)

1 个答案:

答案 0 :(得分:1)

传统上,当您想要移动模型时,您所做的是,而不是修改模型的每个顶点,而是更改World矩阵。

在Primitives3DGame.cs中找到这一行:

Matrix world = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll);

并将其更改为:

Matrix world = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll)
               * Matrix.CreateTranslation(-3, 0, 0);

(当然,请删除您在问题中发布的更改。)

据我所知,您的代码实际上正在运行。但也许你期望立方体旋转但保持在同一个地方(这就是上面的代码所做的)。你在做什么实际上与:

相同
Matrix world = Matrix.CreateTranslation(-3, 0, 0)
               * Matrix.CreateFromYawPitchRoll(yaw, pitch, roll);

请注意相反的顺序 - 您首先进行模型的转换,然后然后围绕原点进行旋转。