Tom*_*Tom 3 c# opengl 3d opentk
我在OpenGL中移动和旋转对象时遇到了问题.我正在使用C#和OpenTK(Mono),但我想问题是我不理解OpenGL部分,所以即使你对C#/ OpenTK一无所知,你也可以帮助我.
我正在阅读OpenGL SuperBible(最新版),我试图用C#重写GLFrame.这是我已经重写的部分:
public class GameObject
{
protected Vector3 vLocation;
public Vector3 vUp;
protected Vector3 vForward;
public GameObject(float x, float y, float z)
{
vLocation = new Vector3(x, y, z);
vUp = Vector3.UnitY;
vForward = Vector3.UnitZ;
}
public Matrix4 GetMatrix(bool rotationOnly = false)
{
Matrix4 matrix;
Vector3 vXAxis;
Vector3.Cross(ref vUp, ref vForward, out vXAxis);
matrix = new Matrix4();
matrix.Row0 = new Vector4(vXAxis.X, vUp.X, vForward.X, vLocation.X);
matrix.Row1 = new Vector4(vXAxis.Y, vUp.Y, vForward.Y, vLocation.Y);
matrix.Row2 = new Vector4(vXAxis.Z, vUp.Z, vForward.Z, vLocation.Z);
matrix.Row3 = new Vector4(0.0f, 0.0f, 0.0f, 1.0f);
return matrix;
}
public void Move(float x, float y, float z)
{
vLocation = new Vector3(x, y, z);
}
public void RotateLocalZ(float angle)
{
Matrix4 rotMat;
// Just Rotate around the up vector
// Create a rotation matrix around my Up (Y) vector
rotMat = Matrix4.CreateFromAxisAngle(vForward, angle);
Vector3 newVect;
// Rotate forward pointing vector (inlined 3x3 transform)
newVect.X = rotMat.M11 * vUp.X + rotMat.M12 * vUp.Y + rotMat.M13 * vUp.Z;
newVect.Y = rotMat.M21 * vUp.X + rotMat.M22 * vUp.Y + rotMat.M23 * vUp.Z;
newVect.Z = rotMat.M31 * vUp.X + rotMat.M32 * vUp.Y + rotMat.M33 * vUp.Z;
vUp = newVect;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我在一些随机坐标上创建了一个新的GameObject(GLFrame):GameObject go = new GameObject(0, 0, 5);
然后旋转一下:go.RotateLocalZ(rotZ);
.然后我使用矩阵Matrix4 matrix = go.GetMatrix();
和渲染帧(首先,我设置了视图矩阵,然后我将它与建模矩阵相乘)
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
this.Title = "FPS: " + (1 / e.Time).ToString("0.0");
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadIdentity();
Matrix4 modelmatrix = go.GetMatrix();
Matrix4 viewmatrix = Matrix4.LookAt(new Vector3(5, 5, -10), Vector3.Zero, Vector3.UnitY);
GL.LoadMatrix(ref viewmatrix);
GL.MultMatrix(ref modelmatrix);
DrawCube(new float[] { 0.5f, 0.4f, 0.5f, 0.8f });
SwapBuffers();
}
Run Code Online (Sandbox Code Playgroud)
这DrawCube(float[] color)
是我自己绘制立方体的方法.
现在最重要的部分:如果我渲染帧没有的GL.MultMatrix(ref matrix);
部分,但用GL.Translate()
和GL.Rotate()
,它的工作原理(第二截图).但是,如果我不使用这两种方法并且我将建模矩阵直接传递给OpenGL使用GL.MultMatrix()
,则会产生一些奇怪的东西(第一次截图).
你能帮我解释一下问题在哪里吗?为什么它使用平移和旋转方法,但不是通过建模矩阵乘以视图矩阵?