Beispiel #1
0
    def handle_collisions(self):
        self.collision_handling_mutex.acquire()
	self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(1))

        # Now check for collisions.

        self.cTrav.traverse(render)

        # Keep the camera at one foot above the terrain,
        # or two feet above the actor, whichever is greater.
        
        entries = []
        for i in range(self.groundHandler.getNumEntries()):
            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) and (entries[0].getIntoNode().getName() == "terrain"):
            base.camera.setZ(entries[0].getSurfacePoint(render).getZ()+1.0)
        if (base.camera.getZ() < self.actor.getZ() + 2.0):
            base.camera.setZ(self.actor.getZ() + 2.0)
        
	self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(0))
        self.collision_handling_mutex.release()
Beispiel #2
0
 def createBallGeom(self, modelNode, ballBody, space):
     ballGeom = OdeSphereGeom(space, 1)
     ballGeom.setCollideBits(BitMask32(0x2))
     ballGeom.setCategoryBits(BitMask32(0x1))
     ballGeom.setBody(ballBody)
     space.setSurfaceType(ballGeom, SurfaceType.BALL)
     return ballGeom
Beispiel #3
0
	def handle_collisions(self, seconds):
		self.collision_handling_mutex.acquire()
		self.groundCol.setIntoCollideMask(BitMask32.bit(0))
		self.groundCol.setFromCollideMask(BitMask32.bit(1))
		
		# Now check for collisions.
		self.cTrav.traverse(render)
		
		# Adjust the object's Z coordinate.  If the object's ray hit anything,
		# update its Z.
		
		current_z = self.attach_object.render_model.getZ() - self.object_bottom_buffer_distance
		entries = []
		for i in range(self.groundHandler.getNumEntries()):
			entry = self.groundHandler.getEntry(i)
			if (entry.getSurfacePoint(render).getZ() - 0.001 < current_z):
				entries.append(entry)

		entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
					     x.getSurfacePoint(render).getZ()))
		if (len(entries)>0):
			surface_z = entries[0].getSurfacePoint(render).getZ()
			#print "> " + self.attach_object.name + " is falling toward " + entries[0].getIntoNode().getName() + "\n"
			new_z = current_z - (self.falling_velocity * seconds)
			if (new_z < surface_z):
				new_z = surface_z
			if ((new_z > current_z + 0.00001) or (new_z < current_z - 0.00001)):
				self.attach_object.render_model.setZ(new_z + self.object_bottom_buffer_distance)
		
		self.groundCol.setIntoCollideMask(BitMask32.bit(0))
		self.groundCol.setFromCollideMask(BitMask32.bit(0))
		self.collision_handling_mutex.release()
Beispiel #4
0
    def handle_collisions(self):
        self.collision_handling_mutex.acquire()
        self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(1))

        # Now check for collisions.
        self.cTrav.traverse(render)
        
        # Adjust the character's Z coordinate.  If the character'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.groundHandler.getNumEntries()):
            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) and (entries[0].getIntoNode().getName() == "terrain"):
            self.actor.setZ(entries[0].getSurfacePoint(render).getZ())
        else:
            self.actor.setPos(self.startpos)
        
        self.groundCol.setIntoCollideMask(BitMask32.bit(0))
        self.groundCol.setFromCollideMask(BitMask32.bit(0))
        self.collision_handling_mutex.release()
Beispiel #5
0
    def setupCollisions(self):

        #player sphere
        cPlayerSphere = CollisionSphere(Point3(0, 0, .5), 10)
        cPlayerNode = CollisionNode("Player")
        cPlayerNode.addSolid(cPlayerSphere)
        
        cPlayerNode.setFromCollideMask(BitMask32.bit(4))
        cPlayerNode.setIntoCollideMask(BitMask32(20))
        
        cPlayerNP = self.player.attachNewNode(cPlayerNode)
        self.cTrav.addCollider(cPlayerNP, self.playerGroundHandler)
        #self.cTrav.addCollider(cPlayerNP, self.cRocketHandler)
        #cPlayerNP.show()
        
        
        #enemy sphere
        cEnemySphere = CollisionSphere(Point3(0, 0, .5), 10)
        cEnemyNode = CollisionNode("Enemy")
        cEnemyNode.addSolid(cEnemySphere)
        
        cEnemyNode.setFromCollideMask(BitMask32.bit(4))
        cEnemyNode.setIntoCollideMask(BitMask32(18))
        
        cEnemyNP = self.enemy.attachNewNode(cEnemyNode)
        self.cTrav.addCollider(cEnemyNP, self.enemyGroundHandler)
Beispiel #6
0
    def __init__(self, parserClass, mainClass, mapLoaderClass, modelLoaderClass):
        self.switchState = False

        # self.t = Timer()

        self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0}
        self.ralph = Actor(
            "data/models/units/ralph/ralph",
            {"run": "data/models/units/ralph/ralph-run", "walk": "data/models/units/ralph/ralph-walk"},
        )
        self.ralph.reparentTo(render)
        # 		self.ralph.setPos(42, 30, 0)
        self.ralph.setPos(6, 10, 0)
        self.ralph.setScale(0.1)

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

        self.isMoving = False

        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.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
        # self.ralphGroundCol.show()

        base.cam.reparentTo(self.ralph)
        base.cam.setPos(0, 9, 7)
        self.floater2 = NodePath(PandaNode("floater2"))
        self.floater2.reparentTo(self.ralph)
        self.floater2.setZ(self.floater2.getZ() + 6)
        base.cam.lookAt(self.floater2)

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

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

        taskMgr.add(self.move, "movingTask", extraArgs=[mainClass, parserClass, mapLoaderClass, modelLoaderClass])
Beispiel #7
0
  def __init__(self, ywn):
      '''
      Constructor
      '''
      Thing.__init__(self, "Lightswitch", ywn)
      
      self.model = loader.loadModel('models/Lightswitch')
      
      self.model.find("**/Piattina").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/Piattina").node().setTag('ID', self.Id)
      self.model.find("**/Piattina").node().setTag('nodeId', "Piattina")
      
      self.model.find("**/Switch").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/Switch").node().setTag('ID', self.Id)
      self.model.find("**/Switch").node().setTag('nodeId', "Switch")
      self.model.find("**/Switch").setP(332)
      
      self.model.find("**/TopScrew").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/TopScrew").node().setTag('ID', self.Id)
      self.model.find("**/TopScrew").node().setTag('nodeId', "TopScrew")
 
      self.model.find("**/BottomScrew").node().setIntoCollideMask(BitMask32.bit(1))
      self.model.find("**/BottomScrew").node().setTag('ID', self.Id)
      self.model.find("**/BottomScrew").node().setTag('nodeId', "BottomScrew")
      
      self.model.setTag('ID', self.Id)
      
      self.status = Lightswitch.SWITCH_OFF
