Getting started

Hi, i’m trying to understand Panda and Python, but there problems I dont get yet, so was wounding if you can help me out? (Sorry about my English)

  1. I can get a environment model loaded and then the panda actor in my level but, I dont get how you would go about Controlling the camera or the panda? I was wounding if someone could write me a really simple tutorial on how you would go about moving them with the arrow keys or the wasd ones please ^^:

Also, I was wounding where I can get more information on python, with simple tutorials/examples.

  1. look at the Feature-Tutorials–Roaming-Ralph
  2. diveintopython.org/

Thanks ^^: I look at the Roaming-Ralph tutorial that came with the program and see what would happen. I keep getting a gray screen when I try using the code with mine, so maybe you can take a look at it?

import direct.directbase.DirectStart
from pandac.PandaModules import CollisionTraverser,CollisionNode
from pandac.PandaModules import CollisionHandlerQueue,CollisionRay
from pandac.PandaModules import Filename
from pandac.PandaModules import PandaNode,NodePath,Camera,TextNode
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("town.x")      
        self.environ.reparentTo(render)
        self.environ.setScale(0.25,0.25,0.25) 
        self.environ.setPos(-8,0,0)


        # Create the main character, Ralph
        ralphStartPos = self.environ.find("0,0,0").getPos()
        self.ralph = Actor("models/panda-model",{"run":"models/panda-walk4",                                                  "walk":"models/panda-walk4"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.001)
        self.ralph.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()

    #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.ralph.getPos()

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

        if (self.keyMap["left"]!=0):
            self.ralph.setH(self.ralph.getH() + elapsed*300)
        if (self.keyMap["right"]!=0):
            self.ralph.setH(self.ralph.getH() - elapsed*300)
        if (self.keyMap["forward"]!=0):
            backward = self.ralph.getNetTransform().getMat().getRow3(1)
            backward.setZ(0)
            backward.normalize()
            self.ralph.setPos(self.ralph.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.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.

        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.ralph.getZ() + 2.0):
            base.camera.setZ(self.ralph.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.ralph.getPos())
        self.floater.setZ(self.ralph.getZ() + 2.0)
        base.camera.lookAt(self.floater)

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



run()

“I keep getting a gray screen” but i done know what the gaol is. Besides you need to learn to help your self. I suggest take a tutorial and just mess with it. Make Ralph move slower or faster. Change ralph model and etc. Not just “oh my code does not work what do it do?”. It obviously not a graphics related bug that nothing is showing up. Ralph works just play with it. Find out how panda works and once you have real problems come back to us :slight_smile:

Sorry to sound harsh but you need to find bugs like this on your own :slight_smile:

lol I know, i’m not new to coding (small C++ things), its just I been at this for a long time and was getting no where on my own. See I loaded a new map town.x and loaded panda as the guy. (I can do that just fine with out the help of the tutorial). So I went to try and added the code to have the camera follow or move the camera on my own. I can do it with the normal setup but they use .egg with their files for the collision and I used .x so I took that code out and compiled it, by my thought it should work? but instead I get a gray screen?

I never said it was a bug bug I just dont get why I get a gray screen. I also have change the little person into the panda too with the tutorial.

loader.loadModel(“town.x”)
i dont think town has efficient collision detection

ralphStartPos = self.environ.find(“0,0,0”).getPos()
what you are looking for a node named “0,0,0” in the root of town? i think root of town is called town
ralphStartPos = Vec3(0,0,0)

Actor(“models/panda-model”,{“run”:“models/panda-walk4”,
“walk”:“models/panda-walk4”})

are you sure you have exported the panda module correctly with a “walk4” animation?

maybe messing with this tutorial is a bad idea…

1)I know my town.x doesnt have efficient collision detection…so maybe thats making him fall into the void itself?

2)Ok didnt know that half…thanks for the tip…

  1. Yea, it works when I change it in the tutorial into the panda, just looks a little funny.

  2. X.x; sorry, trying to understand panda with what I been given with.

Are you expecting your World class to run ?
There isn’t any instantiation yet …

Hehe, nice find!
This should do the trick: (at the end of the file)

World()
run() 

Cool, sorta lol, now I get a error:
ralphStartPos = self.environ.find(“0,0,0”).getPos()
AssertionError: !is_empty() at line 944 of panda/src/pgraph/nodePath.cxx

I don’t get it?

  1. Comment the following code

ralphStartPos = self.environ.find("0,0,0").getPos() 
  1. Change
