Tutorial Introduction
Ogre Tutorial Head

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. By the end of this tutorial you will be fully familiar with animations and quaternion in Mogre/OGRE.

As you go through the tutorial you should be slowly adding code to your own project and watching the results as we build it. There is no substitute for actual programming to get familiar with these concepts! Resist the urge to simply read along.

If you find any errors in this tutorial please send a private message to amirabiri or McDonte.


  • This tutorial assumes you have knowledge of C# or VB.NET programming and are able to setup and compile a Mogre application.
  • This tutorial also assumes that you have created a project using the Mogre Wiki Tutorial Framework.
  • This tutorial makes use of .NET's LinkedList<T> data structure. While no prior knowledge of how to use it, you should at least know what templates are. This is not needed for animation at all but used in this tutorial.
  • Finally this tutorial assumes you are familiar with the most basic concepts of Ogre/Mogre for example by having read the Mogre Basic Tutorials.

Getting started

Start with a fresh version of the Tutorials Framework. Add a reference to the "System" library which the tutorials framework doesn't link to normally. This library is needed because it provides an implementation of a linked list. Vist msdn for more information.


Animations are actually very simple in Mogre, at least from the programmers point of view. The mesh files contain information about animations that the mesh is capable of. Each animation is simply a series of transformations applied on the vertexes of the mesh based around its "skeleton". These transformations are perceived as animation of the mesh to human eyes. Defining these animation transformations is a tedious job and there are many different techniques to do it. However, once an animator has produced such a series of transformations, it is very simple to use them in code.

To use an animation in code, all we need to do is acquire the AnimationState of the desired animation from the entity object, set its properties and enable it to start the animation. Once the animation is started you have to add time to it in each frame, i.e you will interact with it from a frame listener.

Let's look at a simple example to accomplish this. We will use the robot mesh included in the media folder and use its walking animation. Add the following code to your CreateScene method to set up a simple scene and add the robot to it:

Protected Overrides Sub CreateScene()
	mSceneMgr.AmbientLight = ColourValue.White

	Dim robot = mSceneMgr.CreateEntity("Robot", "robot.mesh")
End Sub

So far there is nothing new, this should all be familiar from the previous tutorials. Since we are going to use the AnimationState object in every frame, we should keep a reference to it. So we need a member variable in the tutorial class to hold this reference:

Dim mAnimationState As AnimationState

Next, we will acquire the AnimationState object that represents the "Walk" animation of the robot mesh. Add the following code to your CreateScene method:

mAnimationState = robot.GetAnimationState("Walk")

The name of the animation is chosen by the animator when they create the animation and it is stored in the .mesh file for vertex animations and in the .skeleton file for skeletal animations. Each mesh file can have different animation names. Whenever you use a mesh file you should find out which animations it has available. There are tools that allow you to view the animations as well which we will use later.

Now that we have a reference to the AnimationState object, how do we actually use it? It's very simple: we set its properties depending on what we want to do, and enable it. In this case we want the robot to be walking continuously, so we set the animation to "loop" by setting its Loop property to true:

mAnimationState.Loop = True

And finally we enable it:

mAnimationState.Enable = True

All we have left to do now is feed our animation time in each frame. With the tutorials framework we can achieve this easily using the UpdateScene method:

Protected Overrides Sub UpdateScene(evt As FrameEvent)
End Sub

And that's all there is to it. Pretty simple isn't it? Your tutorial class should now look something like this:

mAnimationState As AnimationState

Protected Overrides Sub CreateScene()
	mSceneMgr.AmbientLight = ColourValue.White

	Dim robot = mSceneMgr.CreateEntity("Robot", "robot.mesh")

	mAnimationState = robot.GetAnimationState("Walk")
	mAnimationState.Loop = True
	mAnimationState.Enabled = True
End Sub

Protected Overrides Sub UpdateScene(evt As FrameEvent)
End Sub

