I'm trying to rotate an object in a program written with OpenGL.
This object goes around in 3D space.
The angle of rotation on the Y axis (the yaw) is calculated with this:
facingAngle = -atan2(heading.y, heading.x);
…and I add it to the model like this:
glm::mat4 model;
model = glm::translate(model, position);
model = glm::rotate(model, facingAngle, glm::vec3(0.0f, 1.0f, 0.0f));
Then I would like this object to lean towards the direction it's heading to, like a cycle or an aircraft does (rolling).
I have tried countless options to calculate this value, but without any luck to find what I actually want.
The best I get so far, if I do this:
leaningAngle = glm::sqrt(squaredLength(steeringForce)) / gravity;
(The function, squaredLength
, does the following: return ( vector.x * vector.x + vector.y * vector.y );
)
The main problem with this is that it always leans the object to one given direction (so in half of the cases it leans outwards instead of inwards). However when I would like to modify this value with either *1
or *-1
based on where the object is heading, I get a weird behavior which I suppose is Gimbal lock.
What I would like to have is a simple equation which will give me an angle to roll the object between realistic values (90
and -90
degrees), and the weight of the angle should be calculated based on the current steering force (the sharper the turn, the bigger the leaning angle is).
The final code should be look like this:
glm::mat4 model;
model = glm::translate(model, position);
model = glm::rotate(model, facingAngle, glm::vec3(0.0f, 1.0f, 0.0f));
model = glm::rotate(model, leaningAngle, glm::vec3(1.0f, 0.0f, 0.0f));