Camera in opengl not working - c++

The problem is when I face my camera down the z axis for example and pitch this works fine however, after I have finished the pitch and would like to yaw on this new axis it begins to roll for some unknown reason =s.
void FrustumCamera::xAxisRotation(float angle)
{
// angle = angle * (double)degToRad;
Vector3<float> x = m_orientation.getXAxis();
Vector3<float> y = m_orientation.getYAxis();
Vector3<float> z = m_orientation.getZAxis();
y.rotateAroundAxis(x,angle);
x = m_orientation.getXAxis();
z.rotateAroundAxis(x,angle);
m_orientation.setYAxis(y);
m_orientation.setZAxis(z);
}
void FrustumCamera::yAxisRotation(float angle)
{
// angle = angle * (double)degToRad;
Vector3<float> x = m_orientation.getXAxis();
Vector3<float> y = m_orientation.getYAxis();
Vector3<float> z = m_orientation.getZAxis();
x.rotateAroundAxis(y,angle);
y = m_orientation.getYAxis();
z.rotateAroundAxis(y,angle);
m_orientation.setXAxis(x);
m_orientation.setZAxis(z);
}
void FrustumCamera::zAxisRotation(float angle)
{
Vector3<float> x = m_orientation.getXAxis();
Vector3<float> y = m_orientation.getYAxis();
Vector3<float> z = m_orientation.getZAxis();
x.rotateAroundAxis(z,angle);
z = m_orientation.getYAxis();
y.rotateAroundAxis(z,angle);
m_orientation.setXAxis(x);
m_orientation.setYAxis(y);
}
template <class Type>
void Vector3<Type>::rotateAroundAxis(Vector3<Type> axis, const float angle)
{
float radians = static_cast<Type>(angle * degToRad);
Type sinAngle = static_cast<Type>(sin(radians));
Type cosAngle = 0.0;
if (angle == 90 || angle == -90)
cosAngle = 0.0;
else
cosAngle = cos(radians);
normalise(axis); // normalise the axis
Type oneMinusCos = 1 - cosAngle; // (1 - cos(theta))
// construct the rotation matrix
Type tempMatrix[3][3];
tempMatrix[0][0] = (axis.x * axis.x) * oneMinusCos + cosAngle;
tempMatrix[0][1] = (axis.x * axis.y) * oneMinusCos + axis.z * sinAngle;
tempMatrix[0][2] = (axis.x * axis.z) * oneMinusCos - axis.y * sinAngle;
tempMatrix[1][0] = (axis.x * axis.y) * oneMinusCos - axis.z * sinAngle;
tempMatrix[1][1] = (axis.y * axis.y) * oneMinusCos + cosAngle;
tempMatrix[1][2] = (axis.y * axis.z) * oneMinusCos + axis.x * sinAngle;
tempMatrix[2][0] = (axis.x * axis.z) * oneMinusCos + axis.y * sinAngle;
tempMatrix[2][1] = (axis.y * axis.z) * oneMinusCos - axis.x * sinAngle;
tempMatrix[2][2] = (axis.z * axis.z) * oneMinusCos + cosAngle;
Vector3<Type> temp(*this);
Vector3<Type> result;
result.x = (temp.x * tempMatrix[0][0]) + (temp.y * tempMatrix[1][0]) + (temp.z * tempMatrix[2][0]);
result.y = (temp.x * tempMatrix[0][1]) + (temp.y * tempMatrix[1][1]) + (temp.z * tempMatrix[2][1]);
result.z = (temp.x * tempMatrix[0][2]) + (temp.y * tempMatrix[1][2]) + (temp.z * tempMatrix[2][2]);
*this = result;
}
void OpenGLRenderer::startDraw(unsigned long mask)
{
//sortBuffer(); // sort draw queue
clearBuffers(mask); // clear buffers
loadIdentity();
glTranslatef(-1*m_frustumCamera->getViewMatrix().getTranslationAxis().x,-1*m_frustumCamera->getViewMatrix().getTranslationAxis().y,-1*m_frustumCamera->getViewMatrix().getTranslationAxis().z);
glMultMatrixf(m_frustumCamera->getViewMatrix().getMatrix());
glTranslatef(m_frustumCamera->getViewMatrix().getTranslationAxis().x,m_frustumCamera->getViewMatrix().getTranslationAxis().y,m_frustumCamera->getViewMatrix().getTranslationAxis().z);// load identity
//
// push matrix stack
matrixStackPush();
}

You might be experiencing Gimbal Lock; this can happen if you pitch all the way up or down so your look vector becomes parallel with your up vector, In which case a yaw will be the same as a roll.
This can be a downside of constructing rotations piecemeal via Euler angles. You may want to look into quaternions. (Note that you cant rotate with Euler angles; they are just a representation for rotation (you need to convert it to matrix or quats), but the way you are tackling it is very much an 'Euler angle' way of thinking about it)
The strength of matrix multiplication is that any sequence of multiple rotations can be represented (and concatenated) as a single rotation matrix. What you need to be doing is something like this:
void Transformable::yaw(float angle)
{
float4x4 rot; // temp rotation matrix
float3 translate(&_transform._41); // save our translation
float3 up(&_transform._21); // y axis
// build the rotation matrix for rotation around y
MatrixRotationAxis(&rot, &up, angle);
// multiply our transform by the rotation matrix
// note that order of multiplication matters and depends on
// if your matrices are column-major or row-major
MatrixMultiply(&_transform, &_transform, &rot);
// write back our original translation
memcpy(&_transform._41, &translate, sizeof(float3));
// might want to reorthogonalise every now and then
// to make sure basis vectors are orthonormal
// or you will probably get matrix creep after a few operations
}
instead of trying to rotate one basis vector at a time. In this case _transform would be a 4x4 homogenous matrix representing the transformation matrix. (rotation and translation). The topleft 3x3 submatrix is simply the basis vectors of the orientation space.

Related

rotating bone with quaternion issue