Compile and run your application. You should see the robot mesh in front of he camera walking in place:


So far about the basics but now we will put this into practise.

Setting up the Scene

Before we begin, notice that we have already defined some variables:

  • mEntity will hold the entity we create,
  • mNode will hold the node we create,
  • mAnimationState will hold the animation state of the object,
  • mDistance will contain the distance from our location to the next waypoint,
  • mDirection will hold the direction the object is moving,
  • mDestination will hold the next waypoint location,
  • mWalkList will contain all the points we wish the object to walk to,
  • mWalkSpeed will hold our speed and
  • mWalking will indicate whether or not we are moving.

Go to the CreateScene method and add the following code to it. All what is done is very simple and is covered in the Basic Tutorials. Take a look there if you are running into problems.

' get the instance of the SceneManager
Dim mgr As SceneManager = Me.mSceneMgr

' set the ambient light
mgr.AmbientLight = ColourValue.White

' create the robot 
Dim ent As Entity = mgr.CreateEntity("Robot", "robot.mesh")
Dim node As SceneNode = mgr.RootSceneNode.CreateChildSceneNode("RobotSceneNode", New Vector3(0F, 0F, 0.25F))

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 .NET's LinkedList, it is an efficient implementation of a doublely linked list that we can use as a two ended queue. We will only be using a few of its methods. The AddFirst and AddLast methods put items at the front and back of the list respectively. The First and Last methods return the items at the front and back of the list respectively. The RemoveFirst and RemoveLast methods remove the items from the front and back of the list respectively. Finally, the Count method returns the number of entries in the list. This code creates the list, and then adds three Vectors to it. We will use these later when we make the robot move.

' create the walking list
mWalkList = New LinkedList(Of Vector3)()
mWalkList.AddLast(New Vector3(550F, 0F, 50F))
mWalkList.AddLast(New Vector3(-100F, 0F, -200F))
mWalkList.AddLast(New Vector3(0F, 0F, 25F))

Next, we want to place some objects on the scene to show where the robot is supposed to be moving. 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 correct place.

' create some knot objects so we can see the robot's movement
ent = mgr.CreateEntity("Knot1", "knot.mesh")
node = mgr.RootSceneNode.CreateChildSceneNode("Knot1Node", New Vector3(0F, -10F, 25F))
node.Scale(0.1F, 0.1F, 0.1F)

ent = mgr.CreateEntity("Knot2", "knot.mesh")
node = mgr.RootSceneNode.CreateChildSceneNode("Knot2Node", New Vector3(550F, -10F, 50F))
node.Scale(0.1F, 0.1F, 0.1F)

ent = mgr.CreateEntity("Knot3", "knot.mesh")
node = mgr.RootSceneNode.CreateChildSceneNode("Knot3Node", New Vector3(-100F, -10F, -200F))
node.Scale(0.1F, 0.1F, 0.1F)

Now compile and run the code. You should see something like this:


Moving the Robot

Now we are going to perform the slightly tricky task of making the robot walk from waypoint to waypoint. Before we begin I would like to re-describe some of the variables that we are storing in the class. We are going to use four variables to accomplish the task of moving the robot. The direction the robot is moving is stored in mDirection. The robot's current destination is stored in mDestination. The distance the robot has left to travel is stored in mDistance. Last but not least, the robot's speed is stored in mWalkSpeed.

TipThere are some nested if-statements in the following code. If you get confused about it, just watch the whole code at the bottom of the page.

Since the variables are already initialized we can use them 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. The NextLocation method is used for this.

Add this code to FrameStarted method just above mAnimationState.AddTime(mDeltaTime) which should be just above the return line:

If Not mWalking Then
' either we've not started walking or reached a way point
' check if there are places to go
    If NextLocation() = True Then
        Dim tmp As LinkedListNode(Of Vector3)

        ' start the walk animation
        mAnimationState = ent.GetAnimationState("Walk")
        mAnimationState.[Loop] = True
        mAnimationState.Enabled = True
        mWalking = True

        ' TO-DO: update the destination using the walklist
    End If
