# OpenGL Ball Rotation

## Recommended Posts

I'm using OpenGL for a top-down 2.5 game. The player is a ball and I need to rotate it based on the direction it's moving. I have created a Matrix class which has a SetRotationYawPitchRoll() method but rotation on an axis will mess up the rotation on another axis.

I've been searching on here for some ideas and I came across the following:

[quote]1. Store the orientation of the ball as a quaternion or matrix
2. For each update, if the speed of the ball is greater than a specified epsilon:
3. The axis of rotation is the normalized cross product of the ball's velocity vector and the current 'up' vector
4. The angle of rotation (in radians) is the distance traveled by the ball during that update divided by the ball's radius
5. Apply this axis-angle rotation to the ball's orientation
6. Re-normalize the orientation to prevent drift (normalization for quaternions, orthogonalization for matrices)[/quote]

Based on this I have created the following methods

In my Matrix class
[code]inline void Matrix3D::SetRotation(Vector3D axis, float angle)
{
Matrix3D& matrix = *this;

float nx = axis.x;
float ny = axis.y;
float nz = axis.z;
float c = cosf(angle);
float s = fastSinf(angle);

matrix(0) = c+nx*nx*(1.0f-c);
matrix(1) = nx*ny*(1.0f-c)-nz*s;
matrix(2) = nx*nz*(1.0f-c)+ny*s;
matrix(3) = matrix(7) = matrix(11) = matrix(12) = matrix(13) = matrix(14) = 0.0f;
matrix(4) = ny*nx*(1.0f-c)+nz*s;
matrix(5) = c+ny*ny*(1.0f-c);
matrix(6) = ny*nz*(1.0f-c)-nx*s;
matrix(8) = nz*nx*(1.0f-c)-ny*s;
matrix(9) = nz*ny*(1.0f-c)+nx*s;
matrix(10) = c+nz*nz*(1.0f-c);
matrix(15) = 1.0f;
}[/code]

And my function to rotate the ball
[code]static inline bool getBallRotationMatrix(Vector3D velocity, Vector3D up, Matrix3D& matrix)
{
Vector3D axis = Cross(velocity, up).Normalize();

float distance = sqrtf(velocity.x * velocity.x + velocity.y * velocity.y);
float angle = distance;

matrix.SetRotation(axis, angle);

return true;
}[/code]

Finally my code to apply the matrix to the model

[code]Matrix3D matrix = Model->GetMatrix();

static Vector3D velocity = Vector3DEmpty();
velocity.x += position.x - m_lastPosition.x;
velocity.y += position.y - m_lastPosition.y;

if(getBallRotationMatrix(velocity, Vector3DMake(0, 0, 1), matrix))
Model->SetMatrix(matrix);[/code]

I have excluded the "distance traveled by the ball during that update divided by the ball's radius" part for now as I just want to have the ball roll in the direction it's moving for now.

Unfortunately it seems no different to SetRotationYawPitchRoll() in that one rotation axis seems to screw up the another.

What is wrong with my code? I don't quite understand how to "orthogonalize the matrix" at the end. Would this explain the results?

##### Share on other sites
I'm using OpenGL for a top-down 2.5 game. The player is a ball and I need to rotate it based on the direction it's moving. I have created a Matrix class which has a SetRotationYawPitchRoll() method but rotation on an axis will mess up the rotation on another axis.

I've been searching on here for some ideas and I came across the following:

[quote]1. Store the orientation of the ball as a quaternion or matrix
2. For each update, if the speed of the ball is greater than a specified epsilon:
3. The axis of rotation is the normalized cross product of the ball's velocity vector and the current 'up' vector
4. The angle of rotation (in radians) is the distance traveled by the ball during that update divided by the ball's radius
5. Apply this axis-angle rotation to the ball's orientation
6. Re-normalize the orientation to prevent drift (normalization for quaternions, orthogonalization for matrices)[/quote]

Based on this I have created the following methods

