在C#/ XNA中转换3D基元的正确方法?

时间:2012-06-04 13:43:24

标签: c# 3d matrix xna

我有一个Block类,它基本上包含一个包含36个顶点的数组,一个围绕原点(0,0,0)构建块的构造函数,以及一个用于更新的方法。

我正在使用物理库来操纵块。我为块分配了一个body和碰撞皮肤,并在每次更新时更新物理步骤。每次更新后,我都会得到一个带有块的新位置,方向等的矩阵

现在,我无法解决的问题是将矩阵应用于块并有效地每帧更新顶点缓冲区的最佳方法。

这基本上就是我现在所拥有的,我几乎肯定有更好的方法......

class Block
{
    const float FullBlockSize = 20f;
    const float HalfBlockSize = FullBlockSize / 2;

    public VertexPositionNormalTexture [] vertices = new VertexPositionNormalTexture[36];
    public VertexPositionNormalTexture [] currentVertices = new VertexPositionNormalTexture[36];
    public DynamicVertexBuffer vBuffer;

    Vector3 position;

    public Block(Vector3 blockPosition)
    {
        position = blockPosition * FullBlockSize;

        /*
         * Build the 6 faces of the block here.
         * The block is built around the origin,
         * (0, 0, 0) being the center of the block.
        */

        vBuffer = new DynamicVertexBuffer(Game.Device, VertexPositionNormalTexture.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
        vBuffer.SetData(vertices);
    }
    public Matrix WorldMatrix
    {
        get
        {
            return Matrix.CreateTranslation(position);
        }
    }
    public void Update()
    {
        currentVertices = (VertexPositionNormalTexture[])vertices.Clone();
        Matrix currentWorld = WorldMatrix;
        for(int i = 0; i < currentVertices.Length; ++i)
        {
            currentVertices[i].Position = Vector3.Transform(currentVertices[i].Position, currentWorld);
        }
        vBuffer.SetData(currentVertices);
    }
}

1 个答案:

答案 0 :(得分:1)

让着色器执行此操作...着色器的其中一个参数通常是WorldMatrix ......

绘制它:

effect.Parameters["WorldMatrix"].SetValue(World);
effect.Apply(0);

如果你在绘制块时遇到问题...尝试自己创建一个世界变换矩阵并测试它......

effect.Parameters["WorldMatrix"].SetValue(Matrix.CreateRotationZ(angle));
effect.Apply(0);

如果您有多个块实例,可以使用实例化将vertexBuffer中的trasnform矩阵传递给着色器...

您可以在此处找到有关实例化的信息:http://blogs.msdn.com/b/shawnhar/archive/2010/06/17/drawinstancedprimitives-in-xna-game-studio-4-0.aspx