You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XNA/Monogame中如何实现Matrix与Vector4相乘?

在XNA/Monogame中实现Matrix与Vector4相乘的解决方案

XNA/Monogame的Matrix类默认没有提供直接与Vector4相乘的*操作符,这就是你代码报错的原因,不需要完全从零编写相乘逻辑,可以用以下两种方式解决:

  • 使用官方提供的Matrix.Transform方法
    这个方法专门用于将矩阵变换应用到向量上,支持Vector4,注意参数顺序是向量在前、矩阵在后,对应矩阵乘向量的运算逻辑:

    Matrix a = Matrix.Identity;
    Vector4 b = Vector4.Zero;
    b = Matrix.Transform(b, a);
    
  • 自定义扩展方法重载*操作符
    如果你习惯用*符号的写法,可以写一个扩展类实现操作符重载,这样就能像你最初写的那样使用a*b:

    public static class MatrixVector4Extensions
    {
        public static Vector4 operator *(Matrix matrix, Vector4 vector)
        {
            return new Vector4(
                matrix.M11 * vector.X + matrix.M12 * vector.Y + matrix.M13 * vector.Z + matrix.M14 * vector.W,
                matrix.M21 * vector.X + matrix.M22 * vector.Y + matrix.M23 * vector.Z + matrix.M24 * vector.W,
                matrix.M31 * vector.X + matrix.M32 * vector.Y + matrix.M33 * vector.Z + matrix.M34 * vector.W,
                matrix.M41 * vector.X + matrix.M42 * vector.Y + matrix.M43 * vector.Z + matrix.M44 * vector.W
            );
        }
    }
    

    引入这个扩展类后,你最初的代码就能正常运行。

内容的提问来源于stack exchange,提问作者Gaming Gecko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 22:37:07