In my Matrix class
[code]inline void Matrix3D::SetRotation(Vector3D axis, float angle)
{
Matrix3D& matrix = *this;

float nx = axis.x;
float ny = axis.y;
float nz = axis.z;
float c = cosf(angle);
float s = fastSinf(angle);

matrix(0) = c+nx*nx*(1.0f-c);
matrix(1) = nx*ny*(1.0f-c)-nz*s;
matrix(2) = nx*nz*(1.0f-c)+ny*s;
matrix(3) = matrix(7) = matrix(11) = matrix(12) = matrix(13) = matrix(14) = 0.0f;
matrix(4) = ny*nx*(1.0f-c)+nz*s;
matrix(5) = c+ny*ny*(1.0f-c);
matrix(6) = ny*nz*(1.0f-c)-nx*s;
matrix(8) = nz*nx*(1.0f-c)-ny*s;
matrix(9) = nz*ny*(1.0f-c)+nx*s;
matrix(10) = c+nz*nz*(1.0f-c);
matrix(15) = 1.0f;
}[/code]

And my function to rotate the ball
[code]static inline bool getBallRotationMatrix(Vector3D velocity, Vector3D up, Matrix3D& matrix)
{
Vector3D axis = Cross(velocity, up).Normalize();

float distance = sqrtf(velocity.x * velocity.x + velocity.y * velocity.y);
float angle = distance;

matrix.SetRotation(axis, angle);

return true;
}[/code]

Finally my code to apply the matrix to the model

[code]Matrix3D matrix = Model->GetMatrix();

static Vector3D velocity = Vector3DEmpty();
velocity.x += position.x - m_lastPosition.x;
velocity.y += position.y - m_lastPosition.y;

if(getBallRotationMatrix(velocity, Vector3DMake(0, 0, 1), matrix))
Model->SetMatrix(matrix);[/code]

I have excluded the "distance traveled by the ball during that update divided by the ball's radius" part for now as I just want to have the ball roll in the direction it's moving for now.

Unfortunately it seems no different to SetRotationYawPitchRoll() in that one rotation axis seems to screw up the another.

What is wrong with my code? I don't quite understand how to "orthogonalize the matrix" at the end. Would this explain the results?
[/quote]
It is quite easy. First you need to understand that the orientation of an object could be represented by an orthogonalized matrix, this are in fact just three normalized vectors and the angel between two vectors is orthogonal = 90 degree. This is often represented by a coordination system consisting of x,y,z vectors seen in modelling tools for example.

The next step is to create a "look-at" matrix. Let's say your objects looks along the z-axis, then your first vector is given: lookat = normalize(ball.velocity)
Now you have to create an orthogonal matrix from this vector (assumption for sake of simplicity: ball can never move up):
[code]
vec lookat = normalize(ball.velocity)
// at first we need a valid reference vector, take a up vector pointing along the y-axis
vec up = vec(0,1,0)
// construct the vector pointing to the right
vec right = crossProduct( lookat,up)
// now we need to correct our up vector
up = crossProduct(lookat,right)

// now all vectors are normalized and orthogonal, construct transformation matrix from these vectors
matrix transform = matrix(right,up,lookat)

// no spin the ball around the right axis
matrix rotationMatrix = rotationMatrix( right, angle)

// rotate transformation
matrix final = transform * rotationMatrix
[/code]

That's it. There might be some misstakes, but this would be the basic approach.

##### Share on other sites
Thanks for your reply. I've tried to translate what you posted into my own function but it's still not quite working. My ball moves along the x and y axis and the up vector is z (ie. 0, 0, 1). If you can imagine it's a top down perspective game.

Here is the function based on your code

[code]static inline bool getBallRotationMatrix(Vector3D velocity, Vector3D up, Matrix3D& matrix)
{
Vector3D lookAt = velocity.Normalize();
Vector3D right = Cross(lookAt, up);
up = Cross(lookAt, right);

Matrix3D transformMatrix;
transformMatrix(M11) = right.x; transformMatrix(M12) = right.y; transformMatrix(M13) = right.z; transformMatrix(M14) = 0;
transformMatrix(M21) = up.x; transformMatrix(M22) = up.y; transformMatrix(M23) = up.z; transformMatrix(M24) = 0;
transformMatrix(M31) = lookAt.x; transformMatrix(M32) = lookAt.y; transformMatrix(M33) = lookAt.z; transformMatrix(M34) = 0;
transformMatrix(M41) = 0; transformMatrix(M42) = 0; transformMatrix(M43) = 0; transformMatrix(M44) = 1;

static float angle = 0;
angle += 1.0f;

Matrix3D rotationMatrix;
rotationMatrix.SetRotation(right, angle);

matrix = transformMatrix * rotationMatrix;

return true;
}[/code]

