Intermediate Tutorial 1         Animation, Walking Between Points, and Basic Quaternions
Print

Any problems you encounter during working with this tutorial should be posted in the Help Forum(external link).

 

Introduction

In this tutorial we will be covering how to take an Entity, animate it, and have it walk between predefined points. This will also cover the basics of Quaternion rotation by showing how to keep the Entity facing the direction it is moving. As you go through the demo you should be slowly adding code to your own project and watching the results as we build it.

You can see the final state of this tutorial here.

Prerequisites

This tutorial will assume that you already know how to set up an Ogre project and make it compile successfully. This tutorial also makes use of the STL deque data structure. While no prior knowledge of how to use a deque is required, you should at least know what templates are. If you are not familiar with STL, I would recommend picking up STL Pocket Reference [ISBN 0-596-00556-3]. This will save you a lot of time in the future.

You can read the first part of "STL Pocket Reference" here(external link)

Getting Started

First, you need to create a new project (I called it ITutorial01) and add the following code:

ITutorial01 header
#ifndef __ITutorial01_h_
#define __ITutorial01_h_
 
#include "BaseApplication.h"
#include <deque>
 
class ITutorial01 : public BaseApplication
{
public:
    ITutorial01(void);
    virtual ~ITutorial01(void);
 
protected:
     virtual void createScene(void);
     virtual void createFrameListener(void);
     virtual bool nextLocation(void);
     virtual bool frameRenderingQueued(const Ogre::FrameEvent &evt);
 
     Ogre::Real mDistance;                  // The distance the object has left to travel
     Ogre::Vector3 mDirection;              // The direction the object is moving
     Ogre::Vector3 mDestination;            // The destination the object is moving towards
 
     Ogre::AnimationState *mAnimationState; // The current animation state of the object
 
     Ogre::Entity *mEntity;                 // The Entity we are animating
     Ogre::SceneNode *mNode;                // The SceneNode that the Entity is attached to
     std::deque<Ogre::Vector3> mWalkList;   // The list of points we are walking to
 
     Ogre::Real mWalkSpeed;                 // The speed at which the object is moving
 
 
 
};
 
#endif // #ifndef __ITutorial01_h_
ITutorial01 implementation
#include "ITutorial01.h"
 
//-------------------------------------------------------------------------------------
ITutorial01::ITutorial01(void)
{
}
//-------------------------------------------------------------------------------------
ITutorial01::~ITutorial01(void)
{
}
 
//-------------------------------------------------------------------------------------
void ITutorial01::createScene(void)
{
}
void ITutorial01::createFrameListener(void){
	BaseApplication::createFrameListener();
}
bool ITutorial01::nextLocation(void){
	return true;}
 
bool ITutorial01::frameRenderingQueued(const Ogre::FrameEvent &evt){
	return BaseApplication::frameRenderingQueued(evt);
}
 
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
 
#ifdef __cplusplus
extern "C" {
#endif
 
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
    INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
    int main(int argc, char *argv[])
#endif
    {
        // Create application object
        ITutorial01 app;
 
        try {
            app.go();
        } catch( Ogre::Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
            MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
            std::cerr << "An exception has occured: " <<
                e.getFullDescription().c_str() << std::endl;
#endif
        }
 
        return 0;
    }
 
#ifdef __cplusplus
}
#endif

Be sure you can compile this code before continuing.

Setting up the Scene

Before we begin, notice that we have already defined 3 variables in the header file. The mEntity will hold the entity we create, mNode will hold the node we create, and mWalkList will contain all the points we wish the object to walk to.

Go to the ITutorial01::createScene function and add the following code to it. First we are going to set the ambient light to full so that we can see objects we put on the screen.

// Set the default lighting.
         mSceneMgr->setAmbientLight(Ogre::ColourValue(1.0f, 1.0f, 1.0f));

Next we will create a Robot on the screen so that we can play with him. To do this we will create the entity for the Robot, then create a SceneNode for him to dangle from.