Beispiel #8
0
    def placeItem(self, item):
        # Add ground collision detector to the health item
        self.cTrav1 = CollisionTraverser()

        self.collectGroundRay = CollisionRay()
        self.collectGroundRay.setOrigin(0,0,300)
        self.collectGroundRay.setDirection(0,0,-1)
        self.collectGroundCol = CollisionNode('colRay')
        self.collectGroundCol.addSolid(self.collectGroundRay)
        self.collectGroundCol.setFromCollideMask(BitMask32.bit(1))
        self.collectGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.collectGroundColNp = item.attachNewNode(self.collectGroundCol)
        self.collectGroundHandler = CollisionHandlerQueue()
        base.cTrav1.addCollider(self.collectGroundColNp, self.collectGroundHandler)
        
        placed = False;
        while placed == False:
            # re-randomize position
            item.setPos(-random.randint(-350,300),-random.randint(-100,150),0)
            
            base.cTrav1.traverse(render)
            
            # Get Z position from terrain collision
            entries = []
            for j in range(self.collectGroundHandler.getNumEntries()):
                entry = self.collectGroundHandler.getEntry(j)
                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"):
                item.setZ(entries[0].getSurfacePoint(render).getZ()+4)
                placed = True
Beispiel #9
0
    def __init__(self,actor):

        self.actor = actor
        self.prevtime = 0
        self.controlMap = {"left":0, "right":0}

        taskMgr.add(self.move,"cameraMoveTask")
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        base.disableMouse()
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2)
        base.camera.setPos(self.actor.getX()-30,self.actor.getY()-10,self.actor.getZ()+7)
        camera.setHpr(-60,0,0)

        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0,0,1000)
        self.groundRay.setDirection(0,0,-1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)

        self.groundColNp.show()
Beispiel #10
0
    def __init__(self, model, run, walk, startPos, scale, select,ralph,saysome):

        self.actor = Actor(model, {"run":run, "walk":walk})
        self.actor.reparentTo(render)
        self.actor.setScale(scale)
        self.actor.setPos(startPos)
        self.actor.setHpr(90,0,0)
        self.playerGUI = saysome
        self.myralph = ralph
        self.setAI()

        self.cTrav = CollisionTraverser()

        self.groundRay = CollisionRay(0,0,1000,0,0,-1)  
        self.groundCol = CollisionNode('dinoRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = self.actor.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)

        self.sphere = CollisionSphere(0,0,5,13)
        self.spherecol = CollisionNode('dinoSphere')
        self.spherecol.addSolid(self.sphere)
        self.spherecol.setCollideMask(BitMask32.bit(1))
        self.dinocolhs = self.actor.attachNewNode(self.spherecol)
Beispiel #11
0
 def makeNew(self, pos, nor, parent=None):
     """Makes a new bullet hole."""
     if parent == None:
         parent = self.container
     else:
         # Add a subnode to the parent, if it's not already there
         child = parent.find('bullet-holes')
         if child.isEmpty():
             parent = parent.attachNewNode('bullet-holes')
         else:
             parent = child
     newhole = NodePath(self.card.generate())
     newhole.reparentTo(parent)
     newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
     newhole.setR(newhole, random() * 360.0)
     newhole.setPos(render, pos)
     # Offset it a little to avoid z-fighting
     # Increase this value if you still see it.
     newhole.setY(newhole, -.001 - random() * 0.01)
     del newhole
     # We don't want one batch per bullet hole, so flatten it.
     # This could be made smarter to preserve culling, but
     # I have yet to see a performance loss.
     # The clearTexture() is a necessary hack.
     parent.clearTexture()
     parent.flattenStrong()
     parent.setTexture(self.texture)
     parent.setTransparency(TransparencyAttrib.MDual)
     parent.setShaderOff(1)
     parent.hide(BitMask32.bit(
         2))  # Invisible to volumetric lighting camera (speedup)
     parent.hide(BitMask32.bit(3))  # Invisible to shadow cameras (speedup)
Beispiel #12
0
 def makeNew(self, pos, nor, parent = None):
   """Makes a new bullet hole."""
   if parent == None:
     parent = self.container
   else:
     # Add a subnode to the parent, if it's not already there
     child = parent.find('bullet-holes')
     if child.isEmpty():
       parent = parent.attachNewNode('bullet-holes')
     else:
       parent = child
   newhole = NodePath(self.card.generate())
   newhole.reparentTo(parent)
   newhole.lookAt(render, Point3(newhole.getPos(render) - nor))
   newhole.setR(newhole, random() * 360.0)
   newhole.setPos(render, pos)
   # Offset it a little to avoid z-fighting
   # Increase this value if you still see it.
   newhole.setY(newhole, -.001 - random() * 0.01)
   del newhole
   # We don't want one batch per bullet hole, so flatten it.
   # This could be made smarter to preserve culling, but
   # I have yet to see a performance loss.
   # The clearTexture() is a necessary hack.
   parent.clearTexture()
   parent.flattenStrong()
   parent.setTexture(self.texture)
   parent.setTransparency(TransparencyAttrib.MDual)
   parent.setShaderOff(1)
   parent.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
   parent.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)
Beispiel #13
0
  def start(self):
    if self.bgColour!=None: base.setBackgroundColor(self.bgColour)

    if self.model!=None:
      self.model.show()
      self.model.hide(BitMask32.bit(1)) # Hide from the reflection camera
      self.model.hide(BitMask32.bit(2)) # Hide from the volumetric lighting camera
      self.model.hide(BitMask32.bit(3)) # Hide from the shadow camera(s), if any
Beispiel #14
0
    def makeNodeLocator(self, environment):
        meshNode = CollisionNode("NavMeshNodeLocator")
        meshNode.setFromCollideMask(BitMask32.allOff())
        meshNode.setIntoCollideMask(OTPGlobals.PathFindingBitmask)

        self.polyHashToPID = {}

        for pId in self.polyToAngles:
            vertCount = 0
            corners = []
            for angle in self.polyToAngles[pId]:
                if angle != 180:
                    # It's a corner
                    corners.append(vertCount)
                vertCount += 1

            # XXX this code only works for square nodes at present
            # Unfortunately we can only make triangle or square CollisionPolygons on the fly
            assert len(corners) == 4

            #import pdb
            #pdb.set_trace()

            verts = []

            for vert in corners:
                verts.append(
                    (self.vertexCoords[self.polyToVerts[pId][vert]][0],
                     self.vertexCoords[self.polyToVerts[pId][vert]][1], 0))

            #import pdb
            #pdb.set_trace()

            poly = CollisionPolygon(verts[0], verts[1], verts[2], verts[3])

            assert poly not in self.polyHashToPID

            self.polyHashToPID[poly] = pId

            meshNode.addSolid(poly)

        ray = CollisionRay()
        ray.setDirection(0, 0, -1)
        ray.setOrigin(0, 0, 0)

        rayNode = CollisionNode("NavMeshRay")
        rayNode.setFromCollideMask(OTPGlobals.PathFindingBitmask)
        rayNode.setIntoCollideMask(BitMask32.allOff())
        rayNode.addSolid(ray)

        self.meshNodePath = environment.attachNewNode(meshNode)
        self.rayNodePath = environment.attachNewNode(rayNode)

        self.meshNodePath.setTwoSided(True)

        self.chq = CollisionHandlerQueue()
        self.traverser = CollisionTraverser()
        self.traverser.addCollider(self.rayNodePath, self.chq)
