【问题标题】:Xna SpriteBatch Matrix.Decompose()Xna SpriteBatch Matrix.Decompose()
【发布时间】:2010-02-26 08:23:50
【问题描述】:

我想做的是能够将变换矩阵推送和弹出到 SpriteBatch 中。我有 2 个精灵,父母和孩子,孩子应该相对于父母进行缩放、旋转和平移。

我目前有一个使用纹理四边形的实现,但我认为这应该可以使用内置的 SpriteBatch 类和使用 Matrix.Decompose()。不过,我不确定如何将分解后的值传递给 SpriteBatch。

我了解如何保留矩阵堆栈,我只是在寻找一个将来自 Matrix.Decompose() 的值与 SpriteBatch 结合使用的示例。

【问题讨论】:

    标签: xna 2d


    【解决方案1】:

    我自己终于想出了这个。不过大部分功劳都属于这个blog post

    你可以使用这个方法来分解你的矩阵:

    private void DecomposeMatrix(ref Matrix matrix, out Vector2 position, out float rotation, out Vector2 scale)
    {
        Vector3 position3, scale3;
        Quaternion rotationQ;
    
        matrix.Decompose(out scale3, out rotationQ, out position3);
    
        Vector2 direction = Vector2.Transform(Vector2.UnitX, rotationQ);
        rotation = (float)Math.Atan2((double)(direction.Y), (double)(direction.X));
        position = new Vector2(position3.X, position3.Y);
        scale = new Vector2(scale3.X, scale3.Y);
    }
    

    然后您可以像这样为您的叶子精灵构建一个变换矩阵:

    Matrix transform = 
        Matrix.CreateScale(new Vector3(this.Scale, 1.0f)) *
        Matrix.CreateRotationZ(this.Rotation) *
        Matrix.CreateTranslation(new Vector3(this.Position, 0));
    

    对于你的父精灵,包括原点:

    Matrix transform = 
        Matrix.CreateTranslation(new Vector3(-this.Origin, 0)) *
        Matrix.CreateScale(new Vector3(this.Scale, 1.0f)) *
        Matrix.CreateRotationZ(this.Rotation) *
        Matrix.CreateTranslation(new Vector3(this.position, 0));
    

    以相反的顺序乘以堆栈中的所有矩阵。

    【讨论】:

    • 我一直在寻找如何从变换矩阵的四元数到 SpriteBatch 可以使用的浮点数,这绝对是它。对于任何来这里的人,您会注意到 matrix.Decompose(...) 返回一个布尔值。我不建议将它放在 if 语句中。无论对我来说,它似乎都返回 false,但仍然输出正确的比例、旋转和位置值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多