围绕其自身轴旋转3D基元

时间:2013-08-26 14:24:09

标签: c# matrix 3d xna transformation

几天后,我一直在XNA开展一个项目。该应用程序的主要思想是有一个平面彩色瓷砖网格,可单独翻转。我遇到的问题是我无法弄清楚如何围绕瓷砖单独的中心轴进行翻转旋转。

现在发生的事情是,瓷砖围绕世界轴而不是自己的轴旋转。

每个图块由一组顶点组成,这些顶点在3D世界中创建一个二维正方形。

我很确定这个问题与我弄乱矩阵有关。

以下是每个瓷砖的代码:

public Tile(Vector3 position, int size, Matrix world)
    {
        this.position = position;
        this.size = size;
        this.world = world;

        vertices = new VertexPositionColor[6];

        for (int i = 0; i < vertices.Length; i++)
            vertices[i].Position = position;

        vertices[0].Position += new Vector3(0, 0, 0);
        vertices[0].Color = Color.Pink;
        vertices[1].Position += new Vector3(0, size, 0);
        vertices[1].Color = Color.Yellow;
        vertices[2].Position += new Vector3(0, size, size);
        vertices[2].Color = Color.Green;

        vertices[3].Position += new Vector3(0, size, size);
        vertices[3].Color = Color.Green;
        vertices[4].Position += new Vector3(0, 0f, size);
        vertices[4].Color = Color.Blue;
        vertices[5].Position += new Vector3(0, 0, 0);
        vertices[5].Color = Color.Blue;
    }

    public VertexPositionColor[] Vertices
    {
        get{ return Functions.TransformVertices((VertexPositionColor[])vertices.Clone(), GetMatrix()); }
    }

    private Matrix GetMatrix()
    {
        return Matrix.CreateRotationZ(rot);
    }


    private void TransformVertices(Matrix matrix)
    {
        for (int i = 0; i < vertices.Length; i++)
            vertices[i].Position = Vector3.Transform(vertices[i].Position, matrix);
    }

这是绘图方法:

protected override void Draw( GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        RasterizerState rasterizerState = new RasterizerState();
        rasterizerState.CullMode = CullMode.None;
        GraphicsDevice.RasterizerState = rasterizerState;
        viewMatrix = Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 0), Vector3.Up);

        effect.CurrentTechnique = effect.Techniques["ColoredNoShading"];
        effect.Parameters["xView"].SetValue(viewMatrix);
        effect.Parameters["xProjection"].SetValue(projectionMatrix);

        Vector3 rotAxis = new Vector3(0, 0, 1);
        rotAxis.Normalize();
        worldMatrix = Matrix.Identity;
        effect.Parameters["xWorld"].SetValue(worldMatrix);

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();

            foreach(Tile tile in tiles)
                GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, tile.Vertices, 0, 2, VertexPositionColor.VertexDeclaration);
        }

        base.Draw(gameTime);
    }

如果有帮助我可以发给你整个来源。任何帮助都是无价的!

1 个答案:

答案 0 :(得分:6)

围绕自己的轴旋转平铺:

(1) Transform the tile back to the origin.
(2) Perform rotation.
(3) Transform back to original position.