Hello all, I’m not new to coding, however this is my 2nd time using python ever.
Well here we go, my original question is mute. however.
i am running into a slight problem with a code i found at[url]Oh my god!]
Pretty much im attempting to use that code as a basis for movement.
however when i boot up the game i get the following
traceback most recent call last:
file momma.py, line 195 in (module)
World()#no need to store to a variable
file momme.py,line 160 in __init__
self.avatar = Avatar()
nameerror: global name 'Avatar' is not defined
Now i tried to find out how to fix the issue with the player but to no aval
here is my code so far, any help would be great!
import direct.directbase.DirectStart
from panda3d.core import CollisionTraverser,CollisionNode
from panda3d.core import CollisionHandlerQueue,CollisionRay
from panda3d.core import Filename,AmbientLight,DirectionalLight
from panda3d.core import PandaNode,NodePath,TextNode
from panda3d.core import Vec3,Vec4,BitMask32
from direct.gui.OnscreenText import OnscreenText
from direct.actor.Actor import Actor
from direct.showbase.DirectObject import DirectObject
import random, sys, os, math
from CameraHandlerClass import CameraHandler
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGui import *
from direct.showbase.DirectObject import DirectObject
from pandac.PandaModules import *
#VVVfullscreen
import platform
from pandac.PandaModules import loadPrcFileData
loadPrcFileData('','show-frame-rate-meter 1')
#fullscreenstuff
from pandac import PandaModules as P #alias PandaModules as P
import direct.directbase.DirectStart # Start Panda
from direct.showbase.DirectObject import DirectObject # To listen for Events
from direct.task import Task # To use Tasks
from direct.actor import Actor # To use animated Actors
from direct.interval import LerpInterval as LERP#alias LerpInterval as LERP
from direct.fsm import FSM# To use Finite State Machines.
from direct.showbase.PythonUtil import clampScalar#useful.
base.cTrav = P.CollisionTraverser()#initialize traverser
#Collision detection can fail if objects move too fast. (Quantum tunnelling.)
base.cTrav.setRespectPrevTransform(1)#fluid move prevents quantum tunnelling.
#Global collision handlers.
Pusher = P.CollisionHandlerPusher()#Pusher keeps its ward out of things.
Floor = P.CollisionHandlerFloor()#Floor keeps its ward grounded.
#collision masks. Use a bitwise or (operator | ) if more than one apply.
AllM = P.BitMask32.bit(0)#for everything in the world, except display elements
GroundM = P.BitMask32.bit(1)#the ground. What the floor rays collide with.
PusherM = P.BitMask32.bit(2)#Solid objects, but not the ground.
CameraM = P.BitMask32.bit(3)#What shouldn't be between camera and avatar.
#setup keyboard and mouse
SPEED = 0.5
class World(DirectObject):
def __init__(self):
#initialize movement variables
self.speed = speed #moving speed
self.point = dest#destination
self.vel = P.Vec3.zero()#velocity
#You must call FSM init if you override init.
FSM.FSM.__init__(self,'avatar')
#Avatar scenegraph setup.
self.prime=P.NodePath('avatar prime')#prime: Avatar's primary nodepath.
self.prime.reparentTo(render)#Make Avatar visible.
self.prime.setZ(iniHight)#Be sure to start above the floor.
self.__initActor(**act)#unpacks act dictionary as optional params
self.__initSolids(**solid)#same with solid
#default to standing state instead of off.
self.request('Stand')
camHandler = CameraHandler()
# Post the instructions
self.title = addTitle("L.O.T.C: Engine V0.001")
self.inst1 = addInstructions(0.95, "[ESC]: Quit")
self.inst2 = addInstructions(0.90, "Rewrite Mouse movement")
self.inst3 = addInstructions(0.85, "Radar, one click movement")
self.inst4 = addInstructions(0.80, "lock camera on space to jebus")
def __initActor(self,model='models/ralph',
hprs=(180,0,0,.2,.2,.2),#ralph's Y is backward and he's too big.
anims={"run":"models/ralph-run","walk":"models/ralph-walk"}):
self.myActor=Actor.Actor(model,anims)
self.myActor.setHprScale(*hprs)
self.myActor.reparentTo(self.prime)#parent actor to the prime
def __initSolids(self,ray=(0, 0, 1.3, 0, 0, -1),sphere=(0,0,.7,.4)):
"""Only seperate for organisation, treat it as is part of __init__() .
Set collision solids for the avatar."""
#Ralph will have collision solids, so the
# visible geometry shouldn't collide at all.
self.prime.setCollideMask(P.BitMask32.allOff())
# to collide with the terrain & keep ralph grounded
fromCol(self.prime,Floor,P.CollisionRay(*ray),AllM|GroundM)
#The ground and walls should have separate collision masks otherwise
# Pusher can interfere with Floor if the ground gets too steep.
#The sphere is set to collide with the other things in
# the world which have mask PusherM
fromCol(self.prime,Pusher,P.CollisionSphere(*sphere),PusherM)
def update(self,dt):
"""Call this method in your main loop task."""
self.prime.setFluidPos(#fluidly update position based on velocity
self.prime.getX()+self.vel.getX()*dt,
self.prime.getY()+self.vel.getY()*dt,
self.prime.getZ() )#let Floor worry about Z
#recalc velocity to point to destination
self.vel = self.point-self.prime.getPos()
if self.vel.lengthSquared()<.1:#Then consider yourself arrived.
self.request('Stand')#change FSM state
self.vel=P.Vec3.zero()#stop moving.
else:
self.vel.normalize()#set magnitude to 1
self.vel*=self.speed#the magnitude of velocity is speed.
def setDestination(self,point):
"""Go to the point."""
self.point = point
pr = self.prime.getP(),self.prime.getR()#to preserve pitch and roll
self.prime.lookAt(self.point)#lookAt affects all three (HPR)
#keep heading but revert pitch and roll.
self.prime.setHpr(self.prime.getH(),*pr)
#subtracting points yeilds a vector pointing from the 1st to the 2nd
self.vel = self.point-self.prime.getPos()#destination from position
self.vel.normalize()#set magnitude to 1
self.vel*=self.speed#the magnitude of velocity is speed.
self.request('Run')#change FSM state
## State handlers. Only define them if something happens at that transition.
def enterRun(self):
self.myActor.loop("run")#loop the run animation
def exitRun(self):
self.myActor.stop("run")#stop the run animation
def enterStand(self):
self.myActor.pose("walk",6)#both feet on the floor
#notice that no def exitStand is required.
class Environ:
def __init__(self):
self.prime = loader.loadModel("models/world")
self.prime.reparentTo(render)
#break the model into the named pieces
for word in ('terrain','tree','wall','rock','hedge'):
setattr(self,word,self.prime.find('**/%s*'%word))#isn't python fun?
#set the collideMasks of the pieces individually
self.terrain.setCollideMask(AllM|GroundM|CameraM)#Ground and walls \
self.wall.setCollideMask(AllM|PusherM|CameraM)#should never be between\
self.rock.setCollideMask(AllM|PusherM|CameraM)#camera and avatar.
#But it doesn't matter if a tree is in the way. Let the player worry\
self.tree.setCollideMask(AllM|PusherM)#about that. Besides, geom test\
self.hedge.setCollideMask(AllM|PusherM)#for doodads is too expensive.
#end Environ
class Marker:
def __init__(self):
#you probably want to use a different marker model
self.prime = loader.loadModel('jack')
self.prime.reparentTo(render)
self.prime.setScale(.1,.1,.1)
#this is just a display element, so it shouldn't affect the world.
self.prime.setCollideMask(P.BitMask32.allOff())#no collisions!
#end Marker
class World(DirectObject):
def __init__(self):
self.avatar = Avatar()#setup ralph
self.environ = Environ().prime#load environ
self.marker = Marker().prime#load marker
EdgeScreenTracker(self.avatar.prime,P.Point3(0,0,1))#setup camera
self.__setupPicking()
self.last = 0#for calculating dt in gameLoop
taskMgr.add(self.gameLoop, "gameLoop")#start the gameLoop task
def __setupPicking(self):
self.pickerQ = P.CollisionHandlerQueue()#the handler
self.picker=fromCol(camera,self.pickerQ,P.CollisionRay(),GroundM)
self.accept('click',self.OnClick)#translated
####uncomment this line to show the collisions:
##base.cTrav.showCollisions(render)
def OnClick(self):
"""Handle the click event."""
mpos=base.mouseWatcherNode.getMouse()#mouse's screen coordinates
#This makes the ray's origin the camera and makes the ray point to mpos
self.picker.node().getSolid(0).setFromLens(
base.camNode,mpos.getX(),mpos.getY())
#We don't want to traverse now, so wait for panda to do it, then move.
taskMgr.doMethodLater(.02,self.__setDestination,'setDest')
def __setDestination(self,task):
#find the position of the nearest intersection in renderspace
if self.pickerQ.getNumEntries() > 0:
self.pickerQ.sortEntries() #this is so we get the closest object
self.point=self.pickerQ.getEntry(0).getSurfacePoint(render)
self.marker.setPos(self.point)#marker indicates destination
self.avatar.setDestination(self.point)#set the destination
def gameLoop(self,task):
"""The main game loop."""
dt = task.time - self.last#time elapsed since the last frame.
self.last = task.time#for calculating dt the next time
self.avatar.update(dt)#allow avatar to update itself
return direct.task.Task.cont#task must return cont to continue a loop
#end World
World()#no need to store to a variable
run()