// Create the entity
        mEntity = mSceneMgr->createEntity("Robot", "robot.mesh");
 
        // Create the scene node
        mNode = mSceneMgr->getRootSceneNode()->
            createChildSceneNode("RobotNode", Ogre::Vector3(0.0f, 0.0f, 25.0f));
        mNode->attachObject(mEntity);

This all should be very basic, so I will not go into detail about any of it. In the next chunk of code, we are going to tell the robot where he needs to be moved to. For those of you who don't know anything about STL, the deque object is an efficient implementation of a double ended queue. We will only be using a few of its methods. The push_front and push_back methods put items at the front and back of the deque respectively. The front and back methods return the values at the front and back of the deque respectively. The pop_front and pop_back methods remove the items from the front and back of the queue respectively. Finally, the empty method returns whether or not the deque is empty. This code adds two Vectors to the deque, which we will later make the robot move to.

// Create the walking list
        mWalkList.push_back(Ogre::Vector3(550.0f,  0.0f,  50.0f ));
        mWalkList.push_back(Ogre::Vector3(-100.0f,  0.0f, -200.0f));

Next, we want to place some objects on the scene to show where the robot is supposed to be moving to. This will allow us to see the robot moving with respect to other objects on the screen. Notice the negative Y component to their position. This puts the objects under where the robot is moving to, and he will stand on top of them when he gets to the right spot.

// Create objects so we can see movement
        Ogre::Entity *ent;
        Ogre::SceneNode *node;
 
        ent = mSceneMgr->createEntity("Knot1", "knot.mesh");
        node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Knot1Node",
            Ogre::Vector3(0.0f, -10.0f,  25.0f));
        node->attachObject(ent);
        node->setScale(0.1f, 0.1f, 0.1f);
 
        ent = mSceneMgr->createEntity("Knot2", "knot.mesh");
        node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Knot2Node",
            Ogre::Vector3(550.0f, -10.0f,  50.0f));
        node->attachObject(ent);
        node->setScale(0.1f, 0.1f, 0.1f);
 
        ent = mSceneMgr->createEntity("Knot3", "knot.mesh");
        node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Knot3Node",
            Ogre::Vector3(-100.0f, -10.0f,-200.0f));
        node->attachObject(ent);
        node->setScale(0.1f, 0.1f, 0.1f);

Finally, we want to set the camera to a good viewing point to see this from. We will move the camera to get a better position.

// Set the camera to look at our handiwork
        mCamera->setPosition(90.0f, 280.0f, 535.0f);
        mCamera->pitch(Ogre::Degree(-30.0f));
        mCamera->yaw(Ogre::Degree(-15.0f));

Now compile and run the code.

Animation

We are now going to setup some basic animation. Animation in Ogre is very simple. To do this, you need to get the AnimationState from the Entity object, set its options, and enable it. This will make the animation active, but you will also need to add time to it after each frame in order for the animation to run. We'll take this one step at a time. First, go to ITutorial01::createFrameListener and add the following code, after the call to BaseApplication::createFrameListener:

// Set idle animation
        mAnimationState = mEntity->getAnimationState("Idle");
        mAnimationState->setLoop(true);
        mAnimationState->setEnabled(true);

The second line gets the AnimationState out of the entity. In the third line we call setLoop( true ), which makes the animation loop over and over. For some animations (like the death animation), we would want to set this to false instead. The fourth line actually enables the Animation. But wait...where did we get ‘idle’ from? How did this magic constant slip in there? Every mesh has their own set of Animations defined for them. In order to see all of the Animations for the particular mesh you are working on, you need to download the OgreMeshViewer and view the mesh from there.

Now, if we compile and run the demo we see...nothing has changed. This is because we need to update the animation state with a time every frame. Find the ITutorial01::frameRenderingQueued method, and add this line of code at the beginning of the function:

mAnimationState->addTime(evt.timeSinceLastFrame);

Now build and run the application. You should see a robot performing his idle animation standing in place.

Moving the Robot