Beispiel #15
0
 def __init__(self):
     self.picker         = CollisionTraverser()            
     self.pickerQ        = CollisionHandlerQueue()         
     pickerCollN         = CollisionNode('heightChecker')       
     self.pickerNode     = render.attachNewNode(pickerCollN) 
     pickerCollN.setFromCollideMask(BitMask32.bit(1))         
     pickerCollN.setIntoCollideMask(BitMask32.allOff())         
     self.pickerRay      = CollisionRay(0,0,300,0,0,-1)                
     pickerCollN.addSolid(self.pickerRay)      
     self.picker.addCollider(self.pickerNode, self.pickerQ)
Beispiel #16
0
 def __init__(self):
     self.picker         = CollisionTraverser()            
     self.pickerQ        = CollisionHandlerQueue()         
     pickerCollN         = CollisionNode('mouseRay')       
     pickerCamN          = base.camera.attachNewNode(pickerCollN) 
     pickerCollN.setFromCollideMask(BitMask32.bit(1))         
     pickerCollN.setIntoCollideMask(BitMask32.allOff())         
     self.pickerRay      = CollisionRay()                
     pickerCollN.addSolid(self.pickerRay)      
     self.picker.addCollider(pickerCamN, self.pickerQ) 
     self.accept('mouse1',self.pick)                
Beispiel #17
0
    def start(self):
        if self.bgColour != None: base.setBackgroundColor(self.bgColour)

        if self.model != None:
            self.model.show()
            self.model.hide(
                BitMask32.bit(1))  # Hide from the reflection camera
            self.model.hide(
                BitMask32.bit(2))  # Hide from the volumetric lighting camera
            self.model.hide(
                BitMask32.bit(3))  # Hide from the shadow camera(s), if any
Beispiel #18
0
    def __init__(self, model, run, walk, startPos, scale):        
        """Initialise the character. 
        
        Arguments: 
        model -- The path to the character's model file (string) 
           run : The path to the model's run animation (string) 
           walk : The path to the model's walk animation (string) 
           startPos : Where in the world the character will begin (pos) 
           scale : The amount by which the size of the model will be scaled 
                   (float) 
                    
           """ 

        self.controlMap = {"left":0, "right":0, "up":0, "down":0} 

        self.actor = Actor(Config.MYDIR+model, 
                                 {"run":Config.MYDIR+run, 
                                  "walk":Config.MYDIR+walk})        
        self.actor.reparentTo(render) 
        self.actor.setScale(scale) 
        self.actor.setPos(startPos) 

        self.controller = Controller.LocalController(self)
        
        taskMgr.add(self.move,"moveTask") # Note: deriving classes DO NOT need 
                                          # to add their own move tasks to the 
                                          # task manager. If they override 
                                          # self.move, then their own self.move 
                                          # function will get called by the 
                                          # task manager (they must then 
                                          # explicitly call Character.move in 
                                          # that function if they want it). 
        self.prevtime = 0 
        self.isMoving = False 

        # 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.groundRay = CollisionRay() 
        self.groundRay.setOrigin(0,0,1000) 
        self.groundRay.setDirection(0,0,-1) 
        self.groundCol = CollisionNode('ralphRay') 
        self.groundCol.addSolid(self.groundRay) 
        self.groundCol.setFromCollideMask(BitMask32.bit(1)) 
        self.groundCol.setIntoCollideMask(BitMask32.allOff()) 
        self.groundColNp = self.actor.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue() 
        self.cTrav.addCollider(self.groundColNp, self.groundHandler) 
Beispiel #19
0
    def __init__(self,actor): 
        """Initialise the camera, setting it to follow 'actor'. 
        
        Arguments: 
        actor -- The Actor that the camera will initially follow. 
        
        """ 
        
        self.actor = actor 
        self.prevtime = 0 

        # The camera's controls: 
        # "left" = move the camera left, 0 = off, 1 = on 
        # "right" = move the camera right, 0 = off, 1 = on 
        self.controlMap = {"left":0, "right":0} 

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

        # Create a "floater" object. It is used to orient the camera above the 
        # target actor's head. 
        
        self.floater = NodePath(PandaNode("floater")) 
        self.floater.reparentTo(render)        

        # Set up the camera. 

        base.disableMouse() 
        base.camera.setPos(self.actor.getX(),self.actor.getY()+2, 2)
        # uncomment for topdown
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2) 
        #base.camera.setHpr(180, -50, 0)
        
        # A CollisionRay beginning above the camera and going down toward the 
        # ground is used to detect camera collisions and the height of the 
        # camera above the ground. A ray may hit the terrain, or it may hit a 
        # rock or a tree.  If it hits the terrain, we detect the camera's 
        # height.  If it hits anything else, the camera is in an illegal 
        # position. 

        self.cTrav = CollisionTraverser() 
        self.groundRay = CollisionRay() 
        self.groundRay.setOrigin(0,0,1000) 
        self.groundRay.setDirection(0,0,-1) 
        self.groundCol = CollisionNode('camRay') 
        self.groundCol.addSolid(self.groundRay) 
        self.groundCol.setFromCollideMask(BitMask32.bit(1)) 
        self.groundCol.setIntoCollideMask(BitMask32.allOff()) 
        self.groundColNp = base.camera.attachNewNode(self.groundCol) 
        self.groundHandler = CollisionHandlerQueue() 
        self.cTrav.addCollider(self.groundColNp, self.groundHandler) 
Beispiel #20
0
    def __init__(self, actor):
        """Initialise the camera, setting it to follow 'actor'. 
        
        Arguments: 
        actor -- The Actor that the camera will initially follow. 
        
        """

        self.actor = actor
        self.prevtime = 0

        # The camera's controls:
        # "left" = move the camera left, 0 = off, 1 = on
        # "right" = move the camera right, 0 = off, 1 = on
        self.controlMap = {"left": 0, "right": 0}

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

        # Create a "floater" object. It is used to orient the camera above the
        # target actor's head.

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

        # Set up the camera.

        base.disableMouse()
        base.camera.setPos(self.actor.getX(), self.actor.getY() + 2, 2)
        # uncomment for topdown
        #base.camera.setPos(self.actor.getX(),self.actor.getY()+10,2)
        #base.camera.setHpr(180, -50, 0)

        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.

        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0, 0, 1000)
        self.groundRay.setDirection(0, 0, -1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
Beispiel #21
0
  def __init__(self,manager,xml):
    self.surface = getWaterSurface(manager)
    self.surface.reparentTo(render)
    self.surface.hide(BitMask32.bit(1)) # Invisible to reflection camera (speedup)
    self.surface.hide(BitMask32.bit(2)) # Invisible to volumetric lighting camera (speedup)
    self.surface.hide(BitMask32.bit(3)) # Invisible to shadow cameras (speedup)
    self.surface.setShader(loader.loadShader(manager.get('paths').getConfig().find('shaders').get('path')+'/water.cg'))
    self.surface.setShaderInput('time', 0.0, 0.0, 0.0, 0.0)
    ntex = loader.loadTexture(manager.get('paths').getConfig().find('textures').get('path')+'/water-normal.png')
    ntex.setMinfilter(Texture.FTLinearMipmapLinear)
    self.surface.setShaderInput('normal', ntex)
    self.surface.setShaderInput('camera', base.cam)
    self.surface.setTransparency(TransparencyAttrib.MDual, 10)
    self.surface.setTwoSided(True)

    self.surface.setShaderInput('waveInfo', Vec4(0.4, 0.4, 0.4, 0))
    self.surface.setShaderInput('param2', Vec4(-0.015,0.005, 0.05, 0.05))
    self.surface.setShaderInput('param3', Vec4(0.7, 0.3, 0, 0))
    self.surface.setShaderInput('param4', Vec4(2.0, 0.5, 0.5, 0.0))
    #self.surface.setShaderInput('speed', Vec4(-.8, -.4, -.9, .3))
    self.surface.setShaderInput('speed', Vec4(0.2, -1.2, -0.2, -0.7))
    self.surface.setShaderInput('deepcolor', Vec4(0.0,0.3,0.5,1.0))
    self.surface.setShaderInput('shallowcolor', Vec4(0.0,1.0,1.0,1.0))
    self.surface.setShaderInput('reflectioncolor', Vec4(0.95,1.0,1.0,1.0))
    self.surface.hide()

    self.wbuffer = base.win.makeTextureBuffer('water', 512, 512)
    self.wbuffer.setClearColorActive(True)
    self.wbuffer.setClearColor(base.win.getClearColor())
    self.wcamera = base.makeCamera(self.wbuffer)
    if manager.get('sky') != None and manager.get('sky').model != None:
      self.sky = manager.get('sky').model.copyTo(self.wcamera)
      self.sky.setTwoSided(True)
      self.sky.setSz(self.sky, -1)
      self.sky.setClipPlaneOff(1)
      self.sky.show()
      self.sky.hide(BitMask32.bit(0)) # Hide for normal camera
      self.sky.hide(BitMask32.bit(2)) # Hide for volumetric lighting camera
      self.sky.hide(BitMask32.bit(3)) # Hide for shadow camera(s), if any
    else:
      self.sky = None
    self.wcamera.reparentTo(render)
    self.wcamera.node().setLens(base.camLens)
    self.wcamera.node().setCameraMask(BitMask32.bit(1))
    self.surface.hide(BitMask32.bit(1))
    wtexture = self.wbuffer.getTexture()
    wtexture.setWrapU(Texture.WMClamp)
    wtexture.setWrapV(Texture.WMClamp)
    wtexture.setMinfilter(Texture.FTLinearMipmapLinear)
    self.surface.setShaderInput('reflection', wtexture)
    self.wplane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
    self.wplanenp = render.attachNewNode(PlaneNode('water', self.wplane))
    tmpnp = NodePath('StateInitializer')
    tmpnp.setClipPlane(self.wplanenp)
    tmpnp.setAttrib(CullFaceAttrib.makeReverse())
    self.wcamera.node().setInitialState(tmpnp.getState())

    #self.fog = Fog('UnderwaterFog')
    #self.fog.setColor(0.0,0.3,0.5)
    self.fogEnabled = False
Beispiel #22
0
 def addDropCollision(self, drop):
     collSph = drop.attachNewNode(CollisionNode('coll_drop'))
     collSph.node().addSolid(CollisionSphere(0, 0, 0, 1))
     collSph.node().setIntoCollideMask(BitMask32.allOff())
     collSph.node().setFromCollideMask(Globals.DropBitmask)
     collGround = drop.attachNewNode(CollisionNode('coll_drop_ground'))
     collGround.node().addSolid(CollisionRay(0, 0, 0, 0, 0, -1))
     collGround.node().setIntoCollideMask(BitMask32.allOff())
     collGround.node().setFromCollideMask(Globals.WallBitmask)
     collGround.show()
     collHdlF.addCollider(collGround, drop)
     base.cTrav.addCollider(collSph, collHdl)
     base.cTrav.addCollider(collGround, collHdlF)
     self.accept("coll_drop-into", self.handleDropCollision)
     self.accept("coll_drop-out", self.completeCollision)
Beispiel #23
0
	def initialize_collision_handling(self):
		self.collision_handling_mutex = Lock()
		
		self.cTrav = CollisionTraverser()
		
		self.groundRay = CollisionRay()
		self.groundRay.setOrigin(0,0,1000)
		self.groundRay.setDirection(0,0,-1)
		self.groundCol = CollisionNode(self.attach_object.name + "_collision_node")
		self.groundCol.setIntoCollideMask(BitMask32.bit(0))
		self.groundCol.setFromCollideMask(BitMask32.bit(0))
		self.groundCol.addSolid(self.groundRay)
		self.groundColNp = self.attach_object.render_model.attachNewNode(self.groundCol)
		self.groundHandler = CollisionHandlerQueue()
		self.cTrav.addCollider(self.groundColNp, self.groundHandler)
Beispiel #24
0
    def createBallColliderModel(self):
        #creates the collider sphere around the ball
        cSphereRad = 9.9
        self.cTrav = CollisionTraverser() #moves over all possible collisions

        self.ballModelSphere = CollisionSphere(0, 0, 0, cSphereRad)
            #collision mesh around ball is a simple sphere
        self.ballModelCol = CollisionNode('ballModelSphere')
        self.ballModelCol.addSolid(self.ballModelSphere)
        self.ballModelCol.setFromCollideMask(BitMask32.bit(0))
        self.ballModelCol.setIntoCollideMask(BitMask32.allOff())
        self.ballModelColNp = self.ballModel.attachNewNode(self.ballModelCol)
        self.ballModelGroundHandler = CollisionHandlerQueue()
            #collision handler queue stores all collision points
        self.cTrav.addCollider(self.ballModelColNp, self.ballModelGroundHandler)
Beispiel #25
0
 def addDropCollision(self, drop):
     collSph = drop.attachNewNode(CollisionNode('coll_drop'))
     collSph.node().addSolid(CollisionSphere(0, 0, 0, 1))
     collSph.node().setIntoCollideMask(BitMask32.allOff())
     collSph.node().setFromCollideMask(Globals.DropBitmask)
     collGround = drop.attachNewNode(CollisionNode('coll_drop_ground'))
     collGround.node().addSolid(CollisionRay(0, 0, 0, 0, 0, -1))
     collGround.node().setIntoCollideMask(BitMask32.allOff())
     collGround.node().setFromCollideMask(Globals.WallBitmask)
     collGround.show()
     collHdlF.addCollider(collGround, drop)
     base.cTrav.addCollider(collSph, collHdl)
     base.cTrav.addCollider(collGround, collHdlF)
     self.accept("coll_drop-into", self.handleDropCollision)
     self.accept("coll_drop-out", self.completeCollision)
Beispiel #26
0
    def __init__(self, x, y, z):

        self.model = loader.loadModel("models/circle")
        self.model.reparentTo(render)
        self.model.setPos(x, y, z)
        self.model.setHpr(0, 0, 0)
        self.model.setColor(1, 1, 1, 1)
        self.model.setTexture(loader.loadTexture('textures/spiral.png'))

        self.glow = loader.loadModel("models/tube")
        self.glow.reparentTo(render)
        self.glow.setShaderOff()
        self.glow.setLightOff()
        self.glow.hide(BitMask32.allOn())
        self.glow.show(BitMask32(0x01))
        self.glow.setPos(x, y, z + 0.05)
        self.glow.setHpr(0, 0, 0)
        self.glow.setColor(1, 1, 1, 1)
        texture = loader.loadTexture('textures/green_glow.png')
        texture.setWrapU(Texture.WMClamp)
        texture.setWrapV(Texture.WMClamp)
        self.glow.setTexture(texture)
        self.glow.setTransparency(TransparencyAttrib.MAlpha)
        self._active = False
        self.visibility = 0

        taskMgr.add(self._update_task, "AcceleratorUpdateTask")
Beispiel #27
0
    def changeModel(self, changeToKey):
        """ Given, changeToKey, containing the key of the self.models dict, this loads
        the activeModel.
        
        TODO: improve so that models can have their own scale. Generalize with separate Models class."""
        if self.models.has_key(changeToKey):
            # TODO: blend or play animation depending on kind of transition
            if hasattr(self, 'activeModel') and self.activeModel:
                #self.activeModel.detachNode()
                self.activeModel.remove()
            self.activeModel = loader.loadModel("media/models/" +
                                                self.models[changeToKey])
            self.activeModel.setScale(self.scale)
            self.activeModel.setPosHpr(*self.offsetVec)
            self.activeModel.setCollideMask(BitMask32.allOff())
            self.activeModel.reparentTo(self)

            # when models are scaled down dramatically (e.g < 1% of original size), Panda3D represents
            # the geometry non-uniformly, which means scaling occurs every render step and collision
            # handling is buggy.  flattenLight()  circumvents this.
            self.activeModel.flattenLight()
        else:
            raise Exception(
                "Error in %s.changeModel() -- cannot find model %s" %
                (self.name, changeToKey))
Beispiel #28
0
 def __init__(self, ywn):
     '''
     Constructor
     '''
     Thing.__init__(self, "Book", ywn)
     
     self.model = loader.loadModel('models/Book')
     
     self.model.find("**/Front").node().setIntoCollideMask(BitMask32.bit(1))
     self.model.find("**/Back").node().setIntoCollideMask(BitMask32.bit(1))
     self.model.find("**/Front").node().setTag('ID', self.Id)
     self.model.find("**/Back").node().setTag('ID', self.Id)
     self.model.find("**/Front").node().setTag('nodeId', "front")
     self.model.find("**/Back").node().setTag('nodeId', "back")
     
     self.model.setTag('ID', self.Id)
Beispiel #29
0
	def make(self):
		"""Build a finished renderable heightMap."""
		
		# apply shader
		#logging.info( "applying shader")
		self.terrain.texturer.apply(self.getRoot())
		
		# detail settings
		#self.getRoot().setSz(1.0 / self.heightMapDetail)
		#self.getRoot().setSy(1.0 / self.heightMapDetail)
		
		#logging.info( "making height map")
		self.makeHeightMap()
		#logging.info( "setHeight()")
		self.setHeight()
		#self.getRoot().setSz(self.maxHeight)
		
		#http://www.panda3d.org/forums/viewtopic.php?=t=12054
		self.calcAmbientOcclusion()
		#loggin.info( "generate()")
		self.generate()
		self.getRoot().setCollideMask(BitMask32.bit(1))
		
		#self.makeSlopeMap()
		#logging.info( "createGroups()")
		self.createGroups()
		self.terrain.populator.populate(self)
Beispiel #30
0
    def _getEnvironmentHash(self, env):
        '''
        Accepts an environment object and returns the MD5 hash of a string representing all collision geometry therein.
        This value should change whenever the layout of your collisions changes.
        Use to determine whether derived data still reflects reality.

        Base method assumes env is a NodePath, but you can override this to handle whatever you like.
        '''
        allCNs = env.findAllMatches('**/+CollisionNode')
        monsterData = []

        for np in allCNs:
            #monsterData.append( str(np) )
            #monsterData.append( str(np.getTransform(env)) )
            #monsterData.append( str(np.getCollideMask()) )
            monsterData.append("cn")

            node = np.node()

            if node.getIntoCollideMask(
            ) & OTPGlobals.WallBitmask != BitMask32.allOff():
                for i in xrange(node.getNumSolids()):
                    s = node.getSolid(i)

                    monsterData.append(str(s))

        monsterData = string.join(monsterData, "")

        hash = md5.new(monsterData)

        return hash.digest()
 def __init__( self, *args, **kwargs ):
     p3d.SingleTask.__init__( self, *args, **kwargs )
     
     self.fromCollideMask = kwargs.pop( 'fromCollideMask', None )
     
     self.node = None
     self.collEntry = None
     
     # Create collision nodes
     self.collTrav = CollisionTraverser()
     #self.collTrav.showCollisions( render )
     self.collHandler = CollisionHandlerQueue()
     self.pickerRay = CollisionRay()
     
     # Create collision ray
     pickerNode = CollisionNode( self.name )
     pickerNode.addSolid( self.pickerRay )
     pickerNode.setIntoCollideMask( BitMask32.allOff() )
     pickerNp = self.camera.attachNewNode( pickerNode )
     self.collTrav.addCollider( pickerNp, self.collHandler )
     
     # Create collision mask for the ray if one is specified
     if self.fromCollideMask is not None:
         pickerNode.setFromCollideMask( self.fromCollideMask )
     
     # Bind mouse button events
     eventNames = ['mouse1', 'control-mouse1', 'mouse1-up']
     for eventName in eventNames:
         self.accept( eventName, self.FireEvent, [eventName] )
Beispiel #32
0
 def __init__( self, name, camera=None, rootNp=None, fromCollideMask=None, pickTag=None ):
     gizmo_core.Object.__init__( self, name, camera, rootNp )
     
     self.fromCollideMask = fromCollideMask
     self.pickTag = pickTag
     
     self.selection = []
     self.node = None
     self.collEntry = None
     
     # Create a marquee
     self.marquee = gizmo_core.Marquee( '%sMarquee' % self.name )
     
     # Create collision nodes
     self.collTrav = CollisionTraverser()
     #self.collTrav.showCollisions( render )
     self.collHandler = CollisionHandlerQueue()
     self.pickerRay = CollisionRay()
     
     # Create collision ray
     pickerNode = CollisionNode( self.name )
     pickerNode.addSolid( self.pickerRay )
     pickerNode.setIntoCollideMask( BitMask32.allOff() )
     pickerNp = camera.attachNewNode( pickerNode )
     self.collTrav.addCollider( pickerNp, self.collHandler )
     
     # Create collision mask for the ray if one is specified
     if self.fromCollideMask is not None:
         pickerNode.setFromCollideMask( self.fromCollideMask )
     
     # Bind mouse button events
     eventNames = ['mouse1', 'control-mouse1', 'mouse1-up']
     for eventName in eventNames:
         self.accept( eventName, self.FireEvent, [eventName] )
Beispiel #33
0
 def addToonCollision(self):
     toon = render.find('**/Toon')
     collTube = toon.attachNewNode(CollisionNode('coll_toon'))
     collTube.node().addSolid(CollisionTube(0, 0, 0.5, 0, 0, 8, 2))
     collTube.node().setIntoCollideMask(Globals.DropBitmask | Globals.ProjBitmask)
     collTube.node().setFromCollideMask(BitMask32.allOff())
     base.cTrav.addCollider(collTube, collHdl)
Beispiel #34
0
    def __init__(self, *args, **kwargs):
        p3d.SingleTask.__init__(self, *args, **kwargs)

        self.fromCollideMask = kwargs.pop('fromCollideMask', None)

        self.node = None
        self.collEntry = None

        # Create collision nodes
        self.collTrav = CollisionTraverser()
        #self.collTrav.showCollisions( render )
        self.collHandler = CollisionHandlerQueue()
        self.pickerRay = CollisionRay()

        # Create collision ray
        pickerNode = CollisionNode(self.name)
        pickerNode.addSolid(self.pickerRay)
        pickerNode.setIntoCollideMask(BitMask32.allOff())
        pickerNp = self.camera.attachNewNode(pickerNode)
        self.collTrav.addCollider(pickerNp, self.collHandler)

        # Create collision mask for the ray if one is specified
        if self.fromCollideMask is not None:
            pickerNode.setFromCollideMask(self.fromCollideMask)

        # Bind mouse button events
        eventNames = ['mouse1', 'control-mouse1', 'mouse1-up']
        for eventName in eventNames:
            self.accept(eventName, self.FireEvent, [eventName])
Beispiel #35
0
 def __init__(self, render, camera):
     #Since we are using collision detection to do picking, we set it up like any other collision detection system with a traverser and a handler 
     self.picker = CollisionTraverser()            #Make a traverser 
     self.pq     = CollisionHandlerQueue()         #Make a handler 
     #Make a collision node for our picker ray 
     self.pickerNode = CollisionNode('mouseRay') 
     #Attach that node to the camera since the ray will need to be positioned relative to it 
     self.pickerNP = camera.attachNewNode(self.pickerNode) 
     #Everything to be picked will use bit 1. This way if we were doing other collision we could seperate it 
     self.pickerNode.setFromCollideMask(BitMask32.bit(1)) 
     self.pickerRay = CollisionRay()               #Make our ray 
     self.pickerNode.addSolid(self.pickerRay)      #Add it to the collision node 
     #Register the ray as something that can cause collisions 
     self.picker.addCollider(self.pickerNP, self.pq) 
     #self.picker.showCollisions(render) 
     
     self.pst = CollisionTraverser()            #Make a traverser 
     self.hqp     = CollisionHandlerQueue()         #Make a handler 
     #Make a collision node for our picker ray 
     
     self.pstNode = CollisionNode('mouseRaytoObj') 
     #Attach that node to the camera since the ray will need to be positioned relative to it 
     self.pstNode.setFromCollideMask(GeomNode.getDefaultCollideMask())
     self.pstNode2 = camera.attachNewNode(self.pstNode) 
     self.pickerRayObj = CollisionRay()   
     #Everything to be picked will use bit 1. This way if we were doing other collision we could seperate it 
     #self.pstNode.setFromCollideMask(BitMask32.bit(1)) 
     self.pstNode.addSolid(self.pickerRayObj)      #Add it to the collision node 
     #Register the ray as something that can cause collisions 
     self.pst.addCollider(self.pstNode2, self.hqp) 
     #self.pst.showCollisions(render) 
    def make(self):
        """Build a finished renderable heightMap."""

        # apply shader
        #logging.info( "applying shader")
        self.terrain.texturer.apply(self.getRoot())

        # detail settings
        #self.getRoot().setSx(1.0 / self.heightMapDetail)
        #self.getRoot().setSy(1.0 / self.heightMapDetail)

        #logging.info( "making height map")
        self.makeHeightMap()
        #logging.info( "setHeight()")
        self.setHeight()
        #self.getRoot().setSz(self.maxHeight)

        #http://www.panda3d.org/forums/viewtopic.php?t=12054
        self.calcAmbientOcclusion()
        #logging.info( "generate()")
        self.generate()
        self.getRoot().setCollideMask(BitMask32.bit(1))

        #self.makeSlopeMap()
        #logging.info( "createGroups()")
        self.createGroups()
        self.terrain.populator.populate(self)
    def __setupNPC(self):
        # This is to support the collisions for each node. See the paragraph comment
        # above where we modify the npc's collision node
        #        playerCollisionNP = self.__mainTarget.find("* collision node")

        modelStanding = "models/ralph"
        modelRunning = "models/ralph-run"
        modelWalking = "models/ralph-walk"
        self.__NPC = NPC(modelStanding, {
            "run": modelRunning,
            "walk": modelWalking
        },
                         turnRate=150,
                         speed=15,
                         agentList=self.__globalAgentList,
                         name="Ralph",
                         collisionMask=BitMask32.bit(3),
                         rangeFinderCount=13,
                         adjacencySensorThreshold=5,
                         radarSlices=5,
                         radarLength=0,
                         scale=1.0,
                         massKg=35.0,
                         collisionHandler=self.physicsCollisionHandler,
                         collisionTraverser=self.cTrav,
                         waypoints=self.roomWaypoints)
        self.__NPC.setFluidPos(render, 20, 10, 0)  #-190
        self.__NPC.setScale(render, 1)
        self.__NPC.setTarget(self.__mainTarget)

        self.__NPC.reparentTo(render)
        self.__NPC.start()
    def __setupNPC(self):
        # This is to support the collisions for each node. See the paragraph comment
        # above where we modify the npc's collision node
#        playerCollisionNP = self.__mainTarget.find("* collision node")

        modelStanding = "models/ralph"
        modelRunning = "models/ralph-run"
        modelWalking = "models/ralph-walk"
        self.__NPC = NPC(modelStanding, 
                                {"run":modelRunning, "walk":modelWalking},
                                turnRate = 150, 
                                speed = 15,
                                agentList = self.__globalAgentList,
                                name = "Ralph",
                                collisionMask = BitMask32.bit(3),
                                rangeFinderCount = 13,
                                adjacencySensorThreshold = 5,
                                radarSlices = 5,
                                radarLength = 0,
                                scale = 1.0,
                                massKg = 35.0,
                                collisionHandler = self.physicsCollisionHandler,
                                collisionTraverser = self.cTrav,
                                waypoints = self.roomWaypoints)
        self.__NPC.setFluidPos(render, 20, 10, 0)#-190
        self.__NPC.setScale(render, 1)
        self.__NPC.setTarget(self.__mainTarget)

        self.__NPC.reparentTo(render)
	self.__NPC.start()
Beispiel #39
0
 def addAttackCollision(self, proj):
     collSph = proj.attachNewNode(CollisionNode('coll_attack'))
     collSph.node().addSolid(CollisionSphere(0, 0, 0, 1))
     collSph.node().setIntoCollideMask(BitMask32.allOff())
     collSph.node().setFromCollideMask(Globals.ProjBitmask)
     base.cTrav.addCollider(collSph, collHdl)
     self.accept("coll_attack-into", self.handleAttackCollision)
     self.accept("coll_attack-out", self.completeAttackCollision)
Beispiel #40
0
 def addToonCollision(self):
     toon = render.find('**/Toon')
     collTube = toon.attachNewNode(CollisionNode('coll_toon'))
     collTube.node().addSolid(CollisionTube(0, 0, 0.5, 0, 0, 8, 2))
     collTube.node().setIntoCollideMask(Globals.DropBitmask
                                        | Globals.ProjBitmask)
     collTube.node().setFromCollideMask(BitMask32.allOff())
     base.cTrav.addCollider(collTube, collHdl)
Beispiel #41
0
  def __init__(self,manager,xml):
    self.light = PDirectionalLight('dlight')
    self.lightNode = NodePath(self.light)
    self.lightNode.setCompass()
    if hasattr(self.lightNode.node(), "setCameraMask"):
      self.lightNode.node().setCameraMask(BitMask32.bit(3))

    self.reload(manager,xml)
Beispiel #42
0
    def __init__(self, manager, xml):
        self.light = PDirectionalLight("dlight")
        self.lightNode = NodePath(self.light)
        self.lightNode.setCompass()
        if hasattr(self.lightNode.node(), "setCameraMask"):
            self.lightNode.node().setCameraMask(BitMask32.bit(3))

        self.reload(manager, xml)
Beispiel #43
0
 def addAttackCollision(self, proj):
     collSph = proj.attachNewNode(CollisionNode('coll_attack'))
     collSph.node().addSolid(CollisionSphere(0, 0, 0, 1))
     collSph.node().setIntoCollideMask(BitMask32.allOff())
     collSph.node().setFromCollideMask(Globals.ProjBitmask)
     base.cTrav.addCollider(collSph, collHdl)
     self.accept("coll_attack-into", self.handleAttackCollision)
     self.accept("coll_attack-out", self.completeAttackCollision)
Beispiel #44
0
    def setCollisions(self):
        # Add physical collision object to player
        self.playerCollider = self.player.attachNewNode(CollisionNode('playercnode'))
        self.playerCollider.node().addSolid(CollisionSphere(0, 0, 0, 1))
        # Adding to trav turns it into a from object( moving object )
        #base.cTrav.addCollider(self.playerCollider, self.collisionHandler)
        self.playerCollider.node().setFromCollideMask(WALL_MASK)
        self.playerCollider.node().setIntoCollideMask(BitMask32.allOff())

        # Sensor collision
        self.playerSensor = self.player.attachNewNode(CollisionNode('playersensor'))
        cs=CollisionSphere(0, 0, 0, 1.2)
        self.playerSensor.node().addSolid(cs)
        self.playerSensor.node().setFromCollideMask(DOOR_MASK)
        self.playerSensor.node().setIntoCollideMask(BitMask32.allOff())
        # as said above, to act correctly we need to make clear to the system that this is just a sensor, with no solid parts
        cs.setTangible(0)
Beispiel #45
0
 def addCogGroundCollision(self, cog = None, ent = None):
     if ent == None:
         ent = cog.getCog()
     collGround = ent.attachNewNode(CollisionNode('coll_ground'))
     collGround.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -1))
     collGround.node().setIntoCollideMask(BitMask32.allOff())
     collGround.node().setFromCollideMask(Globals.WallBitmask)
     collHdlF.addCollider(collGround, ent)
     base.cTrav.addCollider(collGround, collHdlF)
Beispiel #46
0
 def addCogGroundCollision(self, cog=None, ent=None):
     if ent == None:
         ent = cog.getCog()
     collGround = ent.attachNewNode(CollisionNode('coll_ground'))
     collGround.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -1))
     collGround.node().setIntoCollideMask(BitMask32.allOff())
     collGround.node().setFromCollideMask(Globals.WallBitmask)
     collHdlF.addCollider(collGround, ent)
     base.cTrav.addCollider(collGround, collHdlF)
Beispiel #47
0
 def setMousePicker(self):
     self.picker = CollisionTraverser()
     self.pq = CollisionHandlerQueue()
     self.pickerNode = CollisionNode('mouseRay')
     self.pickerNP = camera.attachNewNode(self.pickerNode)
     self.pickerNode.setFromCollideMask(BitMask32.bit(1))
     self.pickerRay = CollisionRay()
     self.pickerNode.addSolid(self.pickerRay)
     self.picker.addCollider(self.pickerNP, self.pq)
     self.selectable = render.attachNewNode("selectable")
Beispiel #48
0
    def setCollisions(self):
        # Add physical collision object to player
        self.playerCollider = self.player.attachNewNode(
            CollisionNode('playercnode'))
        self.playerCollider.node().addSolid(CollisionSphere(0, 0, 0, 1))
        # Adding to trav turns it into a from object( moving object )
        #base.cTrav.addCollider(self.playerCollider, self.collisionHandler)
        self.playerCollider.node().setFromCollideMask(WALL_MASK)
        self.playerCollider.node().setIntoCollideMask(BitMask32.allOff())

        # Sensor collision
        self.playerSensor = self.player.attachNewNode(
            CollisionNode('playersensor'))
        cs = CollisionSphere(0, 0, 0, 1.2)
        self.playerSensor.node().addSolid(cs)
        self.playerSensor.node().setFromCollideMask(DOOR_MASK)
        self.playerSensor.node().setIntoCollideMask(BitMask32.allOff())
        # as said above, to act correctly we need to make clear to the system that this is just a sensor, with no solid parts
        cs.setTangible(0)
Beispiel #49
0
 def setupCollision(self):
     # create collision traverser
     self.picker = CollisionTraverser()
     # create collision handler
     self.pq = CollisionHandlerQueue()
     # create collision node
     self.pickerNode = CollisionNode('mouseRay')  # create collision node
     # attach new collision node to camera node
     self.pickerNP = camera.attachNewNode(
         self.pickerNode)  # attach collision node to camera
     # set bit mask to one
     self.pickerNode.setFromCollideMask(BitMask32.bit(1))  # set bit mask
     # create a collision ray
     self.pickerRay = CollisionRay()  # create collision ray
     # add picker ray to the picker node
     self.pickerNode.addSolid(
         self.pickerRay)  # add the collision ray to the collision node
     # make the traverser know about the picker node and its even handler queue
     self.picker.addCollider(
         self.pickerNP,
         self.pq)  # add the colision node path and collision handler queue
     #self.picker.showCollisions( render ) # render or draw the collisions
     #self.pickerNP.show( ) # render picker ray
     # create col node
     self.colPlane = CollisionNode('colPlane')
     # add solid to col node plane
     self.colPlane.addSolid(
         CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0))))
     # attach new node to the render
     self.colPlanePath = render.attachNewNode(self.colPlane)
     #self.colPlanePath.show( ) # render node
     # make the col plane look at the camera
     # this makes it alway look at the camera no matter the orientation
     # we need this because the ray nees to intersect a plane parallel
     # to the camera
     self.colPlanePath.lookAt(camera)
     # prop up the col plane
     self.colPlanePath.setP(-45)
     # set bit mask to one
     # as I understand it, this makes all col nodes with bit mask one
     # create collisions while ignoring others of other masks
     self.colPlanePath.node().setIntoCollideMask(BitMask32.bit(1))
 def getFlyBallBubble(self):
     if self.__flyBallBubble == None:
         bubble = CollisionSphere(0, 0, 0, GolfGlobals.GOLF_BALL_RADIUS)
         node = CollisionNode('flyBallBubble')
         node.addSolid(bubble)
         node.setFromCollideMask(ToontownGlobals.PieBitmask | ToontownGlobals.CameraBitmask | ToontownGlobals.FloorBitmask)
         node.setIntoCollideMask(BitMask32.allOff())
         self.__flyBallBubble = NodePath(node)
         self.flyBallHandler = CollisionHandlerEvent()
         self.flyBallHandler.addInPattern('flyBallHit-%d' % self.index)
     return self.__flyBallBubble
Beispiel #51
0
    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')
Beispiel #52
0
 def addGagCollision(self, gag):
     collNode = gag.attachNewNode(CollisionNode('coll_gag'))
     collNode.node().addSolid(CollisionSphere(0, 0, 0, 2))
     collNode.node().setIntoCollideMask(BitMask32.allOff())
     collNode.node().setFromCollideMask(Globals.GagBitmask
                                        | Globals.WallBitmask
                                        | Globals.FloorBitmask)
     base.cTrav.addCollider(collNode, collHdl)
     collHdl.addInPattern('%fn-into')
     collHdl.addOutPattern('%fn-out')
     self.accept("coll_gag-into", self.handleInCollisions)
     self.accept("coll_gag-out", self.completeCollision)
 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
Beispiel #54
0
 def __init__(
         self,
         name=NAME_DEFAULT,
         pos=POS_DEFAULT,
         heading=HEADING_DEFAULT,
         vel=VEL_DEFAULT,
         acc=ACC_DEFAULT  # player controlled acceleration. Can be 0.0 - 1.0
 ):
     """@param name string"""
     self.name = name
     self.pos = pos
     self.vel = vel
     self.acc = acc
     self.heading = heading
     self.rotateLeft = False
     self.rotateRight = False
     self.visualNode = self.createVisualNode(self.pos)
     self.bullets = []
     self.collisionHandler = colHandler
     self.collisions = []
     self.collisionSphere = OdeSphereGeom(4)
     self.collisionSphere.setCategoryBits(BitMask32(0xffffffff))
     self.collisionSphere.setCollideBits(BitMask32(0xffffffff))
     self.collisionSphere.setPosition(pos[0], pos[1], 0)
     self.forces = []
     self.mass = 1.0
     self.health = Ship.HEALTH
     self.isAlive = True
     self.shootingSound = loader.loadSfx('anti_tank_gun_single_shot.mp3')
     self.destroySound = loader.loadSfx('large_explosion.mp3')
     self.bulletHitSound = loader.loadSfx(
         'explosion_loud_internal_explosion_very_reverberant.mp3')
     self.collisionSound = loader.loadSfx('car_door_close.mp3')
     self.bulletParent = NodePath("Bullet Parent")
     self.bulletParent.reparentTo(render)
     self.bulletAmbientLight = AmbientLight('Bullet Light')
     self.bulletAmbientLight.setColor(Vec4(.0, .1, .2, .0))
     lightnode = render.attachNewNode(self.bulletAmbientLight)
     self.bulletParent.setLight(lightnode)
