Search code examples
c#openglopentkcamera-matrix

C# OpenGL OpenTK - Camera moves away from drawings as I adjust eye.X value


I've been trying to set up a camera in OpenGL for a few days now, but I just can't get it working properly. As the eye.X or eye.Y value increases/decreases, instead of "looking arround", the camera(I know there is no such thing as a camera...) moves away/gets closer to the drawings!

I hope following information can help you.(I also uploaded a Video, which is showing the error): https://www.youtube.com/watch?v=OlD5X0EzkUw

These are my ModelView calculations on OnUpdateFrame.

_worldPosition = Matrix4.CreateTranslation(_worldX, _worldY, _worldZ);
_cameraMatrix = Matrix4.LookAt(eye.X, eye.Y, eye.Z, center.X, center.Y, center.Z, up.X, up.Y, up.Z);

_modelViewMatrix = _worldPosition * _cameraMatrix;

Here, I adjust the values with OnMouseMove function:

if (_mouseDown)
{
     _mousePos.X = 2.0f * Mouse.X / Width - 1;
     _mousePos.Y = 2.0f * Mouse.Y / Width - 1;

     _mouseDeltaY = (_mousePosOld.Y - _mousePos.Y) / 10;
     _mouseDeltaX = (_mousePosOld.X - _mousePos.X) / 10;

     eye.X -= _mouseDeltaX;
     eye.Y -= _mouseDeltaY;
}

And finally my Vertex shader:

#version 440 core

layout (location = 0) in vec4 position;
layout(location = 1) in vec4 color;

layout(location = 2) uniform  mat4 projectionMatrix;
layout (location = 3) uniform  mat4 modelViewMatrix;

out vec4 vs_color;

void main(void)
{
    gl_Position = projectionMatrix * modelViewMatrix * position;
    vs_color = color;
}

Solution

  • To look around you have to rotate center around eye.

    e.g If you want to do a rotation around the x axis (up, down) the you have to setup a rotation matrix dependent on _mouseDeltaY:

    float angle_degree = _mouseDeltaY;
    Matrix4 rotateY = Matrix4.CreateRotationY(angle_degree * (float)Math.PI / 180.0f);
    

    Compute the vector from eye to center and rotate it:

    Vector3 toTarget = center - eye;
    toTarget = Vector4.Transform(new Vector4(toTarget, 0.0f), rotateY).Xyz;
    

    Finally compute the new center

    center = eye + toTarget;
    

    eye and center are assumed to be of type Vector3. Possibly you have to change the scale of _mouseDeltaY for your needs.