Now we are going to perform the tricky task of making the robot walk from point to point. Before we begin I would like to describe the variables that we have defined. We are going to use 4 variables to accomplish the task of moving the robot. First of all, we are going to store the direction the robot is moving in mDirection. We will store the current destination the Robot is traveling to in mDestination. We will store the distance the robot has left to travel in mDistance. Finally, we will store the robot's moving speed in mWalkSpeed.

The first thing we need to do is to set up these variables. We'll set the walk speed to 35 units per second. There is one big thing to note here. We are explicitly setting mDirection to be the ZERO vector because later we will use this to determine if we are moving the Robot or not. Add the following code to ITutorial01::createFrameListener:

// Set default values for variables
         mWalkSpeed = 35.0f;
         mDirection = Ogre::Vector3::ZERO;

Now that this is done, we need to set the robot in motion. To make the robot move, we simply tell it to change animations. However, we only want to start the robot moving if there is another location to move to. For this reason we call the ITutorial01::nextLocation function. Add this code to the top of the ITutorial01::frameRenderingQueued method just before the AnimationState::addTime call:

if (mDirection == Ogre::Vector3::ZERO) 
        {
            if (nextLocation()) 
            {
                // Set walking animation
                mAnimationState = mEntity->getAnimationState("Walk");
                mAnimationState->setLoop(true);
                mAnimationState->setEnabled(true);
            }
        }

If you compile and run the code right now, the robot will walk in place. This is because the robot starts out with a direction of ZERO and our ITutorial01::nextLocation function always returns true. In later steps we will be adding a bit more intelligence to the ITutorial01::nextLocation function.

Now we are going to actually move the robot in the scene. To do this we need to have him move a small bit every frame. Go to the ITutorial01::frameRenderingQueued method. We will be adding the following code just after our previous if statement and just above the AnimationState::addTime call. This code will handle the case when the robot is actually moving; mDirection != Ogre::Vector3::ZERO.
the reason why mWalkspeed is multiplied by evt.timeSinceLastFrame, is to keep the walkspeed constant, despite variations in framerate.
if you only had written Real move = mWalkspeed, the robot would walk slow on a slow computer, and walk fast on a fast one.

 
Image

else
         {
             Ogre::Real move = mWalkSpeed * evt.timeSinceLastFrame;
             mDistance -= move;

Now, we need to check and see if we are going to overshoot the target position. That is, if mDistance is now less than zero, we need to jump to the point and set up the move to the next point. Note that we are setting mDirection to the ZERO vector. If the nextLocation method does not change mDirection (IE there is nowhere left to go) then we no longer have to move around.

if (mDistance <= 0.0f)
             {
                 mNode->setPosition(mDestination);
                 mDirection = Ogre::Vector3::ZERO;

Now that we have moved to the point, we need to setup the motion to the next point. Once we know if we need to move to another point or not, we can set the appropriate animation; walking if there is another point to go to and idle if there are no more destination points. This is a simple matter of setting the Idle animation if there are no more locations.

// Set animation based on if the robot has another point to walk to. 
                if (! nextLocation())
                {
                    // Set Idle animation                     
                    mAnimationState = mEntity->getAnimationState("Idle");
                    mAnimationState->setLoop(true);
                    mAnimationState->setEnabled(true);
                } 
                else
                {
                    // Rotation Code will go here later
                }
            }

Note that we have no need to set the walking animation again if there are more points in the queue to walk to. Since the robot is already walking there is no reason to tell him to do so again. However, if the robot needs to go to another point, then we need to rotate him to face that point. For now we leave a placeholder comment in the else clause; remember this spot as we will come back to it later.

This takes care of when we are very close to the target position. Now we need to handle the normal case, when we are just on the way to the position but we're not there yet. To do that we will translate the robot in the direction we are traveling, and move it by the amount specified by the move variable. This is accomplished by adding the following code:

else
             {
                 mNode->translate(mDirection * move);
             } // else
         } // if

We are almost done. Our code now does everything except set up the variables required for movement. If we can properly set the movement variables our Robot will move like he is supposed to. Find the ITutorial01::nextLocation function. This function returns false when we run out of points to go to. This will be the first line of our function. (Note you should leave the return true statement at the bottom of the function.)

