Apply CollisionTube to "Roaming Ralph" Project

Hello everyone.
I tried to change CollisionRay to CollisionTube by modified these lines below.

self.cTrav = CollisionTraverser()
        self.environ.setCollideMask(BitMask32.bit(1))
        self.ralphGroundRay = CollisionTube(0,0,300,0,0,1000,200)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
self.ralphGroundColNp.show()

But these lines is the same.

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

        entries = []
        for i in range(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() == "terrian"):
            self.ralph.setZ(entries[0].getSurfacePoint(render).getZ())
        else:
            self.ralph.setPos(startpos)

Then I run this application.
I show the BoundingTube(self.ralphGroundColNp.show()) and it isn’t intersect to a terrain.
but a model can’t move .(it play animation normally but stay at the start point.)

Any idea? Help me please…

  1. tube only serves as “into” object, not “from” object. You can use 2 spheres instead, 1 around the torso, and 1 around the head.
  2. is your terrain named “terrian” ?

Here I use CollisionHandlerGravity to handle ray collision, and CollisionHandlerPusher to handle spheres collision.
I created a dummy node above ralph, since CollisionHandlerGravity wants non scaled node, otherwise it would jitter.

import direct.directbase.DirectStart
from pandac.PandaModules import CollisionTraverser,CollisionNode
from pandac.PandaModules import CollisionHandlerQueue,CollisionRay,CollisionHandlerGravity,CollisionHandlerPusher
from pandac.PandaModules import Filename
from pandac.PandaModules import PandaNode,NodePath,Camera,TextNode, CardMaker
from pandac.PandaModules import Vec3,Vec4,BitMask32
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
from direct.task.Task import Task
from direct.showbase.DirectObject import DirectObject
import random, sys, os, math

SPEED = 0.5

# Figure out what directory this program is in.
MYDIR=os.path.abspath(sys.path[0])
MYDIR=Filename.fromOsSpecific(MYDIR).getFullpath()

# Function to put instructions on the screen.
def addInstructions(pos, msg):
    return OnscreenText(text=msg, style=1, fg=(1,1,1,1),
			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),
	                pos=(1.3,-0.95), align=TextNode.ARight, scale = .07)

