1
\$\begingroup\$

I'm currently developing a 3D game engine in C# using OpenTK.

I have basic game objects, and each game object has transform (translation, rotation and scaling). A game object can have components (much like Unity).

One game object (The camera game object) has three components, A camera, free move and a free look component. The free move component allows the user to move the camera around the scene, whilst the free look camera is SUPPOSED to rotate the camera. However, I get this odd effect:

https://youtu.be/rcdWZcaEqSY

(Note that, the plane isn't changing position, it seems the camera is ... turning upside down?)

On top of that, once I rotate the camera, moving the camera (using the arrow keys) gets really weird, up can become down, left can become right. It's all very odd.

Anywho, here is the update method for my Free Look component:

protected override void OnUpdate(object sender, UpdateEventArgs e)
{
    Rectangle bounds = Game.GetCurrentGame().Window.Bounds;

    Vector2 center = new Vector2(bounds.Left + (bounds.Width / 2), bounds.Top + (bounds.Height / 2));

    Vector2 mousePosition = new Vector2(System.Windows.Forms.Cursor.Position.X,
                                            System.Windows.Forms.Cursor.Position.Y);
    Vector2 deltaPosition = center - mousePosition;

    bool rotX = deltaPosition.X != 0;
    bool rotY = deltaPosition.Y != 0;

    if(rotY)
        Transform.Rotate(new Vector3(0, 1, 0), MathHelper.DegreesToRadians(-deltaPosition.X * sensitivity));
    if(rotX)
        Transform.Rotate(new Vector3(1, 0, 0), MathHelper.DegreesToRadians(-deltaPosition.Y * sensitivity));

    if (rotY || rotX)
        System.Windows.Forms.Cursor.Position = new Point((int)center.X, (int)center.Y);

    base.OnUpdate(sender, e);
}

here is the Rotate method in my transform class:

public void Rotate(Vector3 axis, float angle)
{
    rotation = (Quaternion.FromAxisAngle(axis, angle) * rotation).Normalized();
}

I hope someone can help me get to the bottom of this, I've been so frustrated!

If there's any other code you need to see, just let me know.

\$\endgroup\$

marked as duplicate by DMGregory, Gnemlock, Engineer, doppelgreener, Alexandre Vaillancourt Jun 15 '17 at 1:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 4
    \$\begingroup\$ This is a common mistake when implementing camera rotation - see "I'm rotating an object on two axes, so why does it keep twisting around the third axis?" for a detailed write-up on why it happens (including animated examples) and strategies you can employ to fix it. \$\endgroup\$ – DMGregory Jun 11 '17 at 14:22
  • \$\begingroup\$ @DMGregory Thanks for the input, sadly I'm still struggling with this, since I'm not using unity it's a little difficult to translate. \$\endgroup\$ – user102158 Jun 12 '17 at 5:06