Modifying the Roaming Ralph tutorial to always stay on the terrain.
The code for this tutorial :
# PandAI Author: Srinavin Nair # Original Author: Ryan Myers # Models: Jeff Styers, Reagan Heller
# Last Updated: 6/13/2005 # # This tutorial provides an example of creating a character # and having it walk around on uneven terrain, as well # as implementing a fully rotatable camera. # It uses PandAI pathfinding to move the character.
import direct.directbase.DirectStart from pandac.PandaModulesimport CollisionTraverser,CollisionNode from pandac.PandaModulesimport CollisionHandlerQueue,CollisionRay from pandac.PandaModulesimport Filename from pandac.PandaModulesimport PandaNode,NodePath,Camera,TextNode from pandac.PandaModulesimport Vec3,Vec4,BitMask32 from direct.gui.OnscreenTextimport OnscreenText from direct.actor.Actorimport Actor from direct.task.Taskimport Task from direct.showbase.DirectObjectimport DirectObject importrandom, sys, os, math
#for Pandai from panda3d.aiimport*
SPEED = 0.5
# Figure out what directory this program is in. MYDIR=os.path.abspath(sys.path[0]) MYDIR=Filename.fromOsSpecific(MYDIR).getFullpath()
font = loader.loadFont("cmss12")
# Function to put instructions on the screen. def addInstructions(pos, msg): return OnscreenText(text=msg, style=1, fg=(1,1,1,1), font = font, pos=(-1.3, pos), align=TextNode.ALeft, scale = .05)
# Function to put title on the screen. def addTitle(text): return OnscreenText(text=text, style=1, fg=(1,1,1,1), font = font, pos=(1.3,-0.95), align=TextNode.ARight, scale = .07)
self.title = addTitle("Pandai Tutorial: Roaming Ralph (Walking on Uneven Terrain) working with pathfinding") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Space - do Only once]: Start Pathfinding") self.inst3 = addInstructions(0.85, "[Enter]: Change camera view") #self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") #self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") #self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
# Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions.
# We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal.
#Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value
# Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self):
# Get the time elapsed since last frame. We need this # for framerate-independent movement. elapsed = globalClock.getDt()
# If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. if(self.switchState==False): base.camera.lookAt(self.ralph) if(self.keyMap["cam-left"]!=0): base.camera.setX(base.camera, -(elapsed*20)) if(self.keyMap["cam-right"]!=0): base.camera.setX(base.camera, +(elapsed*20))
# save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something.
startpos = self.ralph.getPos()
# If a move-key is pressed, move ralph in the specified direction.
# If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. if(self.switchState==False): camvec = self.ralph.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if(camdist >10.0): base.camera.setPos(base.camera.getPos() + camvec*(camdist-10)) camdist = 10.0 if(camdist <5.0): base.camera.setPos(base.camera.getPos() - camvec*(5-camdist)) camdist = 5.0
# Now check for collisions.
self.cTrav.traverse(render)
# Adjust ralph's Z coordinate. If ralph's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame.
#print(self.ralphGroundHandler.getNumEntries())
entries = [] for i inrange(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if(len(entries)>0)and(entries[0].getIntoNode().getName() == "terrain"): self.ralph.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.ralph.setPos(startpos)
# Keep the camera at one foot above the terrain, # or two feet above ralph, whichever is greater.