1
votes

I need help with some math related stuff.

I need to rotate a model on the screen with my mouse, but this rotation also needs to be based on the current yaw and pitch of the camera. I've got the first part down, but I don't know how to go on with transforming my roll and pitch to be relative to the camera. Right now, the rotation only works if the camera has not been rotated yet (which is to be expected considering that's what the current code was made to do.)

Also, do note that I do mean roll instead of yaw. I want the roll to be controlled with the left and right swipes of the mouse.

I've read that quaternions can solve the problem, but being a learn-by-example learner, I haven't been able to figure out how to do this.

Here is my current code (Note that PI2 is simply Pi * 2):

float dx = (input.getMouseDX() * prefs.mouseSensitivity);
float dy = (input.getMouseDY() * prefs.mouseSensitivity);

double roll = rollAngle, pitch = pitchAngle;

roll = (roll+dx) % PI2;

if(roll < 0){
    roll += PI2;
}

pitch += dy;

rollAngle = (float) yaw;
pitchAngle = (float) pitch;

Also, here's a GIF of the desired effect at all angles (but the GIF was taken at a non-rotated camera, the only point where I mentioned it worked.)

enter image description here

1

1 Answers

0
votes

I found the solution after visiting a few math websites and what not.

For anyone in the future who has this problem, here's a basic mathematical formula for it:

Variables:

RPYToRot = Function to convert (roll, pitch, yaw) to rotation matrix

RotToRPY = Opposite of above

RCam = camera rotation (roll, pitch, yaw)

RPos = player rotation (roll, pitch, yaw)

The formula itself being:

RNew = RotToRPY(RPYToRot(RPos)*Rcam)

And here's the code I used:

if (!markedMa){
    camMa.setFromEulerAngles((float) Math.toDegrees(-camera.getYaw()), (float) Math.toDegrees(camera.getPitch()), 0f);
    markedMa = true;
}

float dx = (input.getMouseDX() * (prefs.mouseSensitivity * 5f));
float dy = (input.getMouseDY() * (prefs.mouseSensitivity * 5f));

utilMatrix.setFromEulerAngles(0f, -dy, -dx);
camMa.mul(utilMatrix);

plaMa.setFromEulerAngles((float) Math.toDegrees(trueYaw), (float) Math.toDegrees(pitch), (float) Math.toDegrees(roll));
plaMa.mul(camMa);

The trick is to get the camera rotation as soon as you start the rotating on the model (assuming you lock the camera orientation), and multiply it by the mouse movement each frame rather than resetting the camera rotation matrix yourself.

plaMa has your final transformation you can then use to apply to your model.