官术网_书友最值得收藏!

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:

  1. Copy the file containing the curve to the models directory of your project and make sure it is named path.egg.
  2. 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)
  3. 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!

主站蜘蛛池模板: 铜川市| 鹤壁市| 梨树县| 六枝特区| 新丰县| 逊克县| 侯马市| 纳雍县| 临朐县| 前郭尔| 凤阳县| 巴楚县| 汝阳县| 密云县| 出国| 静安区| 曲靖市| 洞口县| 中阳县| 水富县| 淮安市| 汝州市| 天峻县| 志丹县| 平潭县| 马龙县| 兴隆县| 锡林郭勒盟| 盖州市| 新干县| 东莞市| 读书| 嵊泗县| 旬阳县| 阿荣旗| 新兴县| 定安县| 长寿区| 红河县| 乐山市| 惠州市|