Hi!
It’s my first steps in learning Panda3d and Python. It based based on FPS_camera_template code, if i found with this forum and of corse on Roaming Ralph tutorial. Thanks for authors.
With WASD keys and mouse you can control Ralph himself and TPS camera. Waiting for critic and/or advises. Das anybody has an idea how i can make Ralph jumping?
Here is code:
from pandac.PandaModules import loadPrcFileData
loadPrcFileData("", "show-frame-rate-meter 1")
from pandac.PandaModules import CollisionTraverser,CollisionNode
from pandac.PandaModules import CollisionHandlerQueue,CollisionRay
from pandac.PandaModules import WindowProperties
from direct.showbase.DirectObject import DirectObject # To listen for Events
from direct.task import Task # To use Tasks
from direct.actor.Actor import Actor
from pandac.PandaModules import Vec3,Vec4,BitMask32
from direct.gui.OnscreenText import OnscreenText
import direct.directbase.DirectStart
from pandac.PandaModules import ConfigVariableString
import sys, os, math
from pandac.PandaModules import Filename
from pandac.PandaModules import PandaNode,NodePath,Camera,TextNode
from direct.gui.OnscreenText import OnscreenText
from direct.task.Task import Task
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):
props = WindowProperties()
props.setCursorHidden(True)
base.win.requestProperties(props)
base.setBackgroundColor(0, 0, 0)
base.disableMouse()
camera.setPos ( 0, 0, 20 )
camera.setHpr ( 0, 0, 0 )
self.heading = 180
self.pitch = 0
self.title = addTitle("Third person shooter template")
self.inst1 = addInstructions(0.95, "[ESC]: Quit")
self.inst2 = addInstructions(0.90, "[A]: Strafe Left")
self.inst3 = addInstructions(0.85, "[D]: Strafe Right")
self.inst4 = addInstructions(0.80, "[W]: Run Forward")
self.inst6 = addInstructions(0.75, "[S]: Run backward")
self.inst7 = addInstructions(0.65, "[Shift]: Acceleration")
self.inst7 = addInstructions(0.55, "[Mouse]: Camera control")
self.keys = {"strafeLeft" : 0, "strafeRight": 0,
"accel": 0, "back": 0, "jump": 0, "run": 0}
self.accept("escape", sys.exit) #Escape quits
#Other keys events set the appropriate value in our key dictionary
self.accept("a", self.setKey, ["strafeLeft", 1])
self.accept("a-up", self.setKey, ["strafeLeft", 0])
self.accept("d", self.setKey, ["strafeRight", 1])
self.accept("d-up", self.setKey, ["strafeRight", 0])
self.accept("w", self.setKey, ["accel", 1])
self.accept("w-up", self.setKey, ["accel", 0])
self.accept("s", self.setKey, ["back", 1])
self.accept("s-up", self.setKey, ["back", 0])
#self.accept("spacebar", self.setKey, ["jump", 1])
#self.accept("spacebar-up", self.setKey, ["jump", 0])
self.accept("shift", self.setKey, ["run", 1])
self.accept("shift-up", self.setKey, ["run", 0])
self.accept("shift-a", self.setKey, ["strafeLeft", 1])
self.accept("shift-a-up", self.setKey, ["strafeLeft", 0])
self.accept("shift-d", self.setKey, ["strafeRight", 1])
self.accept("shift-d-up", self.setKey, ["strafeRight", 0])
self.accept("shift-w", self.setKey, ["accel", 1])
self.accept("shift-w-up", self.setKey, ["accel", 0])
self.accept("shift-s", self.setKey, ["back", 1])
self.accept("shift-s-up", self.setKey, ["back", 0])
self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
self.gameTask.last = 0
self.isMoving = False
self.environ = loader.loadModel("models/world")
self.environ.reparentTo(render)
self.environ.setPos(0,0,0)
self.environ.setScale(5,5,5)
StartPos = self.environ.find("**/start_point").getPos()
# create dummy cam to which the gun can be attached
self.c_node = render.attachNewNode("camera_dummy_node")
self.ralph = Actor("models/ralph",
{"run":"models/ralph-run",
"walk":"models/ralph-walk"})
self.ralph.reparentTo(render)
self.ralph.setScale(1.0)
self.ralph.setHpr(0,0,0)
# Set angles
self.c_node.setHpr(0, 0, 0)
# Attach the camera to the dummy node.
camera.reparentTo(self.c_node)
self.c_node.setPos(StartPos)
self.ralph.setPos(StartPos)
# Position the camera
camera.setPosHpr(Vec3(0,-40,10),Vec3(0,0,0))
self.prevtime = 0
self.cTrav = CollisionTraverser()
self.ralphGroundRay = CollisionRay()
self.ralphGroundRay.setOrigin(0,0,1000)
self.ralphGroundRay.setDirection(0,0,-1)
self.ralphGroundCol = CollisionNode('ralphRay')
self.ralphGroundCol.addSolid(self.ralphGroundRay)
self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
self.ralphGroundColNp = self.c_node.attachNewNode(self.ralphGroundCol)
self.ralphGroundHandler = CollisionHandlerQueue()
self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
# Uncomment this line to see the collision rays
#self.ralphGroundColNp.show()
#Uncomment this line to show a visual representation of the
#collisions occuring
#self.cTrav.showCollisions(render)
def setKey(self, key, val):
self.keys[key] = val
def gameLoop(self, task):
self.elapsed = task.time - self.prevtime
startpos = self.c_node.getPos()
if self.keys["strafeLeft"]:
self.strafe(-1)
if self.keys["strafeRight"]:
self.strafe(1)
if self.keys["accel"]:
self.walk(1)
if self.keys["back"]:
self.walk(-1)
self.MouseTask()
if self.keys["accel"] and self.keys["run"]:
self.walk(2)
if self.keys["back"] and self.keys["run"]:
self.walk(-2)
if self.keys["accel"] or self.keys["strafeLeft"] or self.keys["strafeRight"] or self.keys["back"]:
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
self.cTrav.traverse(render)
# Adjust camera dummy node Z coordinate. If c_node ray hit terrain,
# update his Z. If it hit anything else, or didn't hit anything, put
# it 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"):
h = entries[0].getSurfacePoint(render).getZ()
self.c_node.setZ(h)
self.ralph.setZ(h)
else:
self.c_node.setPos(startpos)
self.ralph.setPos(startpos)
self.MouseTask()
self.prevtime = task.time
return Task.cont
def strafe(self,dir):
elapsed = self.elapsed
strafe = self.c_node.getNetTransform().getMat().getRow3(0)
strafe.setZ(0)
strafe.normalize()
i = strafe*(elapsed*45*dir)
self.c_node.setPos(self.c_node.getPos() + i)
self.ralph.setPos(self.ralph.getPos() + i)
def walk(self,speed):
elapsed = self.elapsed
forward = self.c_node.getNetTransform().getMat().getRow3(1)
forward.setZ(0)
forward.normalize()
i = forward*(elapsed*45*speed)
self.c_node.setPos(self.c_node.getPos() + i)
self.ralph.setPos(self.ralph.getPos() + i)
def MouseTask(self):
try:
x = base.win.getPointer(0).getX()
y = base.win.getPointer(0).getY()
if base.win.movePointer(0, 100, 100):
self.heading = self.heading - (x - 100)*0.2
self.pitch = self.pitch - (y - 100)*0.2
if (self.pitch < -45): self.pitch = -45
if (self.pitch > -3): self.pitch = -3
self.c_node.setHpr(self.heading,self.pitch,0)
self.ralph.setH(self.heading +180)
except: pass
w = World()
run()
also files
- without models (they are from original tutor) http://www.sharemania.ru/0218256 - 4 kb
and full http://www.sharemania.ru/0210689
- 2.63 mb
P.S. Sorry for my bad english