
Making objects follow a predefined path
In this recipe we will see how to move a model along a line, typically referred to as a path, stored in Panda3D's model format. This can come in very handy for setting paths of non-player characters inside a level. Another common use of this is to attach the camera to a path and make it fly through the game world smoothly.
Getting ready
To follow this recipe you first have to set up a project as described in Setting up the game structure. In addition, you need to create a curve in Maya or Blender and export it to Panda3D's .egg
file format. In case you don't have these tools or do not know how to work with them, here's a sample curve you can paste into a text editor and save it as path.egg
:
<CoordinateSystem> { Z-up } <Group> Curve { <VertexPool> Curve { <Vertex> 0 { -2.66117048264 -0.964361846447 0.0 1.0 } <Vertex> 1 { 1.8930850029 -0.948404431343 0.0 1.0 } <Vertex> 2 { 10.3484048843 1.0 0.0 1.0 } <Vertex> 3 { -3.6957449913 0.0 0.0 1.0 } } <NURBSCurve> { <Order> { 4 } <Knots> { 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 } <VertexRef> { 0 1 2 3 <Ref> { Curve }} } }
How to do it...
Making objects follow a predefined path can be done like the following:
- Copy the file containing the curve to the
models
directory of your project and make sure it is namedpath.egg
. - Copy the following code to
Application.py
:from direct.showbase.ShowBase import ShowBase from direct.actor.Actor import Actor from direct.directutil.Mopath import Mopath from direct.interval.IntervalGlobal import * class Application(ShowBase): def __init__(self): ShowBase.__init__(self) self.smiley = self.loader.loadModel("smiley") self.smiley.reparentTo(render) self.mopath = Mopath() self.mopath.loadFile("path.egg") self.ival = MopathInterval(self.mopath, self.smiley, duration = 10) self.ival.loop() self.cam.setPos(0, -20, 0)
- Press F6 to start the program. The smiley model will follow the path.
How it works...
All it takes for you to use predefined paths is to create a Mopath
object and load the file containing the curve you want your object to follow. Then you pass the Mopath
object to a MopathInterval
that is responsible for interpolating the model position along the path over the specified duration. That's it—it's that easy!