我开始使用XNA并尝试访问for循环中的字段(M11,M21等),如下所示。
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++)
{
// Can't use array notation with this struct. Doesn't work.
matrix[x][y]
// Similar to above, but like a 2D array. Doesn't work either.
matrix[x, y]
// ERROR - I'm using a variable like a method. Doesn't work.
matrix(x, y)
}
}
所以,我知道在这之后我会踢自己,但请告诉我如何访问XNA矩阵的各个字段,以便用for循环遍历它们。如果我能用C ++做到这一点,为什么不用C#?
这是Frank Luna在矩阵章节中使用DirectX 11进行“3D游戏编程”的一个例子,我想了解更多关于矩阵的内容,所以我希望能够做到这一点。与此同时,我会把它全部写出来,从M11 ...... M44开始。
答案 0 :(得分:1)
正如其他人已经指出的那样,没有内置的方法来通过坐标访问矩阵的字段。在非人为的情景中,这不是你经常需要做的事情,而且直接访问这些字段理论上更快(而且框架的矩阵代码就是这种微优化的地方)可能很重要。)
那就是说,如果我在编写代码以支持这种行为时,它可能看起来非常类似于此:
public static class MatrixUtil
{
public static void Set(ref Matrix m, Int32 row, Int32 col, Single value)
{
if (row < 1 || row > 4) throw new ArgumentOutOfRangeException("row");
if (col < 1 || col > 4) throw new ArgumentOutOfRangeException("col");
switch ((row * 10) + col)
{
case 11: m.M11 = value; break;
case 12: m.M12 = value; break;
case 13: m.M13 = value; break;
case 14: m.M14 = value; break;
case 21: m.M21 = value; break;
case 22: m.M22 = value; break;
case 23: m.M23 = value; break;
case 24: m.M24 = value; break;
case 31: m.M31 = value; break;
case 32: m.M32 = value; break;
case 33: m.M33 = value; break;
case 34: m.M34 = value; break;
case 41: m.M41 = value; break;
case 42: m.M42 = value; break;
case 43: m.M43 = value; break;
case 44: m.M44 = value; break;
}
}
public static Single Get(ref Matrix m, Int32 row, Int32 col)
{
if (row < 1 || row > 4) throw new ArgumentOutOfRangeException("row");
if (col < 1 || col > 4) throw new ArgumentOutOfRangeException("col");
switch ((row * 10) + col)
{
case 11: return m.M11;
case 12: return m.M12;
case 13: return m.M13;
case 14: return m.M14;
case 21: return m.M21;
case 22: return m.M22;
case 23: return m.M23;
case 24: return m.M24;
case 31: return m.M31;
case 32: return m.M32;
case 33: return m.M33;
case 34: return m.M34;
case 41: return m.M41;
case 42: return m.M42;
case 43: return m.M43;
case 44: return m.M44;
}
throw new InvalidOperationException();
}
}
然后可以这样调用:
var m = Matrix.Identity;
for (int row = 1; row <= 4; row++)
{
for (int col = 1; col <= 4; col++)
{
Console.WriteLine(MatrixUtil.Get(ref m, row, col));
}
}
您认为这会对您有用吗?