class World(DirectObject):

    def __init__(self):

        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        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

        self.environ = loader.loadModel(MYDIR+"/models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralphDummy=render.attachNewNode('ralphDummyNode')
        self.ralph = Actor(MYDIR+"/models/ralph",
                                 {"run":MYDIR+"/models/ralph-run",
                                  "walk":MYDIR+"/models/ralph-walk"})
        self.ralph.reparentTo(self.ralphDummy)
        self.ralph.setScale(.2)
        self.ralphDummy.setPos(ralphStartPos)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.prevtime = 0
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralphDummy.getX(),self.ralphDummy.getY()+10,2)

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

        self.cTrav = CollisionTraverser()
        self.environ.setCollideMask(BitMask32.bit(1))

        # ralph's radius
        #________________________
        radius=self.ralph.getSx()*1.3

        # collision ray (handled by gravity handler)
        #________________________
        fromMask=BitMask32.bit(1)
        intoMask=BitMask32.allOff()
        rcn=self.ralphDummy.attachCollisionRay('ralphRay',0,0,2*radius,0,0,-1,fromMask,intoMask)
        self.ralphGroundHandler = CollisionHandlerGravity()
        self.cTrav.addCollider(rcn, self.ralphGroundHandler)
        self.ralphGroundHandler.addCollider(rcn, self.ralphDummy)

        # collision sphere (handled by pusher)
        #________________________
        fromMask=BitMask32.bit(1)
        intoMask=BitMask32.allOff()
        scn1=self.ralphDummy.attachCollisionSphere('bottomSphere',0,0,1.5*radius,radius,fromMask,intoMask)
        scn2=self.ralphDummy.attachCollisionSphere('topSphere',0,0,3.2*radius,radius,fromMask,intoMask)
        self.ralphBodyHandler = CollisionHandlerPusher()
        self.cTrav.addCollider(scn1, self.ralphBodyHandler)
        self.cTrav.addCollider(scn2, self.ralphBodyHandler)
        self.ralphBodyHandler.addCollider(scn1, self.ralphDummy)
        self.ralphBodyHandler.addCollider(scn2, self.ralphDummy)

        self.ralphDummy.showCS()

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()

        #Uncomment this line to show a visual representation of the
        #collisions occuring
        self.cTrav.showCollisions(render)



    #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, task):

        elapsed = task.time - self.prevtime

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        base.camera.lookAt(self.ralph)
        camright = base.camera.getNetTransform().getMat().getRow3(0)
        camright.normalize()
        if (self.keyMap["cam-left"]!=0):
            base.camera.setPos(base.camera.getPos() - camright*(elapsed*20))
        if (self.keyMap["cam-right"]!=0):
            base.camera.setPos(base.camera.getPos() + camright*(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.ralphDummy.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        if (self.keyMap["left"]!=0):
            self.ralphDummy.setH(self.ralphDummy.getH() + elapsed*300)
        if (self.keyMap["right"]!=0):
            self.ralphDummy.setH(self.ralphDummy.getH() - elapsed*300)
        if (self.keyMap["forward"]!=0):
            backward = self.ralphDummy.getNetTransform().getMat().getRow3(1)
            backward.setZ(0)
            backward.normalize()
            self.ralphDummy.setPos(self.ralphDummy.getPos() - backward*(elapsed*5))

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if (self.keyMap["forward"]!=0) or (self.keyMap["left"]!=0) or (self.keyMap["right"]!=0):
            if self.isMoving is False:
                self.ralph.loop("run")
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.ralph.pose("walk",5)
                self.isMoving = False

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.ralphDummy.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.

#         entries = []
#         for i in range(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.

        entries = []
        for i in range(self.camGroundHandler.getNumEntries()):
            entry = self.camGroundHandler.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"):
            base.camera.setZ(entries[0].getSurfacePoint(render).getZ()+1.0)
        if (base.camera.getZ() < self.ralphDummy.getZ() + 2.0):
            base.camera.setZ(self.ralphDummy.getZ() + 2.0)

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        self.floater.setPos(self.ralphDummy.getPos())
        self.floater.setZ(self.ralphDummy.getZ() + 2.0)
        base.camera.lookAt(self.floater)

        # Store the task time and continue.
        self.prevtime = task.time
        return Task.cont


w = World()
run()

Oh! It’s work and beter than before. :open_mouth:
Thank you Thank you very much , Ynjh_jo!! :astonished:

one question plz :frowning:

I c your code and try to use CollisionHandlerGravity()

but my modelActor was shaking
(i change environ and actor to learn code…) :slight_smile:
when i change parameter originZ in collisionRay
(“2*radius” To 0) then it make my modelActor sink in environfloor

plz tell me about parameter in collisionRay
b coz i don’t understand in the manual

and how to fix my problem?plz

sorry my english :frowning:
and thx very much :smiley:

  1. As I wrote, the shaking (jumping) caused by CollisionHandlerGravity which wants non-scaled collision node, so you should create your avatar hierarchy this way :

dummy
|
|
----- actor
|
----- collision node(s)

  1. collision ray started from it’s origin to infinity
    When it’s origin Z is 0, the origin is at your actor’s feet, or exactly on the floor. CollisionHandlerGravity sets the handled node (actor’s dummy node) at most at the collision Z.

Hi

I know this thread is old, but it is the only mention of CollisionHandlerGravity() on the forum.

I was using CollisionHandlerFloor(), and it did the trick mostly, but my character bounced around a lot and falls through floors when the framerate gets low. CollisionHandlerGravity() seems pretty much the same, but the character doesnt bounce around on the spot so much.

When he falls a long way though, he tends to fall right through the floor. Is there some way for me to enable fluid move or something similar?

(I have found CollisionHandlerFluidPusher() which seems good for wall collisions, but I can’t find anything like that for these floor handlers)

Are you using a collision ray against floor polygons, or some other solid? If you aren’t using a ray, there isn’t a %100 failsafe way to guarantee that your object isn’t going to fall through some T-edge crack at some point.
See here. :slight_smile:

I use Gravity, but I’ve never issues with it falling through floors or stability issues with ray->polygon based collisions, no matter how high the impact speed or how low the FPS.

Hmmm, thats interesting. I am using a ray, and it definitely still falls through the floors sometimes. my code for the ray looks like this:

        fromMask=BitMask32.bit(1)
        intoMask=BitMask32.allOff()
        collisionRay=self.character.attachCollisionRay('characterRay',0,0,5,0,0,-1,fromMask,intoMask)
        collisionRay.show()
        self.characterGroundHandler = CollisionHandlerGravity()
        base.cTrav.addCollider(collisionRay, self.characterGroundHandler)
        self.characterGroundHandler.addCollider(collisionRay, self.character) 

character is an “actor” object

That looks right to me – You’ve got a ray going from 5 units up, going in a negative-Z direction. (Assuming you are using standard Panda3d axis of Z+ for up, Y+ for forward.)

Have you checked your level collision geometry? Maybe some surfaces aren’t manifold or contain invisible cracks? (Try merging vertices, in your modeler of choice.) I would simplify the level geometry and see if this still occurs. I don’t have any trouble with ray-based items moving around standard terrain generated from triangles. But you to remember, a ray can still pierce collision polygons if there is any kind of discontinuity.

Check my boxman demo and see if behaves the same way on your system. He runs around using the GravityWalker class, which is based on CollisionGravityPusher. It’s stable to me.