self.ralph.setPos(ralphStartPos)

to

self.ralph.setPos(0,0,0)

This will atleast remove your current error.
But beware there are more to follow.

Yea I thought so, I kinda took the Roaming-Ralph tutorial and changed it up so it work with what I was trying to do with no real understanding what was going on. (Why I kinda ask for examples on the controling of the camera or the panda that way I didnt get one big confusing example.) As for number one, I was trying to set it up so it started at 0,0,0 spot as my town was -8,0,0…

I still get the following error:
ralphStartPos = self.environ.find(“0,0,0”).getPos()
AssertionError: !is_empty() at line 944 of panda/src/pgraph/nodePath.cxx

Thanks for the help.

I guess you haven’t done the changes that I specified in the last post.

Change
ralphStartPos = self.environ.find(“0,0,0”).getPos()
to
#ralphStartPos = self.environ.find(“0,0,0”).getPos()

and
self.ralph.setPos(ralphStartPos)
to
self.ralph.setPos(0,0,0)

and then see what errors occur

Oh><; I thought I did. I miss understood what you meant by the comment thing sorry, thought you wanted me to say something about why it was there.

Ok now I get the following errors:
File “town.py”. line 202 in ?
run()
File “C:\Panda3d-1.4.2\direct\src\showbase\ShowBase.pr”, line 2176 in run self.taskMgr.run()
File “C:\Panda3d-1.4.2\direct\src\task\Task.py”, line 930, in run self.step()
File “C:\Panda3d-1.4.2\direct\src\task\Task.py”, line 862, in stepself._stepThroughList(taskPriList)
File “C:\Panda3d-1.4.2\direct\src\task\Task.py”, line 764, in _stepThroughList ret = self._executeTask(task)
File “C:\Panda3d-1.4.2\direct\src\task\Task.py”, line 684, in _stepThroughList ret = Task(*task.extraArgs)
File “town.py”, line 157, in move self.cTrav.traverse(render)
AttributeError: World instance has no attribute ‘cTrav’

I am not sure what exactly you want to do.
Anyways, if you only want your environment/actor to be loaded successfully then

Comment all this one block of code starting from

self.cTrav.traverse(render)

to
base.camera.setZ(self.ralph.getZ() + 2.0)

including the statements given above.
I hope this helps.

Oh I think I found the error. Its working anycase. I left some of the old code behind by mistake.

As for what I was doing, see I just wanted to control ralph (or the panda by changing the modles/actors) with in my own world instead of the one the example makes (town.x). I didnt use .egg so the old collison code was messing up… I think, or some of the code I thought I got was still calling for things that wasn’t there.

I think theres some things still mess up with in the code cus when I go forward, its a awfully slow, I change the speed, but it doesn’t seem to do much?

import direct.directbase.DirectStart 
from pandac.PandaModules import CollisionTraverser,CollisionNode 
from pandac.PandaModules import CollisionHandlerQueue,CollisionRay 
from pandac.PandaModules import Filename 
from pandac.PandaModules import PandaNode,NodePath,Camera,TextNode 
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 = 2

# 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("town.x")      
        self.environ.reparentTo(render) 
        self.environ.setScale(0.25,0.25,0.25) 
        self.environ.setPos(-8,0,0) 


        # Create the main character, Ralph 
        # ralphStartPos = self.environ.find("0,0,0").getPos() 
        self.ralph = Actor("models/panda-model",{"run":"models/panda-walk4",                            

                      "walk":"models/panda-walk4"}) 
        self.ralph.reparentTo(render) 
        self.ralph.setScale(.001) 
        self.ralph.setPos(0,0,0) 

        # 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() 

    #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.ralph.getPos() 

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

        if (self.keyMap["left"]!=0): 
            self.ralph.setH(self.ralph.getH() + elapsed*300) 
        if (self.keyMap["right"]!=0): 
            self.ralph.setH(self.ralph.getH() - elapsed*300) 
        if (self.keyMap["forward"]!=0): 
            backward = self.ralph.getNetTransform().getMat().getRow3(1) 
            backward.setZ(0) 
            backward.normalize() 
            self.ralph.setPos(self.ralph.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.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 

        
        # 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.ralph.getPos()) 
        self.floater.setZ(self.ralph.getZ() + 2.0) 
        base.camera.lookAt(self.floater) 

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


World()
run() 

lmao actully I think I jsut did what you said just I took the code out. o.O