OpenTK Camera in C#

2019-08-06 11:30发布

问题:

I'm trying to acquaint myself with writing programs with OpenTK in C#. I cannot figure out how to set and move camera. Currently, I have the following libraries imported:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Platform.Windows;
using System.Runtime.InteropServices;
using Imaging = System.Drawing.Imaging;
using TK = OpenTK.Graphics.OpenGL;
using System.IO;
using System.Threading;

I have put this code in Main to get my camera to work:

var myWindow = new GameWindow(840, 600);
Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(1.04f, 4f / 3f, 1f, 10000f);//Setup Perspective
float[] persF;
persF = new float[4] { 1.04f, 4f / 3f, 1f, 10000f };
Matrix4 lookat = Matrix4.LookAt(100, 20, 0, 0, 0, 0, 0, 1, 0);// 'Setup camera
float[] lookF;
lookF = new float[9] { 100, 20, 0, 0, 0, 0, 0, 1, 0 };
GL.MatrixMode(MatrixMode.Projection);// 'Load Perspective
GL.LoadIdentity();
GL.LoadMatrix(persF);
GL.MatrixMode(MatrixMode.Modelview);// 'Load Camera
GL.LoadIdentity();
GL.LoadMatrix(lookF);
GL.Enable(EnableCap.DepthTest);// 'Enable correct Z Drawings
GL.DepthFunc(DepthFunction.Less);// 'Enable correct Z Drawings
GL.Viewport(0, 0, myWindow.Width, myWindow.Height);

When I use GL.LoadMatrix(perspective) and GL.LoadMatrix(lookat), I get an overload matching error. For this reason, I converted the matrices to float arrays. When I try to draw polygons, they fail to show up unless this code is commented out (with the exception of the var myWindow = new GameWindow(840, 600) command.

回答1:

For your first issue, GL.LoadMatrix only has a ref Matrix4 overload, not just a Matrix4 overload. Passing the matrix by reference is a lot faster, since it won't create an extra copy on the stack when you call the method. Second, the parameters for Matrix4.CreatePerspectiveFiledOfView and Matrix4.LookAt are not matrices. They generate a 4x4 matrix (16 floats) based on those parameters, so your persF and lookF "matrices" will create some very strange results.

The proper call is GL.LoadMatrix(ref perspective); and GL.LoadMatrix(ref lookat);

And you should be creating a subclass of GameWindow and overriding OnLoad for this code and OnRenderFrame for your drawing code.