if (mWalkList.empty())
             return false;

Now we need to set the variables (still in the nextLocation method). First we will pull the destination vector from the deque. We will set the direction vector by subtracting the SceneNode's current position from the destination. We have a problem though. Remember how we multiplied mDirection by the move amount in frameRenderingQueued? If we do this, we need the direction vector to be a unit vector (that is, it's length equals one). The normalise function does this for us, and returns the old length of the vector. Handy that, since we need to also set the distance to the destination.

mDestination = mWalkList.front();  // this gets the front of the deque
        mWalkList.pop_front();             // this removes the front of the deque
 
        mDirection = mDestination - mNode->getPosition();
        mDistance = mDirection.normalise();

Now compile and run the code. It works! Sorta. The robot now walks to all the points, but he is always facing the Ogre::Vector3::UNIT_X direction (his default). We will need to change the direction he is facing when he is moving towards points.

What we need to do is get the direction the Robot is facing, and use rotate function to rotate the object in the right position. Insert the following code where we left our placeholder comment in the previous step. The first line gets the direction the Robot is facing. The second line builds a Quaternion representing the rotation from the current direction to the destination direction. The third line actually rotates the Robot.

Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_X;
         Ogre::Quaternion quat = src.getRotationTo(mDirection);
         mNode->rotate(quat);

We briefly mentioned Quaternions in Basic Tutorial 4, but this is the first real use we have had for them. Basically speaking, Quaternions are representations of rotations in 3 dimensional space. They are used to keep track of how the object is positioned in space, and may be used to rotate objects in Ogre. In the first line we call the getOrientation method, which returns a Quaternion representing the way the Robot is oriented in space. Since Ogre has no idea which side of the Robot is the "front" of the robot, we must multiply this orientation by the UNIT_X vector (which is the direction the robot "naturally" faces) to we obtain the direction the robot is currently facing. We store this direction in the src variable. In the second line, the getRotationTo method gives us a Quaternion that represents the rotation from the direction the Robot is facing to the direction we want him to be facing. In the third line, we rotate the node so that it faces the new orientation.

There is only one problem with the code we have created. There is a special case where SceneNode::rotate will fail. If we are trying to turn the robot 180 degrees, the rotate code will bomb with a divide by zero error. In order to fix that, we will test to see if we are performing a 180 degree rotation. If so, we will simply yaw the robot by 180 degrees instead of using rotate. To do this, delete the three lines we just put in and replace them with this:

Ogre::Vector3 src = mNode->getOrientation() * Ogre::Vector3::UNIT_X;
        if ((1.0f + src.dotProduct(mDirection)) < 0.0001f) 
        {
            mNode->yaw(Ogre::Degree(180));
        }
        else
        {
            Ogre::Quaternion quat = src.getRotationTo(mDirection);
            mNode->rotate(quat);
        } // else

All of this should now be self explanatory except for what is wrapped in that if statement. If two unit vectors oppose each other (that is, the angle between them is 180 degrees), then their dot product will be -1. So, if we dotProduct the two vectors together and the result equals -1.0f, then we need to yaw by 180 degrees, otherwise we use rotate instead. Why do I add 1.0f and check to see if it is less than 0.0001f? Don't forget about floating point rounding error. You should never directly compare two floating point numbers. Finally, note that in this case the dot product of these two vectors will fall in the range [-1, 1]. In case it is not abundantly clear, you need to know at minimum basic linear algebra to do graphics programming! At the very least you should review the Quaternion and Rotation Primer and consult a book on basic vector and matrix operations.

Now our code is complete! Compile and run the demo to see the Robot walk the points he was given.

Additional Information

Walking on terrain (aka modifying the robots y-axis)

The code for rotation of the robot will not work properly when also changing the y-axis of the robot. You might see unexpected roll and pitch.
This can be fixed with the code below which was sponsered by the article Quaternion and Rotation Primer.

