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

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!

主站蜘蛛池模板: 元谋县| 太原市| 汉源县| 宾阳县| 开远市| 中阳县| 塘沽区| 垣曲县| 东城区| 临西县| 山阳县| 辰溪县| 富宁县| 田林县| 宜州市| 来安县| 蚌埠市| 南汇区| 将乐县| 满城县| 仁布县| 佛冈县| 平阳县| 芮城县| 马关县| 汝南县| 丹江口市| 克什克腾旗| 石柱| 沙洋县| 奎屯市| 上饶县| 天气| 双流县| 霍林郭勒市| 安塞县| 临城县| 新昌县| 蒲江县| 西乡县| 方正县|