Right now the angle is just incrementing so the ball should roll in the direction based on the velocity but it's not; it seems to be spinning all over the place.

##### Share on other sites
Thanks for your reply. I've tried to translate what you posted into my own function but it's still not quite working. My ball moves along the x and y axis and the up vector is z (ie. 0, 0, 1). If you can imagine it's a top down perspective game.

Here is the function based on your code

[code]static inline bool getBallRotationMatrix(Vector3D velocity, Vector3D up, Matrix3D& matrix)
{
Vector3D lookAt = velocity.Normalize();
Vector3D right = Cross(lookAt, up);
up = Cross(lookAt, right);

Matrix3D transformMatrix;
transformMatrix(M11) = right.x; transformMatrix(M12) = right.y; transformMatrix(M13) = right.z; transformMatrix(M14) = 0;
transformMatrix(M21) = up.x; transformMatrix(M22) = up.y; transformMatrix(M23) = up.z; transformMatrix(M24) = 0;
transformMatrix(M31) = lookAt.x; transformMatrix(M32) = lookAt.y; transformMatrix(M33) = lookAt.z; transformMatrix(M34) = 0;
transformMatrix(M41) = 0; transformMatrix(M42) = 0; transformMatrix(M43) = 0; transformMatrix(M44) = 1;

static float angle = 0;
angle += 1.0f;

Matrix3D rotationMatrix;
rotationMatrix.SetRotation(right, angle);

matrix = transformMatrix * rotationMatrix;

return true;
}[/code]

Right now the angle is just incrementing so the ball should roll in the direction based on the velocity but it's not; it seems to be spinning all over the place.
[/quote]
A problem could be the velocity, but it depends on your physics engine. The velocity of slow or almost stopping objects could change frequently, instead of using the velocity you could remember the last position(updated each XXX ms) and take the delta = current_position - last_position as look at vector. This should be more stable.

##### Share on other sites
[quote name='Ashaman73' timestamp='1310716997' post='4835596']
delta = current_position - last_position as look at vector.
[/quote]

This is what I'm using for velocity at the moment. Any other ideas would be appreciated.

##### Share on other sites
Ashaman73: Perhaps if I explain how it's rolling using the code above you can understand the problem better?

When the ball moves up and down it rolls on the x axis which is okay. When moving the ball left or right it will roll on the z axis but it should be rolling on the y axis.

So it's really the left and right movement that seems to be off. If I swap the x and y values for the "right" vector when passed into SetRotation then left and right is now on the y axis and up and down rolls on the z axis.

Here is my code for calling the function

[code]Matrix3D matrix = Model->GetMatrix();

static Vector3D velocity = Vector3DEmpty();
velocity.x = position.x - m_lastPosition.x;
velocity.y = position.y - m_lastPosition.y;

if(getBallRotationMatrix(velocity, Vector3DMake(0, 0, 1), matrix))
Model->SetMatrix(matrix);[/code]

Aslo if the velocity (delta) is zero the ball will disappear. I'm guessing I'll need to make a threshold of some sort to correct this.

##### Share on other sites
Well it seems if I change the following

[code]matrix = transformMatrix * rotationMatrix;[/code]

to

[code]matrix = rotationMatrix;[/code]

It now rolls in the correct direction. So I'm guessing that the transformMatrix is not correct.

