簡體   English   中英

在C#/ XNA中轉換3D基本體的正確方法?

[英]Proper way of transforming 3D primitives in C#/XNA?

我有一個Block類,該類基本上包含36個頂點的數組,一個構造器,該構造器圍繞原點(0、0、0)構建塊,以及一種用於更新的方法。

我正在使用物理庫來操作塊。 我為塊分配了一個身體和碰撞皮膚,並在每次更新時更新了物理步驟。 每次更新后,我都會得到一個包含塊的新位置,方向等的矩陣。

現在,我無法確定的最好方法是將矩陣應用於塊並在每幀有效地更新頂點緩沖區。

這基本上是我目前所擁有的,我幾乎肯定有更好的方法...

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

讓着色器執行此操作...着色器的參數之一通常是WorldMatrix ...

畫出來:

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

如果您在繪制塊時遇到問題,請嘗試自己創建一個世界變換矩陣並對其進行測試。

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

如果您有多個block實例,則可以使用實例化將vertexBuffer中的trasnform矩陣傳遞給着色器...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM