def setupCollHandlers(self): ###### Collisions ###### base.cTrav = CollisionTraverser() self.collisionHandler = CollisionHandlerEvent() self.wallHandler = CollisionHandlerPusher() self.collisionHandler.addInPattern('%fn-into-%in') # this is on the other hand the relative call for the OUT event, as is when the FROM object (heart) goes OUT the INTO oject (heart). self.collisionHandler.addOutPattern('%fn-out-%in')
def setupWallSphere(self, bitmask, avatarRadius): self.avatarRadius = avatarRadius cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius) cSphereNode = CollisionNode('Flyer.cWallSphereNode') cSphereNode.addSolid(cSphere) cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) if config.GetBool('want-fluid-pusher', 0): self.pusher = CollisionHandlerFluidPusher() else: self.pusher = CollisionHandlerPusher() self.pusher.addCollider(cSphereNodePath, self.avatarNodePath) self.cWallSphereNodePath = cSphereNodePath
def setupCollHandlers(self): ###### Collisions ###### base.cTrav = CollisionTraverser() self.collisionHandler = CollisionHandlerEvent() self.wallHandler = CollisionHandlerPusher() self.collisionHandler.addInPattern("%fn-into-%in") # this is on the other hand the relative call for the OUT event, as is when the FROM object (heart) goes OUT the INTO oject (heart). self.collisionHandler.addOutPattern("%fn-out-%in")
def createCollisionHandlers(self): # Create a new collision traverser instance. We will use this to determine # if any collisions occurred after performing movement. self.cTrav = CollisionTraverser() camGroundRay = CollisionRay() camGroundRay.setOrigin(0, 0, 1000) camGroundRay.setDirection(0, 0, -1) camGroundCol = CollisionNode('camRay') camGroundCol.addSolid(camGroundRay) camGroundCol.setFromCollideMask(BitMask32.bit(0)) camGroundCol.setIntoCollideMask(BitMask32.allOff()) camGroundColNp = base.camera.attachNewNode(camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(camGroundColNp, self.camGroundHandler) # register the collision pusher self.pusher = CollisionHandlerPusher() # register collision event pattern names self.pusher.addInPattern('col-%fn-into')
class characterCollSystem(): def __init__(self,rootNode,trav,id): self.GroundRay=CollisionRay(0,0,10,0,0,-1) self.GroundCol = CollisionNode('colDown_'+str(id)) self.GroundCol.addSolid(self.GroundRay) self.GroundCol.setFromCollideMask(BitMask32.bit(1)) self.GroundCol.setIntoCollideMask(BitMask32.allOff()) self.GroundColNp = rootNode.attachNewNode(self.GroundCol) #self.GroundColNp.show() self.GroundHandler = CollisionHandlerQueue() trav.addCollider(self.GroundColNp, self.GroundHandler) self.EnvDetector=CollisionSphere(0, 0, 1, 0.8) self.EnvCol = CollisionNode('colEnv_'+str(id)) self.EnvCol.addSolid(self.EnvDetector) self.EnvCol.setFromCollideMask(BitMask32.bit(2)) self.EnvCol.setIntoCollideMask(BitMask32.allOff()) self.EnvColNp = rootNode.attachNewNode(self.EnvCol) #self.EnvColNp.show() self.pusher = CollisionHandlerPusher() self.pusher.addCollider(self.EnvColNp, rootNode) trav.addCollider(self.EnvColNp, self.pusher) self.trav=trav
class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Panda settings base.setBackgroundColor(0.6, 0.6, 0.6) base.cam.setPos(0, 0, 100) base.cam.setHpr(0, -90, 0) # Setup keys for moving localPlayer self.setupKeys() # Setup collision handlers self.setupCollHandlers() # Load localPlayer self.setupPlayer() # Setup dna parser self.dnaParser = DNAParser(self) # Load default room self.dnaParser.createRoom('dna/room_yellow_castle.yaml') # Setup collision colliders self.setupColliders() def setupKeys(self): # This is used to store which keys are currently pressed. self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0} self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) taskMgr.add(self.moveTask, "moveTask") def setupCollHandlers(self): ###### Collisions ###### base.cTrav = CollisionTraverser() self.collisionHandler = CollisionHandlerEvent() self.wallHandler = CollisionHandlerPusher() self.collisionHandler.addInPattern('%fn-into-%in') # this is on the other hand the relative call for the OUT event, as is when the FROM object (heart) goes OUT the INTO oject (heart). self.collisionHandler.addOutPattern('%fn-out-%in') def setupPlayer(self): # Load up player class self.localPlayer = LocalPlayer() # Load up player object self.localPlayer.loadPlayerModel(PlayerModel) # Make player object avalible to this class self.player = self.localPlayer.player # Set player color self.localPlayer.setPos(PlayerPos) # Setup player collisions self.localPlayer.setCollisions() # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Moves the player around def moveTask(self, task): dt = globalClock.getDt() if self.keyMap["left"]: self.player.setX(self.player.getX() - PlayerWalkSpeed) if self.keyMap["right"]: self.player.setX(self.player.getX() + PlayerWalkSpeed) if self.keyMap["forward"]: self.player.setY(self.player.getY() + PlayerWalkSpeed) if self.keyMap["backward"]: self.player.setY(self.player.getY() - PlayerWalkSpeed) return task.cont # Dose basic setup for the next room and keeps # the player avatar in place! def transition(self, newroom, exittunnel, coll): self.dnaParser.createRoom(newroom) self.positionCalculator(exittunnel) # Calculates where to place the player when he leaves a tunnel def positionCalculator(self, tunnel): # Get position of tunnel the player is exiting from tunnelNode = render.find(tunnel) tunnelX = tunnelNode.getX() tunnelY = tunnelNode.getY() tunnelhpr = tunnelNode.getH() if tunnelhpr == 90: if self.player.getX() > tunnelX: self.player.setX(tunnelX + 5) else: self.player.setX(tunnelX - 5) else: if self.player.getY() > tunnelY: self.player.setY(tunnelY + 5) else: self.player.setY(tunnelY - 5) def setupColliders(self): # Tell collider what to check for # TEMP # playerCollider = self.localPlayer.playerCollider playerSensor = self.localPlayer.playerSensor # Tell the wallHandler what to collide with self.wallHandler.addCollider(playerCollider, self.player) # Adding to trav turns it into a from object( moving object ) base.cTrav.addCollider(playerCollider, self.wallHandler) # Adding to trav turns it into a from object( moving object ) base.cTrav.addCollider(playerSensor, self.collisionHandler)
class CogdoFlyingCollisions(GravityWalker): wantFloorSphere = 0 def __init__(self): GravityWalker.__init__(self, gravity=0.0) def initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius = 1.4, floorOffset = 1.0, reach = 1.0): self.cHeadSphereNodePath = None self.cFloorEventSphereNodePath = None self.setupHeadSphere(avatarNodePath) self.setupFloorEventSphere(avatarNodePath, ToontownGlobals.FloorEventBitmask, avatarRadius) GravityWalker.initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius, floorOffset, reach) def setupWallSphere(self, bitmask, avatarRadius): self.avatarRadius = avatarRadius cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius) cSphereNode = CollisionNode('Flyer.cWallSphereNode') cSphereNode.addSolid(cSphere) cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) if config.GetBool('want-fluid-pusher', 0): self.pusher = CollisionHandlerFluidPusher() else: self.pusher = CollisionHandlerPusher() self.pusher.addCollider(cSphereNodePath, self.avatarNodePath) self.cWallSphereNodePath = cSphereNodePath def setupEventSphere(self, bitmask, avatarRadius): self.avatarRadius = avatarRadius cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius * 1.04) cSphere.setTangible(0) cSphereNode = CollisionNode('Flyer.cEventSphereNode') cSphereNode.addSolid(cSphere) cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.event = CollisionHandlerEvent() self.event.addInPattern('enter%in') self.event.addOutPattern('exit%in') self.cEventSphereNodePath = cSphereNodePath def setupRay(self, bitmask, floorOffset, reach): cRay = CollisionRay(0.0, 0.0, 3.0, 0.0, 0.0, -1.0) cRayNode = CollisionNode('Flyer.cRayNode') cRayNode.addSolid(cRay) self.cRayNodePath = self.avatarNodePath.attachNewNode(cRayNode) cRayNode.setFromCollideMask(bitmask) cRayNode.setIntoCollideMask(BitMask32.allOff()) self.lifter = CollisionHandlerGravity() self.lifter.setLegacyMode(self._legacyLifter) self.lifter.setGravity(self.getGravity(0)) self.lifter.addInPattern('%fn-enter-%in') self.lifter.addAgainPattern('%fn-again-%in') self.lifter.addOutPattern('%fn-exit-%in') self.lifter.setOffset(floorOffset) self.lifter.setReach(reach) self.lifter.addCollider(self.cRayNodePath, self.avatarNodePath) def setupHeadSphere(self, avatarNodePath): collSphere = CollisionSphere(0, 0, 0, 1) collSphere.setTangible(1) collNode = CollisionNode('Flyer.cHeadCollSphere') collNode.setFromCollideMask(ToontownGlobals.CeilingBitmask) collNode.setIntoCollideMask(BitMask32.allOff()) collNode.addSolid(collSphere) self.cHeadSphereNodePath = avatarNodePath.attachNewNode(collNode) self.cHeadSphereNodePath.setZ(base.localAvatar.getHeight() + 1.0) self.headCollisionEvent = CollisionHandlerEvent() self.headCollisionEvent.addInPattern('%fn-enter-%in') self.headCollisionEvent.addOutPattern('%fn-exit-%in') base.cTrav.addCollider(self.cHeadSphereNodePath, self.headCollisionEvent) def setupFloorEventSphere(self, avatarNodePath, bitmask, avatarRadius): cSphere = CollisionSphere(0.0, 0.0, 0.0, 0.75) cSphereNode = CollisionNode('Flyer.cFloorEventSphere') cSphereNode.addSolid(cSphere) cSphereNodePath = avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.floorCollisionEvent = CollisionHandlerEvent() self.floorCollisionEvent.addInPattern('%fn-enter-%in') self.floorCollisionEvent.addAgainPattern('%fn-again-%in') self.floorCollisionEvent.addOutPattern('%fn-exit-%in') base.cTrav.addCollider(cSphereNodePath, self.floorCollisionEvent) self.cFloorEventSphereNodePath = cSphereNodePath def deleteCollisions(self): GravityWalker.deleteCollisions(self) if self.cHeadSphereNodePath != None: base.cTrav.removeCollider(self.cHeadSphereNodePath) self.cHeadSphereNodePath.detachNode() self.cHeadSphereNodePath = None self.headCollisionsEvent = None if self.cFloorEventSphereNodePath != None: base.cTrav.removeCollider(self.cFloorEventSphereNodePath) self.cFloorEventSphereNodePath.detachNode() self.cFloorEventSphereNodePath = None self.floorCollisionEvent = None self.cRayNodePath.detachNode() del self.cRayNodePath self.cEventSphereNodePath.detachNode() del self.cEventSphereNodePath def setCollisionsActive(self, active = 1): if self.collisionsActive != active: if self.cHeadSphereNodePath != None: base.cTrav.removeCollider(self.cHeadSphereNodePath) if active: base.cTrav.addCollider(self.cHeadSphereNodePath, self.headCollisionEvent) if self.cFloorEventSphereNodePath != None: base.cTrav.removeCollider(self.cFloorEventSphereNodePath) if active: base.cTrav.addCollider(self.cFloorEventSphereNodePath, self.floorCollisionEvent) GravityWalker.setCollisionsActive(self, active) def enableAvatarControls(self): pass def disableAvatarControls(self): pass def handleAvatarControls(self, task): pass
def __init__(self): # Load the environment model. environ = loader.loadModel("zebrafishEnviron17_100contrast") environ.reparentTo(render) environ.setScale(1, 1, 1) environ.setPos(0, 0, 0) # Load AVI texture self.tex1 = loader.loadTexture("VRE_autoPA_bigFish.avi") self.tex2 = loader.loadTexture("VRE_autoPA_hE.avi") self.tex3 = loader.loadTexture("VRE_autoPA_vE.avi") self.tex4 = loader.loadTexture("VRE_autoPA_bigFeeding.avi") self.texBG = loader.loadTexture("VRE_autoPA_realFishBG.jpg") self.texBG4 = loader.loadTexture("VRE_autoPA_feedingBG.jpg") self.sound1 = loader.loadSfx("VRE_autoPA_realFish.avi") self.sound2 = loader.loadSfx("VRE_autoPA_hE.avi") self.sound3 = loader.loadSfx("VRE_autoPA_vE.avi") self.sound4 = loader.loadSfx("VRE_autoPA_feeding.avi") self.tex1.synchronizeTo(self.sound1) self.tex2.synchronizeTo(self.sound2) self.tex3.synchronizeTo(self.sound3) self.tex4.synchronizeTo(self.sound4) # Load TV model and apply baseline texture self.TV1 = loader.loadModel("zebrafishEnviron4TV3") self.TV2 = loader.loadModel("zebrafishEnviron4TV3") self.TV1.reparentTo(render) self.TV2.reparentTo(render) self.TV1.setTexture(self.tex1, 1) self.TV2.setTexture(self.tex1, 1) self.TV1.setPos(0, -20.3, 0) self.TV2.setPos(0, 20.3, 0) self.TV2.setH(180) # Add the spinCameraTask procedure to the task manager. taskMgr.add(self.spinCameraTask, "SpinCameraTask") # KH: taskMgr is an attribute of class ShowBase. It keeps a list of currently-running taks. ".add()" is a method of taskMgr. # self.spinCameraTask is a function defined below. "SpinCameraTask" can be an arbitrary name. base.disableMouse() base.camera.setPos(0, 0, 5) base.camLens.setFov( 40 ) # Necessary to set bot horizontal and vertical FOV. If only set horizontal, vertical FOV will be calculated using the aspect ratio of the window. base.setAspectRatio( 1.33 ) # Override window's aspect ratio, which is 3X wider, as specified in the beginning # Turn off the default camera and replace it with 3 cameras, with side-by-side displayRegions. base.camNode.setActive(0) base.makeCamera(base.win, displayRegion=(0.33, 0.66, 0, 1), lens=base.camLens) # central camera base.makeCamera(base.win, displayRegion=(0, 0.33, 0, 1), lens=base.camLens) # left camera base.makeCamera(base.win, displayRegion=(0.66, 0.99, 0, 1), lens=base.camLens) # right camera base.camList[1].setH(0) base.camList[2].setH(40) base.camList[3].setH(-40) # Set collision rules base.cTrav = CollisionTraverser() environ_mask = BitMask32.bit(2) camera.setCollideMask( BitMask32.allOff() ) # KH: visible geometry nodes also have an "into" mask. Collision should not act on these nodes. Turn the mask off. cameraCN = CollisionNode('eye') # KH: collision node cameraCN.addSolid(CollisionSphere(0, 0, 0, 1)) cameraCN.setFromCollideMask(environ_mask) cameraCN.setIntoCollideMask(BitMask32.allOff()) cameraCNP = camera.attachNewNode(cameraCN) # KH: collision node path environ.setCollideMask(BitMask32.allOff()) environ.setScale(1) wallCNP = environ.find( "**/wall_collide" ) # KH: CNP for environ, you manually set the <Collide> tag in egg file wallCNP.node().setIntoCollideMask(environ_mask) eHandler = CollisionHandlerPusher() eHandler.addCollider(cameraCNP, camera) base.cTrav.addCollider(cameraCNP, eHandler) # communicate with LabView using ActiveX LabVIEW = win32com.client.Dispatch("Labview.Application") self.VI = LabVIEW.getvireference( 'C:\\Friedrich KH\\LabviewPython_reset.vi') # Path to LabVIEW VI self.VI._FlagAsMethod("Call") # Flag "Call" as Method
def __init__(self): from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4 ShowBase.__init__(self) self.sky = self.loader.loadModel('models/sky-sphere') self.sky.reparentTo(self.render) self.stage = self.loader.loadModel('models/test-collide') self.stage.reparentTo(self.render) self.floor = self.stage.findAllMatches('**/=CollideType=floor') self.floor.setCollideMask(FLOOR_MASK) self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle') if self.obstacles: self.obstacles.setCollideMask(OBSTACLE_MASK) self.zones = self.stage.findAllMatches('**/=CollideType=zone') if self.zones: self.zones.setCollideMask(ZONE_MASK) self.create_stanchions() # Character rig, which allows camera to follow character self.char_rig = self.stage.attachNewNode('char_rig') self.active_char = Character('mainchar', self.char_rig) self.cam.reparentTo(self.char_rig) self.cam.setPos(0.5, -3, 1.5) self.cam.lookAt(0.5, 0, 1.5) self.light = DirectionalLight('dlight') self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0)) self.lightNP = self.stage.attachNewNode(self.light) self.lightNP.setHpr(-75, -45, 0) self.stage.setLight(self.lightNP) self.amblight = AmbientLight('amblight') self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0)) self.amblightNP = self.stage.attachNewNode(self.amblight) self.stage.setLight(self.amblightNP) self.accept('w', self.active_char.begin_forward) self.accept('a', self.active_char.begin_left) self.accept('s', self.active_char.begin_backward) self.accept('d', self.active_char.begin_right) self.accept('w-up', self.active_char.end_forward) self.accept('a-up', self.active_char.end_left) self.accept('s-up', self.active_char.end_backward) self.accept('d-up', self.active_char.end_right) self.taskMgr.add(self.active_char.MoveTask, 'MoveTask') self.look = False self.prev_pos = None self.accept('mouse2', self.begin_look) self.accept('mouse2-up', self.end_look) self.accept('mouse3', self.active_char.begin_spin) self.accept('mouse3-up', self.active_char.end_spin) self.taskMgr.add(self.MouseTask, 'MouseTask') self.floor_handler = CollisionHandlerFloor() self.floor_handler.addCollider(self.active_char.actor_from_floor, self.char_rig) self.wall_handler = CollisionHandlerPusher() self.wall_handler.addCollider(self.active_char.actor_from_obstacle, self.char_rig) self.zone_handler = CollisionHandlerEvent() self.zone_handler.addInPattern('%fn-into') self.zone_handler.addOutPattern('%fn-out') def foo(entry): print 'You are in the zone' def bar(entry): print 'You are not in the zone' self.accept('blockchar_zone-into', foo) self.accept('blockchar_zone-out', bar) self.cTrav = CollisionTraverser('main traverser') self.cTrav.setRespectPrevTransform(True) self.cTrav.addCollider(self.active_char.actor_from_floor, self.floor_handler) self.cTrav.addCollider(self.active_char.actor_from_obstacle, self.wall_handler) self.cTrav.addCollider(self.active_char.actor_from_zone, self.zone_handler)
class FreeBLiTZ(ShowBase): def __init__(self): from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4 ShowBase.__init__(self) self.sky = self.loader.loadModel('models/sky-sphere') self.sky.reparentTo(self.render) self.stage = self.loader.loadModel('models/test-collide') self.stage.reparentTo(self.render) self.floor = self.stage.findAllMatches('**/=CollideType=floor') self.floor.setCollideMask(FLOOR_MASK) self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle') if self.obstacles: self.obstacles.setCollideMask(OBSTACLE_MASK) self.zones = self.stage.findAllMatches('**/=CollideType=zone') if self.zones: self.zones.setCollideMask(ZONE_MASK) self.create_stanchions() # Character rig, which allows camera to follow character self.char_rig = self.stage.attachNewNode('char_rig') self.active_char = Character('mainchar', self.char_rig) self.cam.reparentTo(self.char_rig) self.cam.setPos(0.5, -3, 1.5) self.cam.lookAt(0.5, 0, 1.5) self.light = DirectionalLight('dlight') self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0)) self.lightNP = self.stage.attachNewNode(self.light) self.lightNP.setHpr(-75, -45, 0) self.stage.setLight(self.lightNP) self.amblight = AmbientLight('amblight') self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0)) self.amblightNP = self.stage.attachNewNode(self.amblight) self.stage.setLight(self.amblightNP) self.accept('w', self.active_char.begin_forward) self.accept('a', self.active_char.begin_left) self.accept('s', self.active_char.begin_backward) self.accept('d', self.active_char.begin_right) self.accept('w-up', self.active_char.end_forward) self.accept('a-up', self.active_char.end_left) self.accept('s-up', self.active_char.end_backward) self.accept('d-up', self.active_char.end_right) self.taskMgr.add(self.active_char.MoveTask, 'MoveTask') self.look = False self.prev_pos = None self.accept('mouse2', self.begin_look) self.accept('mouse2-up', self.end_look) self.accept('mouse3', self.active_char.begin_spin) self.accept('mouse3-up', self.active_char.end_spin) self.taskMgr.add(self.MouseTask, 'MouseTask') self.floor_handler = CollisionHandlerFloor() self.floor_handler.addCollider(self.active_char.actor_from_floor, self.char_rig) self.wall_handler = CollisionHandlerPusher() self.wall_handler.addCollider(self.active_char.actor_from_obstacle, self.char_rig) self.zone_handler = CollisionHandlerEvent() self.zone_handler.addInPattern('%fn-into') self.zone_handler.addOutPattern('%fn-out') def foo(entry): print 'You are in the zone' def bar(entry): print 'You are not in the zone' self.accept('blockchar_zone-into', foo) self.accept('blockchar_zone-out', bar) self.cTrav = CollisionTraverser('main traverser') self.cTrav.setRespectPrevTransform(True) self.cTrav.addCollider(self.active_char.actor_from_floor, self.floor_handler) self.cTrav.addCollider(self.active_char.actor_from_obstacle, self.wall_handler) self.cTrav.addCollider(self.active_char.actor_from_zone, self.zone_handler) #self.cTrav.showCollisions(self.stage) def create_stanchions(self): from pandac.PandaModules import GeomVertexReader, CollisionNode, CollisionTube self.stanchions = self.stage.findAllMatches('**/=Stanchion') for stanchion in self.stanchions: geomnode = stanchion.node() radius = float(stanchion.getTag('Stanchion')) geom = geomnode.getGeom(0) vdata = geom.getVertexData() for gp in range(geom.getNumPrimitives()): vreader = GeomVertexReader(vdata, 'vertex') prim = geom.getPrimitive(gp) prim = prim.decompose() for p in range(prim.getNumPrimitives()): start = prim.getPrimitiveStart(p) end = prim.getPrimitiveEnd(p) vertices = [] for v in range(start, end): vi = prim.getVertex(v) vreader.setRow(vi) vertex = vreader.getData3f() vertices.append(vertex) vertices.append(vertices[0]) for i in range(1, len(vertices)): a, b = vertices[i - 1], vertices[i] stanchion_np = stanchion.attachNewNode( CollisionNode('stanchion')) print 'creating cyl with radius %f from %s to %s' % ( radius, a, b) stanchion_np.node().addSolid( CollisionTube(a[0], a[1], a[2], b[0], b[1], b[2], radius)) stanchion_np.node().setFromCollideMask(OBSTACLE_MASK) geomnode.removeAllGeoms() def begin_look(self): self.look = True def end_look(self): self.look = False self.prev_pos = None def MouseTask(self, task): if self.mouseWatcherNode.hasMouse(): (x, y) = self.mouseWatcherNode.getMouse() if self.prev_pos: if self.look or self.active_char.spinning: h_diff = (x - self.prev_pos[0]) * 180 p_diff = (y - self.prev_pos[1]) * 90 new_h = clamp_deg_sign(self.char_rig.getH() - h_diff) self.char_rig.setH(new_h) self.cam.setP(self.cam.getP() + p_diff) self.active_char.spin(new_h) self.prev_pos = (x, y) return task.cont
class FreeBLiTZ(ShowBase): def __init__(self): from pandac.PandaModules import CollisionHandlerFloor, CollisionHandlerPusher, CollisionHandlerEvent, CollisionTraverser from pandac.PandaModules import DirectionalLight, AmbientLight, VBase4 ShowBase.__init__(self) self.sky = self.loader.loadModel('models/sky-sphere') self.sky.reparentTo(self.render) self.stage = self.loader.loadModel('models/test-collide') self.stage.reparentTo(self.render) self.floor = self.stage.findAllMatches('**/=CollideType=floor') self.floor.setCollideMask(FLOOR_MASK) self.obstacles = self.stage.findAllMatches('**/=CollideType=obstacle') if self.obstacles: self.obstacles.setCollideMask(OBSTACLE_MASK) self.zones = self.stage.findAllMatches('**/=CollideType=zone') if self.zones: self.zones.setCollideMask(ZONE_MASK) self.create_stanchions() # Character rig, which allows camera to follow character self.char_rig = self.stage.attachNewNode('char_rig') self.active_char = Character('mainchar', self.char_rig) self.cam.reparentTo(self.char_rig) self.cam.setPos(0.5, -3, 1.5) self.cam.lookAt(0.5, 0, 1.5) self.light = DirectionalLight('dlight') self.light.setColor(VBase4(0.3, 0.28, 0.26, 1.0)) self.lightNP = self.stage.attachNewNode(self.light) self.lightNP.setHpr(-75, -45, 0) self.stage.setLight(self.lightNP) self.amblight = AmbientLight('amblight') self.amblight.setColor(VBase4(0.7, 0.68, 0.66, 1.0)) self.amblightNP = self.stage.attachNewNode(self.amblight) self.stage.setLight(self.amblightNP) self.accept('w', self.active_char.begin_forward) self.accept('a', self.active_char.begin_left) self.accept('s', self.active_char.begin_backward) self.accept('d', self.active_char.begin_right) self.accept('w-up', self.active_char.end_forward) self.accept('a-up', self.active_char.end_left) self.accept('s-up', self.active_char.end_backward) self.accept('d-up', self.active_char.end_right) self.taskMgr.add(self.active_char.MoveTask, 'MoveTask') self.look = False self.prev_pos = None self.accept('mouse2', self.begin_look) self.accept('mouse2-up', self.end_look) self.accept('mouse3', self.active_char.begin_spin) self.accept('mouse3-up', self.active_char.end_spin) self.taskMgr.add(self.MouseTask, 'MouseTask') self.floor_handler = CollisionHandlerFloor() self.floor_handler.addCollider(self.active_char.actor_from_floor, self.char_rig) self.wall_handler = CollisionHandlerPusher() self.wall_handler.addCollider(self.active_char.actor_from_obstacle, self.char_rig) self.zone_handler = CollisionHandlerEvent() self.zone_handler.addInPattern('%fn-into') self.zone_handler.addOutPattern('%fn-out') def foo(entry): print 'You are in the zone' def bar(entry): print 'You are not in the zone' self.accept('blockchar_zone-into', foo) self.accept('blockchar_zone-out', bar) self.cTrav = CollisionTraverser('main traverser') self.cTrav.setRespectPrevTransform(True) self.cTrav.addCollider(self.active_char.actor_from_floor, self.floor_handler) self.cTrav.addCollider(self.active_char.actor_from_obstacle, self.wall_handler) self.cTrav.addCollider(self.active_char.actor_from_zone, self.zone_handler) #self.cTrav.showCollisions(self.stage) def create_stanchions(self): from pandac.PandaModules import GeomVertexReader, CollisionNode, CollisionTube self.stanchions = self.stage.findAllMatches('**/=Stanchion') for stanchion in self.stanchions: geomnode = stanchion.node() radius = float(stanchion.getTag('Stanchion')) geom = geomnode.getGeom(0) vdata = geom.getVertexData() for gp in range(geom.getNumPrimitives()): vreader = GeomVertexReader(vdata, 'vertex') prim = geom.getPrimitive(gp) prim = prim.decompose() for p in range(prim.getNumPrimitives()): start = prim.getPrimitiveStart(p) end = prim.getPrimitiveEnd(p) vertices = [] for v in range(start, end): vi = prim.getVertex(v) vreader.setRow(vi) vertex = vreader.getData3f() vertices.append(vertex) vertices.append(vertices[0]) for i in range(1, len(vertices)): a, b = vertices[i-1], vertices[i] stanchion_np = stanchion.attachNewNode(CollisionNode('stanchion')) print 'creating cyl with radius %f from %s to %s' % (radius, a, b) stanchion_np.node().addSolid(CollisionTube(a[0], a[1], a[2], b[0], b[1], b[2], radius)) stanchion_np.node().setFromCollideMask(OBSTACLE_MASK) geomnode.removeAllGeoms() def begin_look(self): self.look = True def end_look(self): self.look = False self.prev_pos = None def MouseTask(self, task): if self.mouseWatcherNode.hasMouse(): (x, y) = self.mouseWatcherNode.getMouse() if self.prev_pos: if self.look or self.active_char.spinning: h_diff = (x - self.prev_pos[0]) * 180 p_diff = (y - self.prev_pos[1]) * 90 new_h = clamp_deg_sign(self.char_rig.getH() - h_diff) self.char_rig.setH(new_h) self.cam.setP(self.cam.getP() + p_diff) self.active_char.spin(new_h) self.prev_pos = (x, y) return task.cont
class CogdoFlyingCollisions(GravityWalker): wantFloorSphere = 0 def __init__(self): GravityWalker.__init__(self, gravity=0.0) def initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius=1.4, floorOffset=1.0, reach=1.0): self.cHeadSphereNodePath = None self.cFloorEventSphereNodePath = None self.setupHeadSphere(avatarNodePath) self.setupFloorEventSphere(avatarNodePath, ToontownGlobals.FloorEventBitmask, avatarRadius) GravityWalker.initializeCollisions(self, collisionTraverser, avatarNodePath, avatarRadius, floorOffset, reach) return def setupWallSphere(self, bitmask, avatarRadius): self.avatarRadius = avatarRadius cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius) cSphereNode = CollisionNode('Flyer.cWallSphereNode') cSphereNode.addSolid(cSphere) cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) if config.GetBool('want-fluid-pusher', 0): self.pusher = CollisionHandlerFluidPusher() else: self.pusher = CollisionHandlerPusher() self.pusher.addCollider(cSphereNodePath, self.avatarNodePath) self.cWallSphereNodePath = cSphereNodePath def setupEventSphere(self, bitmask, avatarRadius): self.avatarRadius = avatarRadius cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius * 1.04) cSphere.setTangible(0) cSphereNode = CollisionNode('Flyer.cEventSphereNode') cSphereNode.addSolid(cSphere) cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.event = CollisionHandlerEvent() self.event.addInPattern('enter%in') self.event.addOutPattern('exit%in') self.cEventSphereNodePath = cSphereNodePath def setupRay(self, bitmask, floorOffset, reach): cRay = CollisionRay(0.0, 0.0, 3.0, 0.0, 0.0, -1.0) cRayNode = CollisionNode('Flyer.cRayNode') cRayNode.addSolid(cRay) self.cRayNodePath = self.avatarNodePath.attachNewNode(cRayNode) cRayNode.setFromCollideMask(bitmask) cRayNode.setIntoCollideMask(BitMask32.allOff()) self.lifter = CollisionHandlerGravity() self.lifter.setLegacyMode(self._legacyLifter) self.lifter.setGravity(self.getGravity(0)) self.lifter.addInPattern('%fn-enter-%in') self.lifter.addAgainPattern('%fn-again-%in') self.lifter.addOutPattern('%fn-exit-%in') self.lifter.setOffset(floorOffset) self.lifter.setReach(reach) self.lifter.addCollider(self.cRayNodePath, self.avatarNodePath) def setupHeadSphere(self, avatarNodePath): collSphere = CollisionSphere(0, 0, 0, 1) collSphere.setTangible(1) collNode = CollisionNode('Flyer.cHeadCollSphere') collNode.setFromCollideMask(ToontownGlobals.CeilingBitmask) collNode.setIntoCollideMask(BitMask32.allOff()) collNode.addSolid(collSphere) self.cHeadSphereNodePath = avatarNodePath.attachNewNode(collNode) self.cHeadSphereNodePath.setZ(base.localAvatar.getHeight() + 1.0) self.headCollisionEvent = CollisionHandlerEvent() self.headCollisionEvent.addInPattern('%fn-enter-%in') self.headCollisionEvent.addOutPattern('%fn-exit-%in') base.cTrav.addCollider(self.cHeadSphereNodePath, self.headCollisionEvent) def setupFloorEventSphere(self, avatarNodePath, bitmask, avatarRadius): cSphere = CollisionSphere(0.0, 0.0, 0.0, 0.75) cSphereNode = CollisionNode('Flyer.cFloorEventSphere') cSphereNode.addSolid(cSphere) cSphereNodePath = avatarNodePath.attachNewNode(cSphereNode) cSphereNode.setFromCollideMask(bitmask) cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.floorCollisionEvent = CollisionHandlerEvent() self.floorCollisionEvent.addInPattern('%fn-enter-%in') self.floorCollisionEvent.addAgainPattern('%fn-again-%in') self.floorCollisionEvent.addOutPattern('%fn-exit-%in') base.cTrav.addCollider(cSphereNodePath, self.floorCollisionEvent) self.cFloorEventSphereNodePath = cSphereNodePath def deleteCollisions(self): GravityWalker.deleteCollisions(self) if self.cHeadSphereNodePath != None: base.cTrav.removeCollider(self.cHeadSphereNodePath) self.cHeadSphereNodePath.detachNode() self.cHeadSphereNodePath = None self.headCollisionsEvent = None if self.cFloorEventSphereNodePath != None: base.cTrav.removeCollider(self.cFloorEventSphereNodePath) self.cFloorEventSphereNodePath.detachNode() self.cFloorEventSphereNodePath = None self.floorCollisionEvent = None self.cRayNodePath.detachNode() del self.cRayNodePath self.cEventSphereNodePath.detachNode() del self.cEventSphereNodePath return def setCollisionsActive(self, active=1): if self.collisionsActive != active: if self.cHeadSphereNodePath != None: base.cTrav.removeCollider(self.cHeadSphereNodePath) if active: base.cTrav.addCollider(self.cHeadSphereNodePath, self.headCollisionEvent) if self.cFloorEventSphereNodePath != None: base.cTrav.removeCollider(self.cFloorEventSphereNodePath) if active: base.cTrav.addCollider(self.cFloorEventSphereNodePath, self.floorCollisionEvent) GravityWalker.setCollisionsActive(self, active) return def enableAvatarControls(self): pass def disableAvatarControls(self): pass def handleAvatarControls(self, task): pass
class World(DirectObject): def __init__(self): base.win.setClearColor(Vec4(0, 0, 0, 1)) # enable physics (and particle) engine self.throwMode = False self.freelook = False self.score = OnscreenText('0', pos=(-1.32, 0.9), fg=(1, 1, 1, 1), bg=(0, 0, 0, 0.5), scale=0.1, align=TextNode.ALeft) # Load the environment in which Eve will walk. Set its parent # to the render variable so that it is a top-lplayerl node. self.env = loader.loadModel('models/world/world.egg.pz') self.env.reparentTo(render) self.env.setPos(0, 0, 0) self.createCollisionHandlers() # Create an Actor instance for Eve. We also specify the animation # models that we want to use as a dictionary, where we can use to # keys to refer to the animations later on. The start point of Eve # is hardcoded in the world model somewhere, so we look that up. self.player = Eve('Eve', self, self.env.find('**/start_point').getPos()) #self.player.nodePath.setZ(self.player.nodePath.getZ() + 10) self.player.nodePath.reparentTo(render) # Create a floater object that always floats 2 units above Eve. # We make sure that it is attached to Eve by reparenting it to # Eve's object instance. self.floater = NodePath(PandaNode('floater')) self.floater.reparentTo(self.player.nodePath) self.floater.setZ(self.floater.getZ() + 2) # load baseball self.baseball = Baseball('baseball', self, self.player.nodePath.getPos()) self.baseball.nodePath.reparentTo(render) self.player.pickUpItem(self.baseball) # Load the panda bear self.panda = Panda('panda', self, self.player.nodePath.getPos()) self.panda.nodePath.reparentTo(render) # Disable controlling the camera using the mouse. Note that this does # not disable the mouse completely, it merely disables the camera # movement by mouse. base.disableMouse() self.hideMouseCursor() # Set the initial position for the camera as X, Y and Z values. base.camera.setPos(self.player.nodePath.getX(), self.player.nodePath.getY() + 10, 2) # Disable modifier button compound events. base.mouseWatcherNode.setModifierButtons(ModifierButtons()) base.buttonThrowers[0].node().setModifierButtons(ModifierButtons()) # Register any control callbacks. self.accept('escape', sys.exit) self.accept('d', self.dropItem) self.accept('f', self.toggleFullscreen) self.accept('space', self.enterThrowMode) self.accept('space-up', self.leaveThrowMode) # Also make sure that we can, at any time, request the state (pressed # or not) for these keys. self.keys = keys.KeyStateManager() self.keys.registerKeys({ 'arrow_left': 'left', 'arrow_right': 'right', 'arrow_up': 'forward', 'arrow_down': 'backward', 'shift': 'shift', 'r': 'reset' }) self.mouse = mouse.MousePointerManager(0) # Schedule the move method to be executed in the game's main loop. taskMgr.add(self.update, 'update') def hideMouseCursor(self): props = WindowProperties() props.setCursorHidden(True) base.win.requestProperties(props) def toggleFullscreen(self): props = WindowProperties() props.setFullscreen(not base.win.getProperties().getFullscreen()) base.win.requestProperties(props) def enableFreelook(self): self.freelook = True # Make sure we reset the MouseMovementManager's last known mouse position, # so we don't get a huge delta on the first attempt. self.mouse.reset() base.camera.setP(0) def disableFreelook(self): self.freelook = False def createCollisionHandlers(self): # Create a new collision traverser instance. We will use this to determine # if any collisions occurred after performing movement. self.cTrav = CollisionTraverser() camGroundRay = CollisionRay() camGroundRay.setOrigin(0, 0, 1000) camGroundRay.setDirection(0, 0, -1) camGroundCol = CollisionNode('camRay') camGroundCol.addSolid(camGroundRay) camGroundCol.setFromCollideMask(BitMask32.bit(0)) camGroundCol.setIntoCollideMask(BitMask32.allOff()) camGroundColNp = base.camera.attachNewNode(camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(camGroundColNp, self.camGroundHandler) # register the collision pusher self.pusher = CollisionHandlerPusher() # register collision event pattern names self.pusher.addInPattern('col-%fn-into') def update(self, task): # get the time passed since the last frame timePassed = globalClock.getDt() # update player self.player.forceMove(timePassed) self.panda.forceMove(timePassed) # Do collision detection. This iterates all the collider nodes self.cTrav.traverse(render) # check if player's move is valid self.player.validateMove() self.panda.validateMove() # Set the initial position for the camera as X, Y and Z values. base.camera.setPos(self.player.nodePath.getPos()) if self.throwMode: # Position the camera a bit above the ground. base.camera.setZ(base.camera, 1.5) if self.freelook: mx, my = self.mouse.getDelta() h = -mx * 0.1 p = -my * 0.1 base.camera.setHpr(base.camera, h, p, 0) self.player.nodePath.setH(self.player.nodePath, h) else: # Set the heading, pitch and roll of the camera. base.camera.setHpr(self.player.nodePath.getHpr()) else: # Set the heading, pitch and roll of the camera. base.camera.setHpr(self.player.nodePath.getHpr()) # Position the camera somewhat behind the player. base.camera.setY(base.camera, 10) # Make sure the camera is above the ground. camGroundEntry = self.getGroundEntry(self.camGroundHandler) if camGroundEntry is not None and camGroundEntry.getIntoNode( ).getName() == 'terrain': base.camera.setZ( camGroundEntry.getSurfacePoint(render).getZ() + 1.5) # Let the camera look at the floater object above Eve. base.camera.lookAt(self.floater) return Task.cont def dropItem(self): self.player.dropItem() def getGroundEntry(self, collisionHandler): # Put all the collision entries into a Python list so we can sort it, # properly. entries = [] for i in range(collisionHandler.getNumEntries()): entries.append(collisionHandler.getEntry(i)) # Sort the list by the collision points' Z values, making sure the # highest value ends up at the front of the list. entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if len(entries) > 0: return entries[0] else: return None def enterThrowMode(self): self.throwMode = True self.player.enterStrafeMode() self.enableFreelook() def leaveThrowMode(self): self.throwMode = False self.player.leaveStrafeMode() self.disableFreelook()
def __init__(self, models = None, anims = None, sphereString = "**/CollisionSphere", game = None, xStart = 0, yStart = 0, zStart = 0, radius = 3): Actor.__init__(self, models, anims) self.game = game self.health = 10 self.heightOffset = 3 #set up the position self.setPos(xStart, yStart, zStart) self.prevPosition = self.getPos() #self.lastPosition = Point3() self.vel = Vec3() self.accel = Vec3(0, 0, -Unit.gravity) #define the position that will be treated as the center of the map self.wCenter = Point3(0, 0, 0) #the radius of the sphere around this self.radius = 3.5 #the base damage this unit deals upon collision self.collisionAttackPower = 2.5 #set up Panda's collisions #first the pusher cSphere = CollisionSphere((0, 0, 1), 2) cNode = CollisionNode("unit") cNode.addSolid(cSphere) cNode.setIntoCollideMask(BitMask32(PLAYER_ENEMY_OBJECTS)) cNode.setFromCollideMask(BitMask32(PLAYER_ENEMY_OBJECTS)) self.collisionNodePath = self.attachNewNode(cNode) #self.collisionNodePath.show() #set pattern for event sent on collision # "%in" is substituted with the name of the into object, "%fn" is substituted with the name of the from object #do the collision pusher self.collisionPusher = CollisionHandlerPusher() self.collisionPusher.addCollider(self.collisionNodePath, self) self.collisionPusher.addInPattern("%fn-into-%in") self.collisionPusher.addOutPattern("fn-out-%in") game.cTrav.addCollider(self.collisionNodePath, self.collisionPusher) #check for colllisions with the ground self.groundRay = CollisionRay() self.groundRay.setOrigin(0, 0, 4000) self.groundRay.setDirection(0, 0, -1) self.groundCol = CollisionNode('unitRay') self.groundCol.addSolid(self.groundRay) self.groundCol.setFromCollideMask(BitMask32(TERRAIN_RAY_MASK)) self.groundCol.setIntoCollideMask(BitMask32.allOff()) self.groundColNode = self.attachNewNode(self.groundCol) self.groundHandler = CollisionHandlerQueue() game.cTrav.addCollider(self.groundColNode, self.groundHandler) #can be thought of as the inverse of the unit's mass self.accelMultiplier = 45 self.friction = 1.7 self.disableFriction = False self.nodePath = None self.shootable = True #finally set the python tag self.setPythonTag("unit", self)
class Unit(Actor): gravity = 30 def __init__(self, models = None, anims = None, sphereString = "**/CollisionSphere", game = None, xStart = 0, yStart = 0, zStart = 0, radius = 3): Actor.__init__(self, models, anims) self.game = game self.health = 10 self.heightOffset = 3 #set up the position self.setPos(xStart, yStart, zStart) self.prevPosition = self.getPos() #self.lastPosition = Point3() self.vel = Vec3() self.accel = Vec3(0, 0, -Unit.gravity) #define the position that will be treated as the center of the map self.wCenter = Point3(0, 0, 0) #the radius of the sphere around this self.radius = 3.5 #the base damage this unit deals upon collision self.collisionAttackPower = 2.5 #set up Panda's collisions #first the pusher cSphere = CollisionSphere((0, 0, 1), 2) cNode = CollisionNode("unit") cNode.addSolid(cSphere) cNode.setIntoCollideMask(BitMask32(PLAYER_ENEMY_OBJECTS)) cNode.setFromCollideMask(BitMask32(PLAYER_ENEMY_OBJECTS)) self.collisionNodePath = self.attachNewNode(cNode) #self.collisionNodePath.show() #set pattern for event sent on collision # "%in" is substituted with the name of the into object, "%fn" is substituted with the name of the from object #do the collision pusher self.collisionPusher = CollisionHandlerPusher() self.collisionPusher.addCollider(self.collisionNodePath, self) self.collisionPusher.addInPattern("%fn-into-%in") self.collisionPusher.addOutPattern("fn-out-%in") game.cTrav.addCollider(self.collisionNodePath, self.collisionPusher) #check for colllisions with the ground self.groundRay = CollisionRay() self.groundRay.setOrigin(0, 0, 4000) self.groundRay.setDirection(0, 0, -1) self.groundCol = CollisionNode('unitRay') self.groundCol.addSolid(self.groundRay) self.groundCol.setFromCollideMask(BitMask32(TERRAIN_RAY_MASK)) self.groundCol.setIntoCollideMask(BitMask32.allOff()) self.groundColNode = self.attachNewNode(self.groundCol) self.groundHandler = CollisionHandlerQueue() game.cTrav.addCollider(self.groundColNode, self.groundHandler) #can be thought of as the inverse of the unit's mass self.accelMultiplier = 45 self.friction = 1.7 self.disableFriction = False self.nodePath = None self.shootable = True #finally set the python tag self.setPythonTag("unit", self) def applyForceFrom(self, magnitude, sourcePosition): forceVector = self.getPos() - sourcePosition forceVector.normalize() forceVector *= magnitude self.applyForce(forceVector) def applyForce(self, forceVector): self.accel += forceVector * self.accelMultiplier def applyConstantVelocityFrom(self, magnitude, sourcePosition): velVector = self.getPos() - sourcePosition velVector.normalize() velVector *= magnitude self.applyConstantVelocity(velVector) def applyConstantVelocity(self, velVector): self.vel = velVector def takeDamage(self, num): self.health -= num if self.health <= 0: self.die() def die(self): self.game.actors[self.getName()] = None self.delete() def turn(self, magnitude): pass def update(self, time): self.vel += self.accel * time self.accel.set(0, 0, -Unit.gravity) if not self.disableFriction: self.vel -= self.vel * (self.friction * time) self.setFluidPos(self.getPos() + self.vel * time) self.setZ(max(-100, self.getZ())) def collideWithUnit(self, other): velDiff = self.vel - other.vel if velDiff.lengthSquared() > 450: Unit.takeDamage(self, other.collisionAttackPower) Unit.takeDamage(other, self.collisionAttackPower) self.vel *= 0.8 other.vel *= 0.8 def collideWithObstacle(self): if self.vel.lengthSquared() > 500: Unit.takeDamage(self, max(1, self.collisionAttackPower)) self.vel *= 0.5 def terrainCollisionCheck(self): entries = [] length = self.groundHandler.getNumEntries() for i in range(length): entry = self.groundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0): for entry in entries: if entry.getIntoNode().getName() == "craterCollisionPlane": zVal = entry.getSurfacePoint(render).getZ() if zVal >= MAX_HEIGHT:#apply a force toward the center self.applyForce(self.wCenter - Point3((self.getX() * GROUND_REPULSION_MULTIPLIER), (self.getY() * GROUND_REPULSION_MULTIPLIER), 0)) ''' this is a little bit hackish, what is done is that a force in the x and y direction is created proportional to your distance from the origin. this will only work effectively if the crater is xy centered in the environment ''' else: self.setZ(max(zVal, self.getZ())) break
from direct.showbase.DirectObject import DirectObject from pandac.PandaModules import CollisionHandlerEvent, CollisionHandlerQueue, CollisionHandlerFloor, CollisionHandlerPusher, CollisionNode, CollisionTube, CollisionSphere, CollisionRay, CollisionTraverser, BitMask32 from doomsday.base import Globals, SoundBank from doomsday.world.Splat import Splat from panda3d.core import Vec4, Vec3 import math collHdl = CollisionHandlerEvent() collHdlF = CollisionHandlerFloor() collHdlF.setMaxVelocity(8) collHdlPush = CollisionHandlerPusher() class WorldCollisions(DirectObject): def __init__(self): base.cTrav = CollisionTraverser() self.called = False def handleInCollisions(self, entry): cogCollNames = ['coll_body', 'coll_crit'] intoNode = entry.getIntoNodePath() fromNode = entry.getFromNodePath() if (self.called): return self.called = True splatColor = Vec4(0.7, 0.7, 0.8, 1.0) splatScale = 0.7 if (intoNode.getName() in cogCollNames): cog = intoNode.getParent().getPythonTag('Cog') gag = fromNode.getParent().getPythonTag('Stats') splatColor = gag.getSplatColor()
#========================================================================= # Main """ As suggested above, we're going to use what we learned so far to make collide 2d and 3d objects. By the way there is nothing special to do from 3d-3d collisions cos the colliders and handlers used are exactly the same as you'll see. """ #========================================================================= #** Collision system ignition base.cTrav = CollisionTraverser() #** This is the known collision handler we use for floor collisions. We'll keep going with the usual settings here as well. avatarFloorHandler = CollisionHandlerGravity() avatarFloorHandler.setGravity(9.81 + 25) avatarFloorHandler.setMaxVelocity(100) #** the walls collider wallHandler = CollisionHandlerPusher() #** we'll use this to 'sense' the fallout impact velocity and also to 'read' various triggers we've put around the map for several purposes. collisionEvent = CollisionHandlerEvent() #** Collision masks - this time there is a new one: the TRIGGER_MASK is used to detect certain collision geometry to act as a trigger, therefore we need to distinguish'em from floor and walls. FLOOR_MASK = BitMask32.bit(1) WALL_MASK = BitMask32.bit(2) TRIGGER_MASK = BitMask32.bit(3) #** Our steering avatar avatarNP = base.render.attachNewNode(ActorNode('yolkyNP')) avatarNP.reparentTo(base.render) # by the way: this time we wont use the same old smiley but a 2d guy for this snippet purposes only - it is just a plane with a texture glued on, a so 2d object then. avatar = loader.loadModel('yolky') avatar.reparentTo(avatarNP)
class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Panda settings base.setBackgroundColor(0.6, 0.6, 0.6) base.cam.setPos(0, 0, 100) base.cam.setHpr(0, -90, 0) # Setup keys for moving localPlayer self.setupKeys() # Setup collision handlers self.setupCollHandlers() # Load localPlayer self.setupPlayer() # Setup dna parser self.dnaParser = DNAParser(self) # Load default room self.dnaParser.createRoom("dna/room_yellow_castle.yaml") # Setup collision colliders self.setupColliders() def setupKeys(self): # This is used to store which keys are currently pressed. self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0} self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) taskMgr.add(self.moveTask, "moveTask") def setupCollHandlers(self): ###### Collisions ###### base.cTrav = CollisionTraverser() self.collisionHandler = CollisionHandlerEvent() self.wallHandler = CollisionHandlerPusher() self.collisionHandler.addInPattern("%fn-into-%in") # this is on the other hand the relative call for the OUT event, as is when the FROM object (heart) goes OUT the INTO oject (heart). self.collisionHandler.addOutPattern("%fn-out-%in") def setupPlayer(self): # Load up player class self.localPlayer = LocalPlayer() # Load up player object self.localPlayer.loadPlayerModel(PlayerModel) # Make player object avalible to this class self.player = self.localPlayer.player # Set player color self.localPlayer.setPos(PlayerPos) # Setup player collisions self.localPlayer.setCollisions() # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Moves the player around def moveTask(self, task): dt = globalClock.getDt() if self.keyMap["left"]: self.player.setX(self.player.getX() - PlayerWalkSpeed) if self.keyMap["right"]: self.player.setX(self.player.getX() + PlayerWalkSpeed) if self.keyMap["forward"]: self.player.setY(self.player.getY() + PlayerWalkSpeed) if self.keyMap["backward"]: self.player.setY(self.player.getY() - PlayerWalkSpeed) return task.cont # Dose basic setup for the next room and keeps # the player avatar in place! def transition(self, newroom, exittunnel, coll): self.dnaParser.createRoom(newroom) self.positionCalculator(exittunnel) # Calculates where to place the player when he leaves a tunnel def positionCalculator(self, tunnel): # Get position of tunnel the player is exiting from tunnelNode = render.find(tunnel) tunnelX = tunnelNode.getX() tunnelY = tunnelNode.getY() tunnelhpr = tunnelNode.getH() if tunnelhpr == 90: if self.player.getX() > tunnelX: self.player.setX(tunnelX + 5) else: self.player.setX(tunnelX - 5) else: if self.player.getY() > tunnelY: self.player.setY(tunnelY + 5) else: self.player.setY(tunnelY - 5) def setupColliders(self): # Tell collider what to check for # TEMP # playerCollider = self.localPlayer.playerCollider playerSensor = self.localPlayer.playerSensor # Tell the wallHandler what to collide with self.wallHandler.addCollider(playerCollider, self.player) # Adding to trav turns it into a from object( moving object ) base.cTrav.addCollider(playerCollider, self.wallHandler) # Adding to trav turns it into a from object( moving object ) base.cTrav.addCollider(playerSensor, self.collisionHandler)