I need to rotate bones of skeleton, i have already the quaterinion corresponding for each joints; and i am confused when it comes on rotating.
Skeleton to move is my opengl scene i need to move.
My problem is that i can't rotate the joint; Can anyone Help
Bellow is my code
//i evaluate each joint to get the translation and rotation.
void Node::EvaluatePoi(std::vector<POI> pois, const Vector &par_pos,
const Quaternion &par_rot, Vector Node::*world_pos,std::vector<Arti> joints)
{ Vector poi=this->PoiVec ;
Quaternion rot;
if (pois.empty()){
this->*world_pos= this->rest_position ;//OFFSET
rot= this-> rest_rotation ;//identity
}else{
if(this->name=="Hips")
{
this->*world_pos = eval_instant_positionPOI(poi);
rot= this-> rest_rotation ;// do not rotate
}else if(this->name=="LeftUpLeg")
{
this->*world_pos = this->rest_position;// set to OFFSET
rot= this-> rest_rotation ;// do not rotate
}else if(this->name=="RightUpLeg")
{
this->*world_pos = this->rest_position;
rot= this-> rest_rotation ;
}
else
{
this->*world_pos= this->rest_position;
rot= eval_instant_rotationPOI(joints);
}
}
//Applying transformation on the global position with rot =qparent * qchild
(this->*world_pos).rotate(par_rot);
this->*world_pos += par_pos;
rot = par_rot * rot;
// draw joint's subhierarchy
for (int i = 0; i < n_children; i++)
child[i]->EvaluatePoi(pois, this->*world_pos, rot, world_pos,joints);
}
EDIT:
//here i get the local rotation of each joint, after that create quaternions equivalent to individual Euler rotations and then compose to one rotation
Vector x_vector(1.0, 0.0, 0.0),
y_vector(0.0, 1.0, 0.0),
z_vector(0.0, 0.0, 1.0);
Quaternion Node::eval_instant_rotationPOI( std::vector<Arti> joints)
{
Quaternion roto;//= new Quaternion();
Quaternion sample;
double t= 0.02;
Vector v;
Vector Euler(0,0,0);;
string x =this->name;
if(x== "Head"){
Euler=GetEulers(joints,JOINT_HEAD);
}else if(x== "Neck"){
Euler=GetEulers(joints,JOINT_NECK);
}
else if(x== "LeftUpArm"){
Euler=GetEulers(joints,JOINT_LEFT_SHOULDER);
}
else if(x== "RightUpArm"){
Euler=GetEulers(joints,JOINT_RIGHT_SHOULDER);
}
else if(x== "LeftLowArm"){
Euler=GetEulers(joints,JOINT_LEFT_ELBOW);
}
else if(x== "LeftHand"){
Euler=GetEulers(joints,JOINT_LEFT_HAND);
}
else if(x== "RightLowArm"){
Euler=GetEulers(joints,JOINT_RIGHT_ELBOW);
}
else if(x== "RightHand"){
Euler=GetEulers(joints,JOINT_RIGHT_HAND);
}
else if(x== "Hips"){
Euler=GetEulers(joints,JOINT_TORSO);
}
else if(x== "LeftUpLeg"){
Euler=GetEulers(joints,JOINT_LEFT_HIP);
}
else if(x== "RightUpLeg"){
Euler=GetEulers(joints,JOINT_RIGHT_HIP);
}
else if(x== "LeftLowLeg"){
Euler=GetEulers(joints,JOINT_LEFT_KNEE);
}
else if(x== "LeftFoot"){
Euler=GetEulers(joints,JOINT_LEFT_FOOT);
}
else if(x== "RightLowLeg"){
Euler=GetEulers(joints,JOINT_RIGHT_KNEE);
}
else if(x== "RightFoot"){
Euler=GetEulers(joints,JOINT_RIGHT_FOOT);
}
Quaternion qx(x_vector, (Euler.x ));
Quaternion qy(y_vector, (Euler.y ));
Quaternion qz(z_vector, (Euler.z ));
sample = qz * qy * qx;
roto= slerp(qTemp, sample, t);
qTemp=roto;
return roto ;
}
/*here i multiply the joint and its parent to get the Euler Angle ; is it necessary to convert to
Euler Angle?/
Vector Node::GetEulers(std::vector<Arti> joints, const int idx) {
// Get the quaternion of its parent.
Quaternion q_parent;
Quaternion q_current;
if (idx == JOINT_TORSO) {
q_parent.identity();
}
/////
{
q_parent = Quaternion(joints[parent_joint_map[idx]].quat.x,
joints[parent_joint_map[idx]].quat.y,
joints[parent_joint_map[idx]].quat.z,
joints[parent_joint_map[idx]].quat.w);
}
// Get the quaternion of the joint.
q_current = Quaternion(joints[idx].quat.x, joints[idx].quat.y,
joints[idx].quat.z, joints[idx].quat.w);
// Calculate the relative quaternion.
Quaternion q_delta = quat_left_multiply(q_current , quat_inverse(q_parent));
Vector angle = euler_from_quat(q_delta);
// cout<<this->name<<" "<<angle<<" ";
return angle;
}
Quaternion quat_left_multiply(Quaternion l, Quaternion r) {
Quaternion q = {r.w * l.x + r.x * l.w + r.y * l.z - r.z * l.y,
r.w * l.y + r.y * l.w + r.z * l.x - r.x * l.z,
r.w * l.z + r.z * l.w + r.x * l.y - r.y * l.x,
r.w * l.w - r.x * l.x - r.y * l.y - r.z * l.z};
return q;
}
Vector& Vector::rotate(const Quaternion& q)
{
Quaternion p(x, y, z, 0.0f);
Quaternion qc(q);
qc.conjugate();
Quaternion pp(q * p * qc);
x = pp.x;
y = pp.y;
z = pp.z;
return *this;
}
Rotating a quaternion is actually multiplying a quaternion by another. Given the quaternion qA representing the current rotation of an object and qB the quaternion representing the amount of rotation to apply (to add) to this object, the resulting new rotation of this object is computed as follow (pseudocode):
qA = qA * qB;
Alternatively, you can apply (add) this rotation in what is called "object" or "local" transformation space by swapping operands:
qA = qB * qA
Each joint should hold (usualy as class member) a quaternion representing its current rotation in local space. This is probably what you already done. If you want to apply a rotation to that joint, then you simply need multiply the joint quaternion, by another quaternion representing the amount of rotation to apply. A quaterion rotation method can be like this (pseudocode):
Joint::Rotate(const quaterion& amount, bool local)
{
if(local) {
this->rotation = amount * this->rotation;
} else {
this->rotation = this->rotation * amount;
}
this->rotation.normalize();
}
That is all you need for the rotation part, nothing else. After that, you will need to convert the joint quaternion to a rotation matrix, so to be combined with the other joint transformations (translation, scale, whatever). Here is one implementation of the quaternion to rotation matrix conversion (pseudocode):
Matrix3 QuaternionToMatrix(const quaternion& q)
{
float x2 = q.x + q.x;
float y2 = q.y + q.y;
float z2 = q.z + q.z;
float xx = q.x * x2;
float xy = q.x * y2;
float xz = q.x * z2;
float yy = q.y * y2;
float yz = q.y * z2;
float zz = q.z * z2;
float wx = q.w * x2;
float wy = q.w * y2;
float wz = q.w * z2;
Matrix3 m; //< 3x3 matrix
m[0] = (1.0f - (yy + zz));
m[1] = (xy - wz);
m[2] = (xz + wy);
m[3] = (xy + wz);
m[4] = (1.0f - (xx + zz));
m[5] = (yz - wx);
m[6] = (xz - wy);
m[7] = (yz + wx);
m[8] = (1.0f - (xx + yy));
return m;
}
What you may finally need is to input rotation using Euler angles instead of quaternion values. Indeed, Euler angles are easier to handle and understand when it come to apply a rotation in a human point of view. In this case, you'll need to convert the input Euler angles to a quaternion. Here is one possible implementation of Euler angle to quaternion conversion:
Quaternion EulerToQuaternion(float x, float y, float z)
{
float sx = sinf(x * -0.5f);
float cx = cosf(x * -0.5f);
float sy = sinf(y * -0.5f);
float cy = cosf(y * -0.5f);
float sz = sinf(z * -0.5f);
float cz = cosf(z * -0.5f);
Quaternion q;
q.x = sx * cy * cz + cx * sy * sz;
q.y = cx * sy * cz - sx * cy * sz;
q.z = cx * cy * sz + sx * sy * cz;
q.w = cx * cy * cz - sx * sy * sz;
return q;
}

Problems rotating opengl camera

I cannot understand the math behind this problem, I am trying to create an FPS camera where I can look freely with my mouse input.
I am trying to rotate and position my lookat point with 180 degrees of freedom. I understand the easier solution is to glRotate the world to fit my perspective, but I do not want this approach. I am fairly unfamiliar with the trigonometry involved here and cannot figure out how to solve this problem the way I want to...
here is my attempt to do this so far...
code to get mouse coordinates relative to the center of the window, then process it in my camera object
#define DEG2RAD(a) (a * (M_PI / 180.0f))//convert to radians
static void glutPassiveMotionHandler(int x, int y) {
glf centerX = WinWidth / 2; glf centerY = WinHeight / 2;//get windows origin point
f speed = 0.2f;
f oldX = mouseX; f oldY = mouseY;
mouseX = DEG2RAD(-((x - centerX)));//get distance from 0 and convert to radians
mouseY = DEG2RAD(-((y - centerY)));//get distance from 0 and convert to radians
f diffX = mouseX - oldX; f diffY = mouseY - oldY;//get difference from last frame to this frame
if (mouseX != 0 || mouseY != 0) {
mainCamera->Rotate(diffX, diffY);
}
Code to rotate the camera
void Camera::Rotate(f angleX, f angleY) {
Camera::refrence = Vector3D::NormalizeVector(Camera::refrence * cos(angleX)) + (Camera::upVector * sin(angleY));//rot up
Camera::refrence = Vector3D::NormalizeVector((Camera::refrence * cos(angleY)) - (Camera::rightVector * sin(angleX)));//rot side to side
};
Camera::refrence is our lookat point, processing the lookat point is handled as follows
void Camera::LookAt(void) {
gluLookAt(
Camera::position.x, Camera::position.y, Camera::position.z,
Camera::refrence.x, Camera::refrence.y, Camera::refrence.z,
Camera::upVector.x, Camera::upVector.y, Camera::upVector.z
);
};
The camera is defined by a position point (position) a target point (refrence) and a up-vector upVector. If you want to change the orientation of the camera, then you've to rotate the direction vector from the position (position) to the target (refrence) rather then the target point by a Rotation matrix.
Note, since the 2 angles are angles which should change an already rotated view, you've to use a rotation matrix, to rotate the vectors which point in an arbitrary direction.
Write a function which set 3x3 rotation matrix around an arbitrary axis:
void RotateMat(float m[], float angle_radians, float x, float y, float z)
{
float c = cos(angle_radians);
float s = sin(angle_radians);
m[0] = x*x*(1.0f-c)+c; m[1] = x*y*(1.0f-c)-z*s; m[2] = x*z*(1.0f-c)+y*s;
m[3] = y*x*(1.0f-c)+z*s; m[4] = y*y*(1.0f-c)+c; m[5] = y*z*(1.0f-c)-x*s;
m[6] = z*x*(1.0f-c)-y*s; m[7] = z*y*(1.0f-c)+x*s; m[8] = z*z*(1.0f-c)+c };
}
Write a function which rotates a 3 dimensional vector by the matrix:
Vector3D Rotate(float m[], const Vector3D &v)
{
Vector3D rv;
rv.x = m[0] * v.x + m[3] * v.y + m[6] * v.z;
rv.y = m[1] * v.x + m[4] * v.y + m[7] * v.z;
rv.z = m[2] * v.x + m[5] * v.y + m[8] * v.z;
return rv;
}
Calculate the vector form the position to the target:
Vector3D los = Vector3D(refrence.x - position.x, refrence.y - position.y, refrence.z - position.z);
Rotate all the vectors around the z axis of the world by angleX:
float rotX[9];
RotateMat(rotX, angleX, Vector3D(0, 0, 1));
los = Rotate(rotX, los);
upVector = Rotate(rotX, upVector);
Rotate all the vectors around the current y axis of the view by angleY:
float rotY[9];
RotateMat(rotY, angleY, Vector3D(los.x, los.y, 0.0));
los = Rotate(rotY, los);
upVector = Rotate(rotY, upVector);
Calculate the new target point:
refrence = Vector3D(position.x + los.x, position.y + los.y, position.z + los.z);
U_Cam_X_angle is left right rotation.. U_Cam_Y_angle is up down rotation.
view_radius is the view distance (zoom) to U_look_point_x, U_look_point_y and U_look_point_z.
This is ALWAYS a negative number! This is because you are always looking in positive direction. Deeper in the screen is more positive.
This is all in radians.
The last three.. eyeX, eyeY and eyeZ is where the camera is in 3D space.
This code is in VB.net. Find a converter online for VB to C++ or do it manually.
Public Sub set_eyes()
Dim sin_x, sin_y, cos_x, cos_y As Single
sin_x = Sin(U_Cam_X_angle + angle_offset)
cos_x = Cos(U_Cam_X_angle + angle_offset)
cos_y = Cos(U_Cam_Y_angle)
sin_y = Sin(U_Cam_Y_angle)
cam_y = Sin(U_Cam_Y_angle) * view_radius
cam_x = (sin_x - (1 - cos_y) * sin_x) * view_radius
cam_z = (cos_x - (1 - cos_y) * cos_x) * view_radius
Glu.gluLookAt(cam_x + U_look_point_x, cam_y + U_look_point_y, cam_z + U_look_point_z, _
U_look_point_x, U_look_point_y, U_look_point_z, 0.0F, 1.0F, 0.0F)
eyeX = cam_x + U_look_point_x
eyeY = cam_y + U_look_point_y
eyeZ = cam_z + U_look_point_z
End Sub

How to correctly convert from Euler angles and multiply quaternions?

We are trying to convert from a local space incremental rotation in Euler (X,Y,Z) = Pitch Yaw Roll to an absolute world space rotation Quaternion.
We are doing this by converting each incremental rotation to a quaternion and accumulating (through multiplication) Quaternion rotations to give a world space quaternion.
However our result rotations show the object rotating around world space axes rather than local object axes.
I am following this pseudocode loop and c++, and have built the same in Unity3D (which works correctly since the Quaternion operations are aready provided).
Does anyone have any pointers as to what is going wrong here?
Quaternion qacc;
Quaternion q1;
loop
{
quacc = quacc * q1.degreeToQuaternion(xRot, yRot, zRot);
}
...
void Quaternion::degreeToQuaternion( double yaw, double pitch, double roll) // yaw (Z), pitch (Y), roll (X)
{
yaw = yaw * M_PI / 180.;
pitch = pitch * M_PI / 180.;
roll = roll * M_PI / 180.;
radianToQuaternion(yaw, pitch, roll);
}
void Quaternion::radianToQuaternion( double yaw, double pitch, double roll) // yaw (Z), pitch (Y), roll (X)
{
double cy = cos(yaw * 0.5);
double sy = sin(yaw * 0.5);
double cp = cos(pitch * 0.5);
double sp = sin(pitch * 0.5);
double cr = cos(roll * 0.5);
double sr = sin(roll * 0.5);
this->w = cy * cp * cr + sy * sp * sr;
this->x = cy * cp * sr - sy * sp * cr;
this->y = sy * cp * sr + cy * sp * cr;
this->z = sy * cp * cr - cy * sp * sr;
}
Quaternion operator * (Quaternion q0, Quaternion q1)
{
Quaternion q2;
double mag;
q2.w = q0.w * q1.w - q0.x * q1.x - q0.y * q1.y - q0.z * q1.z;
q2.x = q0.w * q1.x + q0.x * q1.w + q0.y * q1.z - q0.z * q1.y;
q2.y = q0.w * q1.y - q0.x * q1.z + q0.y * q1.w + q0.z * q1.x;
q2.z = q0.w * q1.z + q0.x * q1.y - q0.y * q1.x + q0.z * q1.w;
mag = sqrt (q2.w * q2.w + q2.x * q2.x + q2.y * q2.y + q2.z * q2.z);
q2.w /= mag;
q2.x /= mag;
q2.y /= mag;
q2.z /= mag;
return q2;
}

Calculate position and rotation of camera with mouse events

My plan:
1. Calculate mouse direction [x, y] [success]
I my Mouse Move event:
int directionX = lastPosition.x - position.x;
int directionY = lastPosition.y - position.y;
2. Calculate angles [theta, phi] [success]
float theta = fmod(lastTheta + sensibility * directionY, M_PI);
float phi = fmod(lastPhi + sensibility * directionX * -1, M_PI * 2);
Edit {
bug fix:
float theta = lastTheta + sensibility * directionY * -1;
if (theta < M_PI / -2)theta = M_PI / -2;
else if (theta > M_PI / 2)theta = M_PI / 2;
float phi = fmod(lastPhi + sensibility * directionX * -1, M_PI * 2);
}
Now I have given theta, phi, the centerpoint and the radius and I want to calculate the position and the rotation [that the camera look at the centerpoint]
3. Calculate position coordinates [X,Y,Z] [failed]
float newX = radius * sin(phi) * cos(theta);
float newY = radius * sin(phi) * sin(theta);
float newZ = radius * cos(phi);
Solution [by meowgoesthedog]:
float newX = radius * cos(theta) * cos(phi);
float newY = radius * sin(theta);
float newZ = radius * cos(theta) * sin(phi);
4. Calculate rotation [failed]
float pitch = ?;
float yaw = ?;
Solution [by meowgoesthedog]:
float pitch = -theta;
float yaw = -phi;
Thanks for your solutions!
Your attempt was almost (kinda) correct:
As the diagram shows, in OpenGL the "vertical" direction is conventionally taken to be Y, whereas your formulas assume it is Z
phi and theta are in the wrong order
Very simple conversion: yaw = -phi, pitch = -theta (from the perspective of the camera)
Fixed formulas:
float position_X = radius * cos(theta) * cos(phi);
float position_Y = radius * sin(theta);
float position_Z = radius * cos(theta) * sin(phi);
(There may also be some sign issues with the mouse deltas but they should be easy to fix.)

Rotation of object around World Axis OpenGL

I'm trying to make a controllable ball in OpenGL. I'm using my own matrix class to transform the object matrix, but I can't seem to get the Rotation right. I always end up with the ball rotating around the local axis.
This is how it looks right now https://gfycat.com/LongKindBassethound . The long line are the local axis.
So when the ball moves forward the next side movement will be wrong. Theres a function in the matrix class that allows rotation around any axis:
Matrix& Matrix::rotationAxis(const Vector& Axis, float Angle) {
const float Si = sin(Angle);
const float Co = cos(Angle);
const float OMCo = 1 - Co;
Vector Ax = Axis;
Ax.normalize();
m00= (Ax.X * Ax.X) * OMCo + Co;
m01= (Ax.X * Ax.Y) * OMCo - (Ax.Z * Si);
m02= (Ax.X * Ax.Z) * OMCo + (Ax.Y * Si);
m03= 0;
m10= (Ax.Y * Ax.X) * OMCo + (Ax.Z * Si);
m11= (Ax.Y * Ax.Y) * OMCo + Co;
m12= (Ax.Y * Ax.Z) * OMCo - (Ax.X * Si);
m13= 0;
m20= (Ax.Z * Ax.X) * OMCo - (Ax.Y * Si);
m21= (Ax.Z * Ax.Y) * OMCo + (Ax.X * Si);
m22= (Ax.Z * Ax.Z) * OMCo + Co;
m23= 0;
m30= 0;
m31= 0;
m32= 0;
m33= 1;
return *this;
}
I think with this I can take the world direction vectors and transform them to the local space of the object and then rotate around the result. I don't really know how to do that though (matrix of the ball * world vector? That doesn't work). I would really like to avoid quaternions, but if I can't do that I would appreciate suggestions in that direction too.
EDIT: More Info
The transforamtion Code. As you can see I tried different methods that all do the same... So no surprise there that it doesnt work.
Matrix transM, rotX, rotZ;
rotationX = straight;
rotationZ = side;
if (velocity != Vector(0, 0, 0)) {
velocity.X = -0.0005 * DeltaTime;
velocity.X = clamp(velocity.X, 0, FLT_MAX);
velocity.Z = -0.0005 * DeltaTime;
velocity.Z = clamp(velocity.Z, 0, FLT_MAX);
}
velocity.X += speed * -side * DeltaTime;
velocity.Z += speed * straight * DeltaTime;
transM.translation(velocity.X, 0, velocity.Z);
if (velocity.Z != 0 || velocity.X != 0) {
//http://mathworld.wolfram.com/EulerAngles.html
//http://gamedev.stackexchange.com/questions/67199/how-to-rotate-an-object-around-world-aligned-axes
Vector localAxisX = m_Ball * Vector(1, 0, 0);
Vector localAxisZ = m_Ball * Vector(0, 0, 1);
rotX.rotationAxis(Vector(1, 0, 0), 0.5* M_PI * straight * DeltaTime);
rotZ.rotationAxis(Vector(0, 0, 1), 0.5* M_PI * side * DeltaTime);
//rotX.rotationX(0.5* M_PI * straight * DeltaTime * 3);
//rotZ.rotationZ(0.5* M_PI * side * DeltaTime * 3);
//Matrix fullRotation.rotationYawPitchRoll(Vector(0, 0.5* M_PI * straight * DeltaTime, 0.5* M_PI * side * DeltaTime));
m_Ball = transM * m_Ball * (rotX*rotZ);
}
else {
m_Ball = transM * m_Ball;
}
Draw code with my previous attempt trying to use glRotatef (obviously commented out right now)
void Ball::draw(float DeltaTime) {
glPushMatrix();
glMultMatrixf(m_Ball);
if(rotationX)
glRotatef(0.5* M_PI * rotationX * DeltaTime, 1.0, 0.0, 0.0);
if(rotationZ)
glRotatef(0.5* M_PI * rotationZ * DeltaTime, 0.0, 0.0, 1.0);
g_Model_ball.drawTriangles();
glPopMatrix();
drawAxis();
}
I highly suggest using quaternions to easily handle compound rotations and avoid gimbal lock.
https://en.wikipedia.org/wiki/Gimbal_lock
Ok with regards to your comments and video, You want to rotate around the ball's center. It seems you accumulate your rotations in m_Ball but do a weird transM multiplication. Also you are probably accumulating translations in transM.
Try not to mix your translations and rotations and avoid accumulating them in your m_Ball. You can do something like this.
//transformation matrix
transM.translation(velocity.X, 0, velocity.Z);
//accumulate translations in m_BallT
m_BallT = transM * m_BallT;
//final Rotation
Matrix rotation = rotX * rotZ;
//accumulate rotations in m_BallR
m_BallR = rotation * m_BallR;
//now compute your final transformation matrix from accumulated rotations and translation
m_Ball = m_BallT * m_BallR;
note how m_BallR is just rotations accumulated. Post multiplication will ensure new rotation is applied after accumulated rotations in m_BallR. Finally translate to the final position accumulated in m_BallT. Your ball will rotate about its center and move according to m_BallT.
You could also simply replace the transformation component on your m_BallR to avoid extra matrix multiplications.
Vector newPos(m_Ball.translation().X + velocity.X, terrainNoise.GetHeight(m_Ball.translation().X, m_Ball.translation().Z) + 0.5, m_Ball.translation().Z + velocity.Z);
rotX.rotationAxis(Vector(1, 0, 0), 0.5* M_PI * straight * DeltaTime * abs(velocity.Z) * 100);
rotZ.rotationAxis(Vector(0, 0, 1), 0.5* M_PI * side * DeltaTime * abs(velocity.X) * 100);
m_Rotation = (rotX*rotZ);
m_Ball = (m_Ball.invert() * m_Rotation).invert();
m_Ball.m03 = newPos.X;
m_Ball.m13 = newPos.Y;
m_Ball.m23 = newPos.Z;
This is the solution I came up with after reading this link provided by #Spektre. Basically you just invert the ModelMatrix of the ball to get it into world position, do your rotation and then transform it back into local space.
You have to set the newPos Vector before you rotate, otherwise it would affect future transformations.