Search code examples
c#opentk

OpenTK: rotate object with mouse, sometimes the rotation is reversed


I try to rotate object with mouse on a virtual sphere like MeshLab.

private void RotateCamera(Vector3 newDragPoint)
        {
            var rotAxis = Vector3.Normalize(Vector3.Cross(oldDragPoint, newDragPoint));
            var angle = Vector3.Dot(Vector3.Normalize(oldDragPoint), Vector3.Normalize(newDragPoint));
            double angleVal = Math.Acos(angle);
            Matrix4 rotateMatrix = Matrix4.CreateFromAxisAngle(rotAxis, (float)(angleVal));
            var modelViewMatrixTemp = rotateMatrix * modelViewMatrix;
        }

At the beginning it works good, the model view matrix is:

Row0: {(0.99888134, -0.044642903, -0.0154874, 0)}
    Row1: {(0.04587658, 0.9947593, 0.0913476, 0)}
    Row2: {(0.011327561, -0.0919559, 0.9956961, 0)}
    Row3: {(0, 0, -1, 1)}

but after a while if the rotation on x-y plane is big enough, the object start to rotate against the movement of mouse,

Row0: {(-0.9778508, -0.19920659, -0.06419495, 0)}
    Row1: {(0.18042804, -0.95778984, 0.22378196, 0)}
    Row2: {(-0.10606451, 0.20724255, 0.97251993, 0)}
    Row3: {(0, 0, -1, 1)} 

how to determine the angle under this kind of situation?

update______

now I figured out the rotation is applied to the object with initial pose, not the rotated object, but still have no idea of how to fix it.


Solution

  • split the new rotation with old rotation will solve this problem. keep the current rotation as oldRotation, then replace the line var modelViewMatrixTemp = rotateMatrix * modelViewMatrix; with

    var modelViewMatrixTemp = oldRotation * rotateMatrix * modelViewMatrix;
    oldRotation = oldRotation * rotateMatrix;
    

    that will apply rotation on rotated object.