##### Share on other sites
So it's really the left and right movement that seems to be off. If I swap the x and y values for the "right" vector when passed into SetRotation then left and right is now on the y axis and up and down rolls on the z axis.
[/quote]
It sounds like the wrong "handness". Are you using a right or left handed coordination system ? The resulting vectors (lookat,up,right) must be a valid in your used coordination system. It seems that the right vector is pointing into the wrong direction. Instead of negating the x value, it would be better to switch the cross product parameters. Instead of
[code] Vector3D lookAt = velocity.Normalize();
Vector3D right = Cross(lookAt, up);
up = Cross(lookAt, right);
[/code]
use something like
[code] Vector3D lookAt = velocity.Normalize();
Vector3D right = Cross(up,lookAt);
up = Cross(lookAt, right);
[/code]
The same must be ensured for the up vector.

Test this code with a default setup (look at=your default look at axis, up = pointing up in your world), the result must represent the axis of your used coordination system.

##### Share on other sites
OpenGL uses a right handed coordinate system so that's what I'm using.

Swapping those two values around for the "right" cross product turned the ball into a pancake and had in spinning very oddly.

Is it possible I'm filling out the values in the transformMatrix incorrectly?

##### Share on other sites
I'm going to bump this in the hope someone can help locate the error in the code. Without the transformMatrix it rolls correctly, but I believe it needs it to blend the smaller movements. I've spent quite a bit of time messing around and can't get it working right. Any help is appreciated.

##### Share on other sites
The problem is, that there're too many possible places where some minor bug could be hidden. There's no "defined" way to do all the math including right or left handed coord system (i.e. I use a left handed coord system in combination with opengl). Detecting such bugs just from watching the behavior of the ball is really hard. I would sugguest to write some small (unit) tests to test your code.

I would do the following:
1. Extent your getBallRotationMatrix function by an additional parameter "angle" and remove the static angle variable from the function code.
2. Add some easy test cases for getBallRotationMatrix:
- up =your world up vector
- velocity = your look along vector
- angle = 0
This must result in a matrix representing your coordination system. Then start to add some other test cases (angle 90,180,270,360 degree, look along x,y,z axis etc.).

Good luck

## Create an account

Register a new account

• ## Partner Spotlight

• ### Forum Statistics

• Total Topics
627677
• Total Posts
2978591
• ### Similar Content

• Both functions are available since 3.0, and I'm currently using glMapBuffer(), which works fine.
But, I was wondering if anyone has experienced advantage in using glMapBufferRange(), which allows to specify the range of the mapped buffer. Could this be only a safety measure or does it improve performance?
Note: I'm not asking about glBufferSubData()/glBufferData. Those two are irrelevant in this case.
• By xhcao
Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness.
• By cebugdev
hi guys,
are there any books, link online or any other resources that discusses on how to build special effects such as magic, lightning, etc. in OpenGL? i mean, yeah most of them are using particles but im looking for resources specifically on how to manipulate the particles to look like an effect that can be use for games,. i did fire particle before, and I want to learn how to do the other 'magic' as well.
Like are there one book or link(cant find in google) that atleast featured how to make different particle effects in OpenGL (or DirectX)? If there is no one stop shop for it, maybe ill just look for some tips on how to make a particle engine that is flexible enough to enable me to design different effects/magic
let me know if you guys have recommendations.
• By dud3
How do we rotate the camera around x axis 360 degrees, without having the strange effect as in my video below?
Mine behaves exactly the same way spherical coordinates would, I'm using euler angles.
Tried googling, but couldn't find a proper answer, guessing I don't know what exactly to google for, googled 'rotate 360 around x axis', got no proper answers.

References:
Code: https://pastebin.com/Hcshj3FQ
The video shows the difference between blender and my rotation:

• By Defend
I've had a Google around for this but haven't yet found some solid advice. There is a lot of "it depends", but I'm not sure on what.
My question is what's a good rule of thumb to follow when it comes to creating/using VBOs & VAOs? As in, when should I use multiple or when should I not? My understanding so far is that if I need a new VBO, then I need a new VAO. So when it comes to rendering multiple objects I can either:
* make lots of VAO/VBO pairs and flip through them to render different objects, or
* make one big VBO and jump around its memory to render different objects.
I also understand that if I need to render objects with different vertex attributes, then a new VAO is necessary in this case.
If that "it depends" really is quite variable, what's best for a beginner with OpenGL, assuming that better approaches can be learnt later with better understanding?

• 11
• 12
• 10
• 12
• 22