Vector3 mDestination = mWalkList.front( );                    // mDestination is the next location
Vector3 mDirection = mDestination - mNode->getPosition();     // B-A = A->B (see vector questions above)
Vector3 src = mNode->getOrientation() * Vector3::UNIT_X;      // Orientation from initial direction
src.y = 0;                                                    // Ignore pitch difference angle
mDirection.y = 0;
src.normalise();
Real mDistance = mDirection.normalise( );                     // Both vectors modified so renormalize them
Quaternion quat = src.getRotationTo(mDirection);
 
mNode->rotate(quat);

 

My robot does not face to the direction at the beginning?

The robot is turned when it arrives a waypoint. To properly turn the robot in all cases you best put the rotation code to a new function:

//put this line to the header
void rotateRobotToDirection(void);
 
//this to the application itself
void ITutorial01::rotateRobotToDirection(void) {
  Vector3 src = mNode->getOrientation() * Vector3::UNIT_X;      // Orientation from initial direction
  src.y = 0;                                                    // Ignore pitch difference angle
  mDirection.y = 0;
  src.normalise();
  Real mDistance = mDirection.normalise( );                     // Both vectors modified so renormalize them
  Quaternion quat = src.getRotationTo(mDirection);
 
  mNode->rotate(quat);
}

Now you can use this function in the else-part of "if (! nextLocation())". And you can add it to this part of the code to rotate the robot to the walking direction right at the beginning:

if (mDirection == Ogre::Vector3::ZERO) 
{
  if (nextLocation()) 
  {
    // Set walking animation
    mAnimationState = mEntity->getAnimationState("Walk");
    mAnimationState->setLoop(true);
    mAnimationState->setEnabled(true);
 
    rotateRobotToDirection();
  }
}
else
//...

 

Exercises for Further Study

Easy Questions

  1. Add more points to the robot's path. Be sure to also add more knots that sit under his position so you can track where he is supposed to go.
  2. Robots who have outlived their usefulness should not continue existing! When the robot has finished walking, have him perform the death animation instead of idle. The animation for death is ‘Die’.

 

Intermediate Questions

  1. There is something wrong with mWalkSpeed. Did you notice this when going through the tutorial? We only set the value once, and never change it. This should be a constant static class variable. Change the variable so that it is.
  2. The code does something very hacky, and that's track whether or not the Robot is walking by looking at the mDirection vector and comparing it to Vector3::ZERO. It would have been better if we instead had a boolean variable called mWalking that kept track of whether or not the robot is moving. Implement this change.

 

Difficult Questions

  1. One of the limitations of this class is that you cannot add points to the robot's walking path after you have created the object. Fix this problem by implementing a new method which takes in a Vector3 and adds it to the mWalkList deque. (Hint, if the robot has not finished walking you will only need to add the point to the end of the deque. If the robot has finished, you will need to make him start walking again, and call nextLocation to start him walking again.)

 

Expert Questions

  1. Another major limitation of this class is that it only tracks one object. Reimplement this class so that it can move and animate any number of objects independently of each other. (Hint, you should create another class that contains everything that needs to be known to animate one object completely. Store this in a STL map object so that you can retrieve data later based on a key.) You get bonus points if you can do this without registering any additional frame listeners.
  2. After making the previous change, you might have noticed that Robots can now collide with each other. Fix this by either creating a smart path finding function, or detecting when robots collide and stopping them from passing through each other.

 
Proceed to Intermediate Tutorial 2 RaySceneQueries and Basic Mouse Usage


Alias: Intermediate_Tutorial_1


Contributors to this page: buckybadger1 points  , Spacegaier3733 points  , pera119 points  , onigami1 points  , lingfors11 points  , Jahren186 points  , jacmoe111451 points  and atomr181 points  .
Page last modified on Tuesday 27 of December, 2011 20:49:52 GMT by buckybadger1 points .


The content on this page is licensed under the terms of the Creative Commons Attribution-ShareAlike License.
As an exception, any source code contributed within the content is released into the Public Domain.