Beispiel #55
0
    def shoot(self):
        # TODO: add proper unit tests!
        angle = self.heading * math.pi / 180.0
        headingX = math.cos(angle)
        headingY = math.sin(angle)
        offset = Vec3(headingX, headingY, 0) * Ship.BULLET_OFFSET
        shipPos = self.getPos()
        bulletPos = (offset[0] + shipPos[0], offset[1] + shipPos[1], offset[2])

        bulletVisual = loader.loadModel("bullet.bam")
        bulletVisual.setPos(tupleToVec3(bulletPos))
        bulletVisual.setHpr(tupleToVec3((self.heading + 90, 180)))
        bulletVisual.setScale(1.5)
        bulletVisual.reparentTo(self.bulletParent)

        # Create physics for bullet
        collisionSphere = OdeSphereGeom(1.5)
        collisionSphere.setCategoryBits(BitMask32(0xffffffff))
        collisionSphere.setCollideBits(BitMask32(0xffffffff))
        collisionSphere.setPosition(bulletPos[0], bulletPos[1], bulletPos[2])

        shipVel = self.getVel()

        bullet = {
            'vel': (headingX * Ship.BULLET_SPEED +
                    shipVel[0] / Ship.BULLET_SHIP_SPEED_CORRELATION,
                    headingY * Ship.BULLET_SPEED +
                    shipVel[1] / Ship.BULLET_SHIP_SPEED_CORRELATION),
            'visual':
            bulletVisual,
            'physical':
            collisionSphere,
            'isAlive':
            True,
            'timeToLive':
            Ship.BULLET_MAX_LIFE_TIME
        }
        self.bullets.append(bullet)
        self.shootingSound.play()
Beispiel #56
0
    def startGame(self):
        self.hideLogin()
        """Initialise the game environment and characters."""
        # Post some onscreen instructions.

        title = addTitle("Nexus Demo")
        # inst1 = addInstructions(0.95, "[ESC]: Quit")
        # inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        # inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        # inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        # inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward")
        # inst6 = addInstructions(0.65, "[A]: Rotate Camera Left")
        # inst7 = addInstructions(0.60, "[S]: Rotate Camera Right")

        # Initialise the environment.

        base.win.setClearColor(Vec4(0, 0, 0, 1))
        environ = loader.loadModel(Config.MYDIR + "/models/world/world")
        environ.reparentTo(render)
        environ.setPos(0, 0, 0)
        environ.setCollideMask(BitMask32.bit(1))

        # Create a character for the player.

        player = Character("/models/ralph/ralph", "/models/ralph/ralph-run",
                           "/models/ralph/ralph-walk",
                           environ.find("**/start_point").getPos(), .2)

        # Hook up some control keys to the character

        self.accept("arrow_left", player.setControl, ["left", 1])
        self.accept("arrow_right", player.setControl, ["right", 1])
        self.accept("arrow_up", player.setControl, ["up", 1])
        self.accept("arrow_down", player.setControl, ["down", 1])

        # Stop event handling if the keys are lifted up
        self.accept("arrow_left-up", player.setControl, ["left", 0])
        self.accept("arrow_right-up", player.setControl, ["right", 0])
        self.accept("arrow_up-up", player.setControl, ["up", 0])
        self.accept("arrow_down-up", player.setControl, ["down", 0])

        # Create a camera to follow the player.

        camera = Camera(player.actor)

        # Accept some keys to move the camera.

        self.accept("a-up", camera.setControl, ["left", 0])
        self.accept("s-up", camera.setControl, ["right", 0])
        self.accept("a", camera.setControl, ["left", 1])
        self.accept("s", camera.setControl, ["right", 1])
 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 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