Sign in to follow this  
Headkaze

OpenGL Ball Rotation

Recommended Posts

Headkaze    607
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 this post


Link to post
Share on other sites
Ashaman73    13715
[quote name='Headkaze' timestamp='1310694931' post='4835529']
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 this post


Link to post
Share on other sites
Headkaze    607
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 this post


Link to post
Share on other sites
Ashaman73    13715
[quote name='Headkaze' timestamp='1310714084' post='4835589']
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 this post


Link to post
Share on other sites
Headkaze    607
[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 this post


Link to post
Share on other sites
Headkaze    607
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 this post


Link to post
Share on other sites
Headkaze    607
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 this post


Link to post
Share on other sites
Ashaman73    13715
[quote name='Headkaze' timestamp='1310842325' post='4836090']
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 this post


Link to post
Share on other sites
Headkaze    607
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 this post


Link to post
Share on other sites
Headkaze    607
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 this post


Link to post
Share on other sites
Ashaman73    13715
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 :D

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By Zaphyk
      I am developing my engine using the OpenGL 3.3 compatibility profile. It runs as expected on my NVIDIA card and on my Intel Card however when I tried it on an AMD setup it ran 3 times worse than on the other setups. Could this be a AMD driver thing or is this probably a problem with my OGL code? Could a different code standard create such bad performance?
    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      Question:
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
       
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
    • By markshaw001
      Hi i am new to this forum  i wanted to ask for help from all of you i want to generate real time terrain using a 32 bit heightmap i am good at c++ and have started learning Opengl as i am very interested in making landscapes in opengl i have looked around the internet for help about this topic but i am not getting the hang of the concepts and what they are doing can some here suggests me some good resources for making terrain engine please for example like tutorials,books etc so that i can understand the whole concept of terrain generation.
       
    • By KarimIO
      Hey guys. I'm trying to get my application to work on my Nvidia GTX 970 desktop. It currently works on my Intel HD 3000 laptop, but on the desktop, every bind textures specifically from framebuffers, I get half a second of lag. This is done 4 times as I have three RGBA textures and one depth 32F buffer. I tried to use debugging software for the first time - RenderDoc only shows SwapBuffers() and no OGL calls, while Nvidia Nsight crashes upon execution, so neither are helpful. Without binding it runs regularly. This does not happen with non-framebuffer binds.
      GLFramebuffer::GLFramebuffer(FramebufferCreateInfo createInfo) { glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); textures = new GLuint[createInfo.numColorTargets]; glGenTextures(createInfo.numColorTargets, textures); GLenum *DrawBuffers = new GLenum[createInfo.numColorTargets]; for (uint32_t i = 0; i < createInfo.numColorTargets; i++) { glBindTexture(GL_TEXTURE_2D, textures[i]); GLint internalFormat; GLenum format; TranslateFormats(createInfo.colorFormats[i], format, internalFormat); // returns GL_RGBA and GL_RGBA glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, createInfo.width, createInfo.height, 0, format, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); DrawBuffers[i] = GL_COLOR_ATTACHMENT0 + i; glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, textures[i], 0); } if (createInfo.depthFormat != FORMAT_DEPTH_NONE) { GLenum depthFormat; switch (createInfo.depthFormat) { case FORMAT_DEPTH_16: depthFormat = GL_DEPTH_COMPONENT16; break; case FORMAT_DEPTH_24: depthFormat = GL_DEPTH_COMPONENT24; break; case FORMAT_DEPTH_32: depthFormat = GL_DEPTH_COMPONENT32; break; case FORMAT_DEPTH_24_STENCIL_8: depthFormat = GL_DEPTH24_STENCIL8; break; case FORMAT_DEPTH_32_STENCIL_8: depthFormat = GL_DEPTH32F_STENCIL8; break; } glGenTextures(1, &depthrenderbuffer); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, createInfo.width, createInfo.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthrenderbuffer, 0); } if (createInfo.numColorTargets > 0) glDrawBuffers(createInfo.numColorTargets, DrawBuffers); else glDrawBuffer(GL_NONE); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer Incomplete\n"; glBindFramebuffer(GL_FRAMEBUFFER, 0); width = createInfo.width; height = createInfo.height; } // ... // FBO Creation FramebufferCreateInfo gbufferCI; gbufferCI.colorFormats = gbufferCFs.data(); gbufferCI.depthFormat = FORMAT_DEPTH_32; gbufferCI.numColorTargets = gbufferCFs.size(); gbufferCI.width = engine.settings.resolutionX; gbufferCI.height = engine.settings.resolutionY; gbufferCI.renderPass = nullptr; gbuffer = graphicsWrapper->CreateFramebuffer(gbufferCI); // Bind glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); // Draw here... // Bind to textures glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[0]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[2]); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, depthrenderbuffer); Here is an extract of my code. I can't think of anything else to include. I've really been butting my head into a wall trying to think of a reason but I can think of none and all my research yields nothing. Thanks in advance!
    • By Adrianensis
      Hi everyone, I've shared my 2D Game Engine source code. It's the result of 4 years working on it (and I still continue improving features ) and I want to share with the community. You can see some videos on youtube and some demo gifs on my twitter account.
      This Engine has been developed as End-of-Degree Project and it is coded in Javascript, WebGL and GLSL. The engine is written from scratch.
      This is not a professional engine but it's for learning purposes, so anyone can review the code an learn basis about graphics, physics or game engine architecture. Source code on this GitHub repository.
      I'm available for a good conversation about Game Engine / Graphics Programming
  • Popular Now