End If

If you compile and run the code right now, the robot will walk in place. This is because the robot starts out with a mWalking = false and our NextLocation method always returns true. In later steps we will be adding a bit more intelligence to the NextLocation method.

Note that we also left a placeholder for the code to update the Robot's destination. We'll get to that later too.

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. We will be adding the following code just after our previous if statement and just above the return line of the method. This code will handle the case when the robot is actually moving, so if mWalking equals true.

Else ' we're in motion				
   ' determine how far to move this frame
    mDistance -= (mWalkSpeed * deltaTime)

Now, we need to check and see if we've arrived at the waypoint. That is, if mDistance is now less than or equal to zero, we need to set the point and setup the move to the next point. Note that we are setting mDirection to the ZERO vector and that we are setting mWalking to false. The robot stops at each waypoint, then checks to see if it has another waypoint. Put this code just after the last one:

' check to see if we've arrived at a waypoint
If mDistance <= 0F Then
    ' set our node to the destination we've just reached and set direction to 0
    node.Position = mDestination
    mDirection = Vector3.ZERO
    mWalking = False
    ' TO-DO: rotation code goes here

    ' TO-DO: movement code goes here
End If

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. Update FrameStarted just below the close of the if statement:

Else ' nowhere to go; set the idle animation
    mAnimationState = ent.GetAnimationState("Idle")
End If

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 travelling, and move it by the amount specified by the move variable. This is accomplished by adding the following code:

    ' TO-DO: rotation code goes here

    ' movement code goes here
    node.Translate(mDirection * mWalkSpeed * deltaTime)
End 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 NextLocation method. This method returns false when we run out of points to go to. This will be the first of code line in our function.

If mWalkList.Count = 0 Then
    Return False
    Return True
End If

First we will extract the destination vector from the front of the LinkedList and then add the LinkedListNode that held it to the end of the list. This will make the robot keep walking around from point to point.
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 FrameStarted? 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.

' update the destination using the walklist.
mDestination = mWalkList.First.Value
' get the next destination.
tmp = mWalkList.First
' save the node that held it
' remove that node from the front of the list
' add it to the back of the list.
' update the direction and the distance
mDirection = mDestination - node.Position
mDistance = mDirection.Normalise()

Now compile and run the code. It works! Mostly... The robot now walks to all the points, but he is always facing the Vector3.UnitX direction (his default). We will need to change the direction he is facing when he is moving towards a new way point.
What we need to do is get the direction the Robot is facing, and use the Rotate function to rotate the object in the right position. Insert the following code where we left the following placeholder comment earlier:

TO-DO: rotation code goes here

Now the code. 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.

Dim src As Vector3 = node.Orientation * Vector3.UNIT_X
Dim quat As Quaternion = src.GetRotationTo(mDirection)

A lot is going on in that small chunk code! A few questions pop into mind. The most pertenant is: "What is a Quaternion?" Basically, Quaternions are representations of rotations in 3 dimensional space. They are used to keep track of how the object is positioned in space. In the first line we call the Orientation property of the SceneNode, which returns a vector representing the way the robot is currently facing. By multiplying it by the UnitX vector, we obtain the direction the robot is currently facing, which we store in src. 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 use the quaternion to 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 DivisionByZeroError. 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 lines we just put in and replace them with this:

' rotation code goes here
Dim src As Vector3 = node.Orientation * Vector3.UNIT_X

If (1F + src.DotProduct(mDirection)) < 0.0001F Then
	Dim quat As Quaternion = src.GetRotationTo(mDirection)
End If

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 ever 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.


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”.

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.)
  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.

[+] Here's the full code


Original version by Clay Culver.
C# changes by DigitalCyborg.
Mogre changes by Djthorn and McDonte.