예제 #1
0
    def add_gravity_region(self, size, pos, gravity):
        """Makes a bullet ghost, when a object enters
        its gravity is changed to match the arguments passed
        """
        shape = BulletBoxShape(Vec3(size))

        grav_ghost = BulletGhostNode('Ghost')
        grav_ghost.addShape(shape)
        grav_ghost_NP = render.attachNewNode(grav_ghost)
        grav_ghost_NP.setPos(pos)
        grav_ghost_NP.setCollideMask(BitMask32(0x0f))

        self.world.attachGhost(grav_ghost)

        def check_gravity_region(task):
            """Check what bullet nodes are inside
                and apply gravity to them.
            """
            ghost = grav_ghost_NP.node()
            print ghost.getNumOverlappingNodes()
            for node in ghost.getOverlappingNodes():
                print node
                #TODO: Make this only apply when in the region
                #EX: Gravity is set to X  inside, set back to normal when out
                node.setGravity(Vec3(gravity))
            return task.cont
        #Add the region checker task
        taskMgr.add(check_gravity_region, "check_gravity_region")
예제 #2
0
class SMCollect():
	def __init__(self, world, worldNP, sPos):
		self.world = world
		self.worldNP = worldNP
		self.collected = False
		self.collectShape = BulletBoxShape(Vec3(3, 5, 5))
		self.collectGN = BulletGhostNode('Box')
		self.collectGN.addShape(self.collectShape)
		self.collectNP = self.create(sPos, self.collectGN)
		print("Collectable Initialized")
	
	def exists(self):
		return not(self.collected)
	
	def getNode(self):
		return self.collectGN
	
	def create(self, pos, ghostNode):
		collectNode = render.attachNewNode(ghostNode)
		collectNode.setPos(pos)
		collectNode.setCollideMask(BitMask32(0x0f))
		self.world.attachGhost(ghostNode)
		visualCN = loader.loadModel("../res/models/snowflake.egg")
		visualCN.reparentTo(collectNode)
		visualCN.setScale(2)
		return collectNode
		
	def destroy(self):
		self.collected = True
		self.world.removeGhost(self.collectGN)
		self.collectNP.removeNode()
예제 #3
0
    def setupCoins2(self):
        # display coins = 0
        textN = TextNode('coin-score')
        textN.setText(str("Coins: " + str(self.coinsCollected2)))
        textN.setSlant(0.1)
        textNodePath = self.aspect2d.attachNewNode(textN)
        textNodePath.setPos(0, 0.95, 0.9)
        textNodePath.setScale(0.08)
        randNum = random.sample(range(0, 1500, 200), 6)

        # coins
        for i in range(6):
            randX = random.uniform(-3.0, 3.2)
            randY = float(randNum[i])
            shape = BulletSphereShape(0.3)
            coinNode = BulletGhostNode('Coin-' + str(i))
            coinNode.addShape(shape)
            np = self.render.attachNewNode(coinNode)
            np.setCollideMask(BitMask32.allOff())
            np.setPos(randX, randY, 2)

            # Adding sphere model
            sphereNp = loader.loadModel('models/smiley.egg')
            sphereNp_tex = loader.loadTexture("models/sky/coin_2_tex.jpg")
            sphereNp.setTexture(sphereNp_tex, 1)
            sphereNp.reparentTo(np)
            sphereNp.setScale(0.45)
            sphereNp.hprInterval(2.5, Vec3(360, 0, 0)).loop()

            self.world2.attachGhost(coinNode)
            self.coins2.append(coinNode)
            print "node name:" + str(coinNode.getName())
예제 #4
0
    def build_node_path(self, parent_node_path, bullet_world):
        land_geom = self.__build_land_mesh()
        ocean_geom = self.__build_ocean_mesh()
        land_mesh = BulletTriangleMesh()
        land_mesh.addGeom(land_geom)
        land_shape = BulletTriangleMeshShape(land_mesh, dynamic=False)
        ocean_shape = BulletSphereShape(self.__radius)

        land_bullet_node = BulletRigidBodyNode('land collider')
        land_bullet_node.addShape(land_shape)
        bullet_world.attachRigidBody(land_bullet_node)
        land_bullet_node_path = parent_node_path.attachNewNode(
            land_bullet_node)

        ocean_bullet_node = BulletGhostNode('ocean collider')
        ocean_bullet_node.addShape(ocean_shape)
        bullet_world.attachGhost(ocean_bullet_node)
        ocean_bullet_node_path = land_bullet_node_path.attachNewNode(
            ocean_bullet_node)

        land_node = GeomNode('land')
        land_node.addGeom(land_geom)
        land_node_path = land_bullet_node_path.attachNewNode(land_node)
        ocean_node = GeomNode('ocean')
        ocean_node.addGeom(ocean_geom)
        ocean_node_path = ocean_bullet_node_path.attachNewNode(ocean_node)
        ocean_node_path.setTransparency(TransparencyAttrib.MAlpha)

        self.__node_path = land_bullet_node_path
        land_bullet_node.setPythonTag('planet', self)
        return land_bullet_node_path
예제 #5
0
 def setupPhysics(self):
     shape = BulletSphereShape(1.0)
     bnode = BulletGhostNode(self.uniqueName('codeNumberPhys'))
     bnode.addShape(shape)
     bnode.setIntoCollideMask(CIGlobals.EventGroup)
     DistributedEntity.setupPhysics(self, bnode, True)
     self.stopWaterCheck()
     self.acceptOnce('enter' + self.uniqueName('codeNumberPhys'),
                     self.__handlePickup)
 def __setupCollisions(self):
     sphere = BulletSphereShape(4.0)
     gnode = BulletGhostNode(self.uniqueName('NPCToonSphere'))
     gnode.addShape(sphere)
     gnode.setKinematic(True)
     self.collisionNodePath = self.attachNewNode(gnode)
     self.collisionNodePath.setY(1.5)
     self.collisionNodePath.setCollideMask(CIGlobals.EventGroup)
     base.physicsWorld.attachGhost(self.collisionNodePath.node())
예제 #7
0
class floatTrap():
    traps = list()
    model = 0
    index = 0
    def __init__(self, ppos, world, worldNP):
        self.world = world
        if floatTrap.model==0:
            floatTrap.model = Model("../assets/3d/Actors/beartrap2.egg")
        h = deg2Rad(camera.getH())
        p = deg2Rad(camera.getP())
        dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
        npos = map(lambda i: ppos[i]+dir[i]*25, range(3))
        self.instance = floatTrap.model.createInstance(pos=npos,hpr=(0,0,0))
        self.index = floatTrap.index
        
        pmin = LPoint3()
        pmax = LPoint3()
        self.instance.calcTightBounds(pmin,pmax)
        norm = pmin-pmax
        self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5)
        r = max(norm)
        shape = BulletSphereShape(.7*r)
        self.sphere = BulletGhostNode('TrapSphere')
        self.sphere.addShape(shape)
        self.sphere.setDeactivationEnabled(False)
        self.np = worldNP.attachNewNode(self.sphere)
        self.np.setPos(LVecBase3(npos[0],npos[1],npos[2]))
        self.np.setCollideMask(BitMask32.allOn())
        world.attachGhost(self.sphere)
        
        #taskMgr.add(self.check,"floatTrap"+str(self.index)+"Check")
        floatTrap.traps.append(self)
        floatTrap.index = floatTrap.index + 1
        #pos = self.instance.getPos()
        #self.np.setPos(pos[0]-self.off[0],pos[1]-self.off[1],pos[2]-self.off[2])
    def kill(self):
        floatTrap.traps.remove(self)
        self.world.removeGhost(self.sphere)
        self.instance.detachNode()
    def check(self,contacts,human,players):
        if len(contacts)>0:
            contactObject = contacts[0].getNode0()
            if contacts[0].getNode0().getName()=="TrapSphere":
                contactObject = contacts[0].getNode1()
            name = contactObject.getName()
            print contactObject
            if name==human.character.getName():
                human.trap1()
                self.kill()
                return
            for i in range(len(players)):
                if name==players[i].character.getName():
                    players[i].trap1()
                    self.kill()
                    return
예제 #8
0
    def buildItemColSphereNP(cls, _engine, _radius, _pos, _head):
        """Build a basic BulletCharacter Controller"""
        sphere = BulletSphereShape(_radius)
        node = BulletGhostNode('ItemSphere')
        node.addShape(sphere)
        np = _engine.BulletObjects["object"].attachNewNode(node)
        np.setPos(_pos)
        np.setH(_head)
        np.setCollideMask(BitMask32(0xf))
        _engine.bulletWorld.attachGhost(node)

        return np
 def _createBtGhostNode_(self,np):
   """
   @brief Creates a Bullet Ghost node from the shapes in the model node.  Ignores
   any local geometry transforms but applies local scaling encoded in the model node.
   """
   bt_shape = self._createBulletShape_(np,True,False)
   if bt_shape is None:
     return None
   
   bt_ghost = BulletGhostNode(np.getName())
   bt_ghost.addShape(bt_shape)      
   return bt_ghost
예제 #10
0
    def setupSensor(self, _obj, _eggFile):
        shape = BulletBoxShape(Vec3(_obj.getScale()))

        ghost = BulletGhostNode("Counter_Ghost_Node")
        ghost.addShape(shape)

        np = self.rootNode.attachNewNode(ghost)
        np.setPos(_obj.getPos())
        np.setCollideMask(BitMask32(0x0f))

        self.parent.physics_world.attachGhost(ghost)

        self.parent.game_counter_node = np
    def __init__(self):
        try:
            self.__initialized
            return
        except:
            self.__initialized = 1

        NodePath.__init__(self, hidden.attachNewNode('PositionExaminer'))

        bsph = BulletSphereShape(1.5)
        bgh = BulletGhostNode('positionExaminer_sphereGhost')
        bgh.addShape(bsph)
        bgh.setKinematic(True)
        self.cSphereNodePath = self.attachNewNode(bgh)
예제 #12
0
    def setupFloaters2(self):
        size = Vec3(3.5, 5.5, 0.3)
        randNum = random.sample(range(10, 1500, 500), 3)
        for i in range(3):
            randX = random.randrange(-2, 3, 10)
            randY = float(randNum[i])
            # randY = random.randint(1000, 1500)
            shape = BulletBoxShape(size * 0.55)
            node = BulletRigidBodyNode('Floater')
            node.setMass(0)
            node.addShape(shape)
            np = self.render.attachNewNode(node)
            # np.setPos(9, 30, 3)
            np.setPos(randX, randY, 6)
            np.setR(0)
            self.world2.attachRigidBody(node)

            dummyNp = self.render.attachNewNode('milkyway')
            dummyNp.setPos(randX, randY, 6)

            modelNP = loader.loadModel('models/box.egg')
            modelNP_tex = loader.loadTexture("models/sky/moon_tex.jpg")
            modelNP.setTexture(modelNP_tex, 1)
            modelNP.reparentTo(dummyNp)
            modelNP.setPos(-1, 0, -1)
            modelNP.setPos(-size.x / 2.0, -size.y / 2.0, -size.z / 2.0)
            modelNP.setScale(size)
            dummyNp.hprInterval(2.5, Vec3(360, 0, 0)).loop()

            # Put A Coin On the Floater
            shape = BulletSphereShape(0.75)
            coinNode = BulletGhostNode('FloaterCoin-' + str(i))
            coinNode.addShape(shape)
            np = self.render.attachNewNode(coinNode)
            np.setCollideMask(BitMask32.allOff())
            # np.setPos(randX, randY, 2)
            np.setPos(randX, randY, 7.0)

            # Adding sphere model
            sphereNp = loader.loadModel('models/smiley.egg')
            sphereNp_tex = loader.loadTexture("models/sky/coin_2_tex.jpg")
            sphereNp.setTexture(sphereNp_tex, 1)
            sphereNp.reparentTo(np)
            sphereNp.setScale(0.85)
            sphereNp.hprInterval(1.5, Vec3(360, 0, 0)).loop()

            self.world2.attachGhost(coinNode)
            self.coins2.append(coinNode)
            print "node name:" + str(coinNode.getName())
예제 #13
0
 def addSpings(self):
     for pos in SPRING_LIST:
         print "add spring #{} at: {}".format(len(self.springs), pos)
         shape = BulletBoxShape(Vec3(0.3, 0.3, 0.8))
         node = BulletGhostNode('Spring' + str(len(self.springs)))
         node.addShape(shape)
         springNP = self.render.attachNewNode(node)
         springNP.setCollideMask(BitMask32.allOff())
         springNP.setPos(pos.getX(), pos.getY(), pos.getZ() + 3.4)
         modelNP = loader.loadModel('models/spring/spring.egg')
         modelNP.reparentTo(springNP)
         modelNP.setScale(1, 1, 1)
         modelNP.setPos(0, 0, -1)
         self.world.attachGhost(node)
         self.springs.append(springNP)
 def __createBulletGhostNodeFromBoxes__(self,boxes,scale, name ):
       
   ghost_node = BulletGhostNode(name)    
   transform  = TransformState.makeIdentity()      
   
   for box in boxes:
     box.scale = scale
     size = box.size
     center = box.center
     box_shape = BulletBoxShape(Vec3(0.5*size[0],0.5*AnimationActor.DEFAULT_WIDTH,0.5 * size[1]))
     #box_shape.setMargin(AnimationActor.COLLISION_MARGIN)
     transform = transform.setPos(Vec3(center[0],0,center[1]))
     ghost_node.addShape(box_shape,transform)
     
   return ghost_node
예제 #15
0
    def buildCharacterGhost(cls, _engine, _height, _radius, _bulletBody, _playerModel, _head):
        """Build a basic BulletGhost body for the player to be used for tracking eventObjects"""

        shape = BulletSphereShape(_radius*4)
        ghost = BulletGhostNode("player_ghost")
        ghost.addShape(shape)
        ghostNP = _engine.BulletObjects["player"].attachNewNode(ghost)
        newz = _playerModel.getPos()
        newz.z = newz.z + 2.5
        ghostNP.setPos(newz)
        ghostNP.setCollideMask(BitMask32.allOff())

        _engine.bulletWorld.attachGhost(ghost)
        ghostNP.reparentTo(_playerModel)

        return ghostNP
예제 #16
0
 def __initCollisions(self, name):
     self.notify.debug("Initializing collision sphere...")
     numSlots = len(self.circles)
     ss = BulletSphereShape(self.numPlayers2SphereRadius[numSlots])
     snode = BulletGhostNode(name)
     snode.addShape(ss)
     snode.setKinematic(True)
     snode.setIntoCollideMask(CIGlobals.LocalAvGroup)
     self.snp = self.attach_new_node(snode)
     self.snp.setZ(3)
     self.snp.setY(self.numPlayers2SphereY[numSlots])
     self.snp.setSx(self.numPlayers2SphereSx[numSlots])
     self.snp.setSy(self.numPlayers2SphereSy[numSlots])
     base.physicsWorld.attachGhost(snode)
     self.acceptOnce("enter" + self.snp.node().getName(),
                     self.__handleEnterCollisionSphere)
예제 #17
0
    def __init__(self,
                 parent_node_np: NodePath,
                 num_lasers: int = 16,
                 distance: float = 50,
                 enable_show=False):
        # properties
        assert num_lasers > 0
        show = enable_show and (AssetLoader.loader is not None)
        self.dim = num_lasers
        self.num_lasers = num_lasers
        self.perceive_distance = distance
        self.height = self.DEFAULT_HEIGHT
        self.radian_unit = 2 * np.pi / num_lasers
        self.start_phase_offset = 0
        self.node_path = parent_node_np.attachNewNode("Could_points")
        self._lidar_range = np.arange(
            0, self.num_lasers) * self.radian_unit + self.start_phase_offset

        # detection result
        self.cloud_points = np.ones((self.num_lasers, ), dtype=float)
        self.detected_objects = []

        # override these properties to decide which elements to detect and show
        self.node_path.hide(CamMask.RgbCam | CamMask.Shadow | CamMask.Shadow
                            | CamMask.DepthCam)
        self.mask = BitMask32.bit(CollisionGroup.BrokenLaneLine)
        self.cloud_points_vis = [] if show else None
        logging.debug("Load Vehicle Module: {}".format(
            self.__class__.__name__))
        if show:
            for laser_debug in range(self.num_lasers):
                ball = AssetLoader.loader.loadModel(
                    AssetLoader.file_path("models", "box.bam"))
                ball.setScale(0.001)
                ball.setColor(0., 0.5, 0.5, 1)
                shape = BulletSphereShape(0.1)
                ghost = BulletGhostNode('Lidar Point')
                ghost.setIntoCollideMask(BitMask32.allOff())
                ghost.addShape(shape)
                laser_np = self.node_path.attachNewNode(ghost)
                self.cloud_points_vis.append(laser_np)
                ball.getChildren().reparentTo(laser_np)
예제 #18
0
    def announceGenerate(self):
        DistributedEntity.announceGenerate(self)

        self.addSound("pickup", "sound/items/jellybean_pickup.ogg")

        import random
        color = random.choice(self.Colors)
        self.getModelNP().setColorScale(color, 1)

        from direct.interval.IntervalGlobal import LerpHprInterval
        self.rot = LerpHprInterval(self.getModelNP(), 1.0, (360, 0, 0), (0, 0, 0))
        self.rot.loop()

        from src.coginvasion.globals import CIGlobals
        from panda3d.bullet import BulletSphereShape, BulletGhostNode
        sph = BulletSphereShape(0.5)
        body = BulletGhostNode(self.uniqueName('jellybean-trigger'))
        body.addShape(sph)
        body.setIntoCollideMask(CIGlobals.EventGroup)
        self.setupPhysics(body, True)
        self.acceptOnce('enter' + self.uniqueName('jellybean-trigger'), self.__enterJellybeanTrigger)
    def makeNodePath(self):
        self.nodePath = NodePath('treasure')
        if self.billboard: self.nodePath.setBillboardPointEye()
        self.nodePath.setScale(0.9 * self.scale)
        self.treasure = self.nodePath.attachNewNode('treasure')
        if self.shadow:
            if not self.dropShadow:
                self.dropShadow = loader.loadModel(
                    'phase_3/models/props/drop_shadow.bam')
                self.dropShadow.setColor(0, 0, 0, 0.5)
                self.dropShadow.setPos(0, 0, 0.025)
                self.dropShadow.setScale(0.4 * self.scale)
                self.dropShadow.flattenLight()
            self.dropShadow.reparentTo(self.nodePath)

        sphere = BulletSphereShape(self.sphereRadius)
        ghost = BulletGhostNode(self.uniqueName('treasureSphere'))
        ghost.addShape(sphere)
        ghost.setIntoCollideMask(CIGlobals.EventGroup)
        self.collNodePath = self.nodePath.attachNewNode(ghost)
        self.collNodePath.stash()
예제 #20
0
    def setupCollector(self, _obj, _eggFile):
        tb = _obj.getTightBounds()
        boxSize = VBase3(tb[1] - tb[0])
        # TODO: istn't there a better way to multiply those two vectors?
        s = _obj.getTransform().getScale()
        boxSize[0] *= s[0]
        boxSize[1] *= s[1]
        boxSize[2] *= s[2]
        shape = BulletBoxShape(boxSize * 0.5)

        ghost = BulletGhostNode("Collector_Ghost_Node")
        ghost.addShape(shape)

        np = self.rootNode.attachNewNode(ghost)
        np.setPos(_obj.getPos())
        np.setHpr(_obj.getHpr())
        np.setCollideMask(BitMask32(0x0f))

        self.parent.physics_world.attachGhost(ghost)

        self.parent.game_collector_nodes.append(np)
예제 #21
0
  def __init__(self,name,right_side_ledge, size = __DEFAULT_SIZE__):
    '''
    Ledge(string name,Bool right_side_ledge, Platform parent_platform, Vec3 size = default)
    
      Creates a ledge object used to detect the extent of a platform at a given location
      The size should be [diameter, height, 0] and the cylinder shape axis is oriented
      in the Y+ direction.
    '''
    
    # storing members
    radius = size.getX()*0.5
    height = size.getY();
    self.size_ = size
    self.parent_platform_ = None #parent_platform
    self.is_right_side_ledge_ = right_side_ledge

    
    ledge_gn = BulletGhostNode(name)
    ledge_gn.addShape(BulletCylinderShape(radius,height, Y_up) )
    ledge_gn.setIntoCollideMask(CollisionMasks.LEDGE)  
    
    GameObject.__init__(self,ledge_gn)
예제 #22
0
 def __init__(self, parent_node_np: NodePath, laser_num: int = 240, distance: float = 50):
     show = self.enable_show and (AssetLoader.loader is not None)
     self.Lidar_point_cloud_obs_dim = laser_num
     self.laser_num = laser_num
     self.perceive_distance = distance
     self.radian_unit = 2 * np.pi / laser_num
     self.detection_results = []
     self.node_path = parent_node_np.attachNewNode("cloudPoints")
     self.node_path.hide(CamMask.RgbCam | CamMask.Shadow)
     self.cloud_points = [] if show else None
     logging.debug("Load Vehicle Module: {}".format(self.__class__.__name__))
     if show:
         for laser_debug in range(self.laser_num):
             ball = AssetLoader.loader.loadModel(AssetLoader.file_path("models", "box.egg"))
             ball.setScale(0.001)
             ball.setColor(0., 0.5, 0.5, 1)
             shape = BulletSphereShape(0.1)
             ghost = BulletGhostNode('Lidar Point')
             ghost.setIntoCollideMask(BitMask32.allOff())
             ghost.addShape(shape)
             laser_np = self.node_path.attachNewNode(ghost)
             self.cloud_points.append(laser_np)
             ball.getChildren().reparentTo(laser_np)
    def load(self):
        if self.autoPhysBox:
            min = Point3(0)
            max = Point3(0)
            self.getUseableBounds(min, max)

            min -= Point3(0.1, 0.1, 0.1)
            max += Point3(0.1, 0.1, 0.1)

            center = PhysicsUtils.centerFromMinMax(min, max)
            extents = PhysicsUtils.extentsFromMinMax(min, max)

            shape = BulletBoxShape(extents)
            # Use the box as a trigger and collision geometry.
            if self.hasPhysGeom:
                bodyNode = BulletGhostNode('useableObject')
            else:
                bodyNode = BulletRigidBodyNode('useableObject')
            bodyNode.setKinematic(True)
            bodyNode.addShape(shape, TransformState.makePos(center))

            self.setupPhysics(bodyNode)
        if self.bodyNP:
            self.bodyNP.setPythonTag('useableObject', self)
예제 #24
0
    def load(self):
        DistributedEntityAI.load(self)
        self.setHpr(self.cEntity.getAngles())
        self.setPos(self.cEntity.getOrigin())

        self.setModel("phase_9/models/cogHQ/square_stomper.bam")
        self.setModelScale(self.scale)
        self.getModelNP().find("**/shaft").setSy(self.height / 16.0)

        self.optimizeModel()

        box = BulletBoxShape((self.scale[1], 1.0, self.scale[0]))
        gh = BulletGhostNode('trigger_hurt')
        gh.addShape(box, TransformState.makePos((0, -0.5, 0)))
        self.floorColl = self.getModelNP().attachNewNode(gh)
        self.floorColl.setCollideMask(CIGlobals.WallGroup
                                      | CIGlobals.CharacterGroup)

        self.enableModelCollisions()

        for bNP in self.getModelNP().findAllMatches("**/+BulletRigidBodyNode"):
            bNP.setSurfaceProp("metal")

        self.b_setEntityState(self.StateUp)
class Models(object):


    def __init__(self):
        
        self.setup()
        
        
        self.angel = 1

               
        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(3000,3000,1)
        self.desert_tex = loader.loadTexture("models/desert.jpg")
        self.environ.setTexture(self.desert_tex, 1)
        
        self.sky = loader.loadModel("models/solar_sky_sphere")
        self.sky.reparentTo(render)
        self.sky.setScale(10000)
        self.sky.setPos(0,0,0)
        self.sky_tex = loader.loadTexture("models/stars_1k_tex.jpg")
        self.sky.setTexture(self.sky_tex, 1)
        
    
        

        
        
    
    def setup(self):
        
        
        
        #World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))
        
        
        
        #Ground
        shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        self.ground = BulletRigidBodyNode('Ground')
        self.ground.addShape(shape) 
        self.groundNp = render.attachNewNode(self.ground)
        self.groundNp.setPos(0, 0, 0)
        self.groundNp.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.ground)
        
        
        
        #BoxPyramid1
        self.pyramid1 = loader.loadModel("models/pyramid/Pyramid")
        self.pyramid1.reparentTo(render)
        self.pyramid1.setScale(.5)
        self.pyramid1.setPos(0,-400,0)
        
        mesh = BulletTriangleMesh()
        for geomNP in self.pyramid1.findAllMatches('**/+GeomNode'):
            geomNode = geomNP.node()
            ts = geomNP.getTransform(self.pyramid1)
            for geom in geomNode.getGeoms():
                mesh.addGeom(geom, ts)
                
                
        shape2 = BulletTriangleMeshShape(mesh, dynamic=False)
        self.node = BulletRigidBodyNode('BoxPyramid1')
        self.node.setMass(0)
        self.node.addShape(shape2)
        self.np = render.attachNewNode(self.node)
        self.np.setPos(0, -400, 0)
        self.np.setScale(1.65)
        self.np.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node)
        
        
        #BoxPyramid2
        self.pyramid2 = loader.loadModel("models/pyramid/Pyramid")
        self.pyramid2.reparentTo(render)
        self.pyramid2.setScale(.25)
        self.pyramid2.setPos(180,-400,0)
        
        mesh2 = BulletTriangleMesh()
        for geomNP in self.pyramid2.findAllMatches('**/+GeomNode'):
            geomNode = geomNP.node()
            ts = geomNP.getTransform(self.pyramid2)
            for geom in geomNode.getGeoms():
                mesh2.addGeom(geom, ts)
                
        shape3 = BulletTriangleMeshShape(mesh2, dynamic=False)
        self.node3 = BulletRigidBodyNode('BoxPyramid2')
        self.node3.setMass(0)
        self.node3.addShape(shape3)
        self.np3 = render.attachNewNode(self.node3)
        self.np3.setPos(180, -400, 0)
        self.np3.setScale(0.85)
        self.np3.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node3)
        
        
        #BoxPyramid3
        self.pyramid3 = loader.loadModel("models/pyramid/Pyramid")
        self.pyramid3.reparentTo(render)
        self.pyramid3.setScale(.25)
        self.pyramid3.setPos(-180,-400,0)
        
        mesh3 = BulletTriangleMesh()
        for geomNP in self.pyramid3.findAllMatches('**/+GeomNode'):
            geomNode = geomNP.node()
            ts = geomNP.getTransform(self.pyramid3)
            for geom in geomNode.getGeoms():
                mesh3.addGeom(geom, ts)
                
                
        shape4 = BulletTriangleMeshShape(mesh2, dynamic=False)
        self.node4 = BulletRigidBodyNode('BoxPyramid3')
        self.node4.setMass(0)
        self.node4.addShape(shape4)
        self.np4 = render.attachNewNode(self.node4)
        self.np4.setPos(-180, -400, 0)
        self.np4.setScale(0.85)
        self.np4.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node4)
        
        
        #BoxSphinx       
        self.sphinx = loader.loadModel("models/sphinx/Sphinx")
        self.sphinx.reparentTo(render)
        self.sphinx.setScale(.08)
        self.sphinx.setPos(100,-50,20)
        shape5 = BulletBoxShape(Vec3(18, 55, 30))
        self.node5 = BulletRigidBodyNode('BoxSphinx')
        self.node5.setMass(0)
        self.node5.addShape(shape5)
        self.np5 = render.attachNewNode(self.node5)
        self.np5.setPos(100, -50, 10)
        self.np5.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node5)
            
    
        
        #start
        blocks_tex6 = loader.loadTexture("models/blocks_tex6.jpg")


   
        
        self.box1= loader.loadModel("models/box/box3")
        self.box1.reparentTo(render)
        self.box1.setScale(10,400,10)
        self.box1.setPos(-300,850,0)
        shape8 = BulletBoxShape(Vec3(8, 315, 13.5))
        self.node8 = BulletRigidBodyNode('Box1')
        self.node8.setMass(0)
        self.node8.addShape(shape8)
        self.np8 = render.attachNewNode(self.node8)
        self.np8.setPos(-300, 850, 10)
        self.np8.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node8) 
        
        
        self.box2= loader.loadModel("models/box/box3")
        self.box2.reparentTo(render)
        self.box2.setScale(10,400,10)
        self.box2.setPos(-350,850,0)
        shape9 = BulletBoxShape(Vec3(8, 315, 13.5))
        self.node9 = BulletRigidBodyNode('Box2')
        self.node9.setMass(0)
        self.node9.addShape(shape9)
        self.np9 = render.attachNewNode(self.node9)
        self.np9.setPos(-350, 850, 10)
        self.np9.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node9) 
        
        
        self.box3= loader.loadModel("models/box/box4")
        self.box3.reparentTo(render)
        self.box3.setScale(40,10,10)
        self.box3.setPos(-325,543,0)
        shape10 = BulletBoxShape(Vec3(30, 8, 13.5))
        self.node10 = BulletRigidBodyNode('Box3')
        self.node10.setMass(0)
        self.node10.addShape(shape10)
        self.np10 = render.attachNewNode(self.node10)
        self.np10.setPos(-325, 543, 10)
        self.np10.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node10) 
        
        self.box4= loader.loadModel("models/box/box4")
        self.box4.reparentTo(render)
        self.box4.setScale(40,10,10)
        self.box4.setPos(-325,1157,0)
        shape11 = BulletBoxShape(Vec3(30, 8, 13.5))
        self.node11 = BulletRigidBodyNode('Box4')
        self.node11.setMass(0)
        self.node11.addShape(shape11)
        self.np11 = render.attachNewNode(self.node11)
        self.np11.setPos(-325, 1157, 10)
        self.np11.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node11) 
        
        
        #Stars 1
        self.stairsList = [0] * 10
        self.stairsListNp = [0] * 10

        
        n5 = 0
        for i in range(10):
            n5 += 2
            self.stairsList[i]= loader.loadModel("models/box/box1")
            self.stairsList[i].reparentTo(render)
            self.stairsList[i].setScale(1.3)
            self.stairsList[i].setPos(-325,925-(n5*1.2),n5)
            self.stairsList[i].setHpr(0,0,90)
            shape6 = BulletBoxShape(Vec3(3.2, 1.1, 1.1))
            node6 = BulletRigidBodyNode('Box5 '+str(i))
            node6.setMass(0)
            node6.addShape(shape6)
            self.stairsListNp[i] = render.attachNewNode(node6)
            self.stairsListNp[i].setPos(-325, 925-(n5*1.2), n5)
            self.stairsListNp[i].setCollideMask(BitMask32.allOn())
            self.world.attachRigidBody(node6) 
            
        self.n5Upstairs = n5
        
        self.box6= loader.loadModel("models/box/box1")
        self.box6.reparentTo(render)
        self.box6.setScale(10,87,0.2)
        self.box6.setPos(-325,829,n5)
        self.shape12 = BulletBoxShape(Vec3(8, 70, 0.75))
        self.node12 = BulletRigidBodyNode('Box6')
        self.node12.setMass(0)
        self.node12.addShape(self.shape12)
        self.np12 = render.attachNewNode(self.node12)
        self.np12.setPos(-325, 829, n5)
        self.np12.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node12) 
        
        
        
        self.box7= loader.loadModel("models/box/box2")
        self.box7.reparentTo(render)
        self.box7.setScale(5,12,0.25)
        self.box7.setPos(-325,749,n5)
        shape13 = BulletBoxShape(Vec3(4, 10, 0.8))
        self.node13 = BulletRigidBodyNode('Box7')
        self.node13.setMass(0)
        self.node13.addShape(shape13)
        self.np13 = render.attachNewNode(self.node13)
        self.np13.setPos(-325, 749, n5)
        self.np13.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node13)
        
        
        box7Interval1 = self.box7.posInterval(3.3, Point3(-325, 749, n5+5),
        startPos=Point3(-325, 749, n5-5))
        np13Interval1 = self.np13.posInterval(3, Point3(-325, 749, n5+5),
        startPos=Point3(-325, 749, n5-5))
        box7Interval2 = self.box7.posInterval(3.3, Point3(-325, 749, n5-5),
        startPos=Point3(-325, 749, n5+5))
        np13Interval2 = self.np13.posInterval(3, Point3(-325, 749, n5-5),
        startPos=Point3(-325, 749, n5+5)) 
             
        self.box7Pace = Sequence(Parallel(box7Interval1,np13Interval1),
                                 Parallel(box7Interval2,np13Interval2),
                                 name="box7Pace")
        self.box7Pace.loop() 
        
        
        
        self.box8= loader.loadModel("models/box/box2")
        self.box8.reparentTo(render)
        self.box8.setScale(5,12,0.25)
        self.box8.setPos(-325,725,n5)
        shape14 = BulletBoxShape(Vec3(4, 10, 0.8))
        node14 = BulletRigidBodyNode('Box8')
        node14.setMass(0)
        node14.addShape(shape14)
        self.np14 = render.attachNewNode(node14)
        self.np14.setPos(-325, 725, n5)
        self.np14.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(node14)
        
        
        box8Interval1 = self.box8.posInterval(3.3, Point3(-325, 725, n5-5),
        startPos=Point3(-325, 725, n5+5))
        np14Interval1 = self.np14.posInterval(3, Point3(-325, 725, n5-5),
        startPos=Point3(-325, 725, n5+5))
        box8Interval2 = self.box8.posInterval(3.3, Point3(-325, 725, n5+5),
        startPos=Point3(-325, 725, n5-5))
        np14Interval2 = self.np14.posInterval(3, Point3(-325, 725, n5+5),
        startPos=Point3(-325, 725, n5-5)) 
             
        self.box8Pace = Sequence(Parallel(box8Interval1,np14Interval1),
                                 Parallel(box8Interval2,np14Interval2),
                                 name="box8Pace")
        self.box8Pace.loop() 
        

        self.Cylinder1= loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder1.reparentTo(render)
        self.Cylinder1.setScale(8,8,0.2)
        self.Cylinder1.setPos(-322,700,n5)
        self.Cylinder1.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape16 = BulletCylinderShape(radius, height, ZUp)
        self.node16 = BulletRigidBodyNode('Cylinder1')
        self.node16.setMass(0)
        self.node16.addShape(shape16)
        self.np16 = render.attachNewNode(self.node16)
        self.np16.setPos(-322, 700, n5)
        self.np16.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node16)
        
        
        self.Cylinder2= loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder2.reparentTo(render)
        self.Cylinder2.setScale(8,8,0.2)
        self.Cylinder2.setPos(-327,680,n5)
        self.Cylinder2.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape17 = BulletCylinderShape(radius, height, ZUp)
        self.node17 = BulletRigidBodyNode('Cylinder2')
        self.node17.setMass(0)
        self.node17.addShape(shape17)
        self.np17 = render.attachNewNode(self.node17)
        self.np17.setPos(-327, 680, n5)
        self.np17.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node17)
        
        
        
        self.Cylinder3= loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder3.reparentTo(render)
        self.Cylinder3.setScale(8,8,0.2)
        self.Cylinder3.setPos(-322,660,n5)
        self.Cylinder3.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape18 = BulletCylinderShape(radius, height, ZUp)
        self.node18 = BulletRigidBodyNode('Cylinder3')
        self.node18.setMass(0)
        self.node18.addShape(shape18)
        self.np18 = render.attachNewNode(self.node18)
        self.np18.setPos(-322, 660, n5)
        self.np18.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node18)
        
        
        self.Cylinder4= loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder4.reparentTo(render)
        self.Cylinder4.setScale(8,8,0.2)
        self.Cylinder4.setPos(-327,640,n5)
        self.Cylinder4.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape19 = BulletCylinderShape(radius, height, ZUp)
        self.node19 = BulletRigidBodyNode('Cylinder4')
        self.node19.setMass(0)
        self.node19.addShape(shape19)
        self.np19 = render.attachNewNode(self.node19)
        self.np19.setPos(-327, 640, n5)
        self.np19.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node19)
        
        
        self.fire= loader.loadModel("models/stop_sign/stop_sign")
        self.fire.setScale(0.01)
        self.fire.reparentTo(render)
        self.fire.setPos(-327,640,n5+5)
        
        #setup the items to be collected 
        self.setupItems()
        
        self.setupEndPoint()
        
    
        
 
        #################End point###################################
        

        

    
    def setupEndPoint(self):
        
        blocks_tex8 = loader.loadTexture("models/blocks_tex8.jpg")

        self.endpoint= loader.loadModel("models/Sphere_HighPoly/Sphere_HighPoly")
        self.endpoint.reparentTo(render)
        self.endpoint.setScale(.8)
        self.endpoint.setPos(0,-200,2)
        self.endpoint.setTexture(blocks_tex8, 1)
        radius = 2.65
        self.shapeEnd = BulletSphereShape(radius)
        self.nodeEnd = BulletGhostNode('EndPoint')
        self.nodeEnd.addShape(self.shapeEnd)
        self.npEnd = render.attachNewNode(self.nodeEnd)
        self.npEnd.setPos(0, -200, 2)
        self.npEnd.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(self.nodeEnd)
        
        
    def setupItems(self):
        
        #############Items########################################
        
        self.iteamsModelsList = [0] * 50
        self.iteamsNodesList = [0] * 50
        self.iteamsNpsList = [0] * 50


        self.index = 0        
            
        n6 = 0
        for i in range(10):
            
            t1= loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(-325,925-(n6*1.2),n6+2)
            t1.setHpr(0,90,0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(-325, 925-(n6*1.2), n6+2)
            npt1.setHpr(0,90,0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)
            
            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1            
            
            n6  += 2
            self.index += 1
            
            
        n7 = 20
        for i in range(5):
            
            t1= loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(-325,880-n7,n6+2)
            t1.setHpr(0,90,0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(-325, 880-n7, n6+2)
            npt1.setHpr(0,90,0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)
            
            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1            
            
            n7  += 20
            self.index += 1
            
   
        t1= loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder1.getX(),self.Cylinder1.getY(),n6+2)
        t1.setHpr(0,90,0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder1.getX(),self.Cylinder1.getY(),n6+2)
        npt1.setHpr(0,90,0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)
            
        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1            
            
        self.index += 1
            
        t1= loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder2.getX(),self.Cylinder2.getY(),n6+2)
        t1.setHpr(0,90,0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder2.getX(),self.Cylinder2.getY(),n6+2)
        npt1.setHpr(0,90,0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)
            
        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1            
            
        self.index += 1
            
            
        t1= loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder3.getX(),self.Cylinder3.getY(),n6+2)
        t1.setHpr(0,90,0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder3.getX(),self.Cylinder3.getY(),n6+2)
        npt1.setHpr(0,90,0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)
            
        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1            
            
        self.index += 1
        

        
            
            
        n6 = 0
        for i in range(30):
            x = random.randint(-50, 50)
            y = random.randint(-50, 50) 
            t1= loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x,y,2)
            t1.setHpr(0,90,0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 2)
            npt1.setHpr(0,90,0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)
            
            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1            
            
            n6  += 2
            self.index += 1
예제 #26
0
class clawTrap():
    traps = list()
    model = 0
    index = 0
    def __init__(self, world, worldNP):
        self.failed = 1
        self.world = world
        if clawTrap.model==0:
            clawTrap.model = Model("../assets/3d/Actors/claw3.egg")
        h = deg2Rad(camera.getH())
        p = deg2Rad(camera.getP())
        dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
        cpos = camera.getPos()
        vec = map(lambda i: cpos[i]+dir[i]*200, range(3))
        rayHit = world.rayTestClosest(cpos,LPoint3(vec[0],vec[1],vec[2]))
        if not rayHit.hasHit():
            return
        npos = rayHit.getHitPos()
        n = rayHit.getHitNormal()
        print n
        npos = map(lambda i: npos[i]+n[i]*5, range(3))
        self.instance = clawTrap.model.createInstance(pos=npos,hpr=(-90*n.x,180*(n.z==1)+90*(abs(n.x)+n.y),0))
        self.index = clawTrap.index
        
        pmin = LPoint3()
        pmax = LPoint3()
        self.instance.calcTightBounds(pmin,pmax)
        norm = pmin-pmax
        self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5)
        r = max(norm)
        shape = BulletSphereShape(.7*r)
        self.sphere = BulletGhostNode('TrapSphere')
        self.sphere.addShape(shape)
        self.sphere.setDeactivationEnabled(False)
        self.np = worldNP.attachNewNode(self.sphere)
        self.np.setPos(LVecBase3(npos[0],npos[1],npos[2]))
        self.np.setCollideMask(BitMask32.allOn())
        world.attachGhost(self.sphere)
        
        #taskMgr.add(self.check,"floatTrap"+str(self.index)+"Check")
        clawTrap.traps.append(self)
        clawTrap.index = clawTrap.index + 1
        self.failed = 0
        #pos = self.instance.getPos()
        #self.np.setPos(pos[0]-self.off[0],pos[1]-self.off[1],pos[2]-self.off[2])
    def kill(self):
        clawTrap.traps.remove(self)
        self.world.removeGhost(self.sphere)
        self.instance.detachNode()
    def check(self,contacts,human,players):
        if len(contacts)>0:
            contactObject = contacts[0].getNode0()
            if contacts[0].getNode0().getName()=="TrapSphere":
                contactObject = contacts[0].getNode1()
            name = contactObject.getName()
            print contactObject
            if name==human.character.getName():
                human.trap2()
                self.kill()
                return
            for i in range(len(players)):
                if name==players[i].character.getName():
                    players[i].trap2()
                    self.kill()
                    return
예제 #27
0
class MyApp(ShowBase):
    def __init__(self, screen_size=84, DEBUGGING=False):
        ShowBase.__init__(self)
        self.render_stuff = True
        self.actions = 3

        self.render.setShaderAuto()
        self.cam.setPos(0, 0, 7)
        self.cam.lookAt(0, 0, 0)

        wp = WindowProperties()
        window_size = screen_size
        wp.setSize(window_size, window_size)
        self.win.requestProperties(wp)

        # Create Ambient Light
        self.ambientLight = AmbientLight('ambientLight')
        self.ambientLight.setColor((0.2, 0.2, 0.2, 1))
        self.ambientLightNP = self.render.attachNewNode(self.ambientLight)
        self.render.setLight(self.ambientLightNP)

        # Spotlight
        self.light = Spotlight('light')
        self.light.setColor((0.9, 0.9, 0.9, 1))
        self.lightNP = self.render.attachNewNode(self.light)
        self.lightNP.setPos(0, 10, 10)
        self.lightNP.lookAt(0, 0, 0)
        self.lightNP.node().getLens().setFov(40)
        self.lightNP.node().getLens().setNearFar(10, 100)
        self.lightNP.node().setShadowCaster(True, 1024, 1024)
        self.render.setLight(self.lightNP)

        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        if DEBUGGING is True:
            debugNode = BulletDebugNode('Debug')
            debugNode.showWireframe(True)
            debugNode.showConstraints(True)
            debugNode.showBoundingBoxes(False)
            debugNode.showNormals(False)
            debugNP = render.attachNewNode(debugNode)
            debugNP.show()
            self.world.setDebugNode(debugNP.node())

        # Reward zone
        self.rzone_shape = BulletBoxShape(Vec3(.8, 1, 0.5))
        self.rzone_ghost = BulletGhostNode('Reward Zone')
        self.rzone_ghost.addShape(self.rzone_shape)
        self.rzone_ghostNP = self.render.attachNewNode(self.rzone_ghost)
        self.rzone_ghostNP.setPos(2.2, 0.0, 0.86)
        self.rzone_ghostNP.setCollideMask(BitMask32(0x0f))
        self.world.attachGhost(self.rzone_ghost)

        # Needed for camera image
        self.dr = self.camNode.getDisplayRegion(0)

        # Needed for camera depth image
        winprops = WindowProperties.size(self.win.getXSize(),
                                         self.win.getYSize())
        fbprops = FrameBufferProperties()
        fbprops.setDepthBits(1)
        self.depthBuffer = self.graphicsEngine.makeOutput(
            self.pipe, "depth buffer", -2, fbprops, winprops,
            GraphicsPipe.BFRefuseWindow, self.win.getGsg(), self.win)
        self.depthTex = Texture()
        self.depthTex.setFormat(Texture.FDepthComponent)
        self.depthBuffer.addRenderTexture(self.depthTex,
                                          GraphicsOutput.RTMCopyRam,
                                          GraphicsOutput.RTPDepth)
        lens = self.cam.node().getLens()
        # the near and far clipping distances can be changed if desired
        # lens.setNear(5.0)
        # lens.setFar(500.0)
        self.depthCam = self.makeCamera(self.depthBuffer,
                                        lens=lens,
                                        scene=render)
        self.depthCam.reparentTo(self.cam)

    def reset(self):
        namelist = [
            'Ground', 'Conveyor', 'Finger', 'Block', 'Scrambled Block',
            'Not Rewardable', 'Teleport Me'
        ]
        for child in render.getChildren():
            for test in namelist:
                if child.node().name == test:
                    self.world.remove(child.node())
                    child.removeNode()
                    break

        # Plane
        self.plane_shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        self.plane_node = BulletRigidBodyNode('Ground')
        self.plane_node.addShape(self.plane_shape)
        self.plane_np = self.render.attachNewNode(self.plane_node)
        self.plane_np.setPos(0.0, 0.0, -1.0)
        self.world.attachRigidBody(self.plane_node)

        # Conveyor
        self.conv_node = BulletRigidBodyNode('Conveyor')
        self.conv_node.setFriction(1.0)
        self.conv_np = self.render.attachNewNode(self.conv_node)
        self.conv_shape = BulletBoxShape(Vec3(100.0, 1.0, 0.05))
        self.conv_node.setMass(1000.0)
        self.conv_np.setPos(-95.0, 0.0, 0.1)
        self.conv_node.addShape(self.conv_shape)
        self.world.attachRigidBody(self.conv_node)
        self.model = loader.loadModel('assets/conv.egg')
        self.model.flattenLight()
        self.model.reparentTo(self.conv_np)

        # Finger
        self.finger_node = BulletRigidBodyNode('Finger')
        self.finger_node.setFriction(1.0)
        self.finger_np = self.render.attachNewNode(self.finger_node)
        self.finger_shape = BulletCylinderShape(0.1, 0.25, ZUp)
        self.finger_node.setMass(0)
        self.finger_np.setPos(1.8, 0.0, 0.24 + 0.0254 * 3.5)
        self.finger_node.addShape(self.finger_shape)
        self.world.attachRigidBody(self.finger_node)
        self.model = loader.loadModel('assets/finger.egg')
        self.model.flattenLight()
        self.model.reparentTo(self.finger_np)

        self.blocks = []
        for block_num in range(15):
            new_block = self.spawn_block(Vec3(18, 0, (0.2 * block_num) + 2.0))
            self.blocks.append(new_block)

        self.have_scramble = False
        self.penalty_applied = False
        self.spawnned = False
        self.score = 10
        self.teleport_cooled_down = True
        self.fps = 20
        self.framecount = 0

        return self.step(1)[0]

    def spawn_block(self, location):
        node = BulletRigidBodyNode('Block')
        node.setFriction(1.0)
        block_np = self.render.attachNewNode(node)
        block_np.setAntialias(AntialiasAttrib.MMultisample)
        shape = BulletBoxShape(Vec3(0.0254 * 4, 0.0254 * 24, 0.0254 * 2))
        node.setMass(1.0)
        #block_np.setPos(-3.7, 0.0, 2.0)
        block_np.setPos(location)
        block_np.setHpr(random.uniform(-60, 60), 0.0, 0.0)
        node.addShape(shape)
        self.world.attachRigidBody(node)
        model = loader.loadModel('assets/bullet-samples/models/box.egg')
        model.setH(90)
        model.setSy(0.0254 * 4 * 2)
        model.setSx(0.0254 * 24 * 2)
        model.setSz(0.0254 * 2 * 2)
        model.flattenLight()
        model.reparentTo(block_np)
        return block_np

    def get_camera_image(self, requested_format=None):
        """
        Returns the camera's image, which is of type uint8 and has values
        between 0 and 255.
        The 'requested_format' argument should specify in which order the
        components of the image must be. For example, valid format strings are
        "RGBA" and "BGRA". By default, Panda's internal format "BGRA" is used,
        in which case no data is copied over.
        """
        tex = self.dr.getScreenshot()
        if requested_format is None:
            data = tex.getRamImage()
        else:
            data = tex.getRamImageAs(requested_format)
        image = np.frombuffer(
            data, np.uint8)  # use data.get_data() instead of data in python 2
        image.shape = (tex.getYSize(), tex.getXSize(), tex.getNumComponents())
        image = np.flipud(image)
        return image[:, :, :3]

    def reset_conv(self):
        conveyor_dist_left = 1 - self.conv_np.getPos()[0]
        if conveyor_dist_left < 10:
            self.conv_np.setX(-95.0)
            self.conv_np.setY(0.0)
        # self.conv_np.setY(0.0)
        # self.conv_np.setHpr(0.0, 0.0, 0.0)

    def check_penalty(self):
        penalty = 0
        self.pzone_ghost = self.pzone_ghostNP.node()
        for node in self.pzone_ghost.getOverlappingNodes():
            if node.name == 'Block':
                penalty = 1
                node.name = 'Scramble'
                self.have_scramble = False
        return penalty

    def check_rewards(self):
        reward = 0
        # Check for reward blocks (recently cleared scrambles)
        rzone_ghost = self.rzone_ghostNP.node()
        scrambled = False
        for node in rzone_ghost.getOverlappingNodes():
            if node.name == 'Block' or node.name == 'Scrambled Block':
                node.name = 'Scrambled Block'
                scrambled = True

        # Rename blocks that are not eligable for reward due to being too late
        for block in self.blocks:
            block_x = block.getPos()[0]
            block_name = block.node().name
            if block_x > 2.4 and block_name == 'Scrambled Block':
                self.have_scramble = False
                scrambled = False
                block.node().name = 'Not Rewardable'

        if scrambled is True:
            self.have_scramble = True
        else:
            if self.have_scramble is True:
                reward = 1
                self.have_scramble = False
        return reward

    def check_teleportable(self, blocks_per_minute):
        self.time = self.framecount / self.fps
        if self.time % (1 / (blocks_per_minute / 60)) < 0.1:
            self.time_to_teleport = True
        else:
            self.time_to_teleport = False
            self.teleport_cooled_down = True
        for block in self.blocks:
            block_x = block.getPos()[0]
            if block_x > 5:
                if block.node().name == 'Scrambled Block':
                    self.have_scramble = False
                block.node().name = 'Teleport Me'
                if self.time_to_teleport is True and self.teleport_cooled_down is True:
                    self.teleport_cooled_down = False
                    block.setX(-4)
                    block.setY(0.0)
                    block.setZ(2.0)
                    block.setHpr(random.uniform(-60, 60), 0.0, 0.0)
                    block.node().name = 'Block'

    def step(self, action):
        dt = 1 / self.fps
        self.framecount += 1
        finger_meters_per_second = 2
        max_dist = 1.1
        real_displacement = finger_meters_per_second * dt
        # Move finger
        if action == 0:
            self.finger_np.setY(self.finger_np.getY() + real_displacement)
            if self.finger_np.getY() > max_dist:
                self.finger_np.setY(max_dist)

        if action == 2:
            self.finger_np.setY(self.finger_np.getY() - real_displacement)
            if self.finger_np.getY() < -max_dist:
                self.finger_np.setY(-max_dist)

        self.world.doPhysics(dt, 5, 1.0 / 120.0)
        self.reset_conv()
        self.check_teleportable(blocks_per_minute=1.1 * 60)

        # Keep the conveyor moving
        self.conv_np.node().setLinearVelocity(Vec3(1.0, 0.0, 0.0))

        if self.render_stuff == True:
            self.graphicsEngine.renderFrame()
        image = self.get_camera_image()
        # image = cv2.resize(image, (84, 84), interpolation=cv2.INTER_CUBIC)

        score = 0
        score += self.check_rewards()
        #score -= self.check_penalty()
        done = False

        return image, score, done
예제 #28
0
class Token():
	
	# Class variables for regular sized token
	R_VALUE = 10
	R_RADIUS = 3
	R_HEIGHT = 6.5
	R_TOKEN_SCALE = (4,4,4)
	
	# Class variables for large token
	L_VALUE = 100
	L_RADIUS = 6
	L_HEIGHT = 15
	L_TOKEN_SCALE = (10,10,10)

	# Model used for token
	MODEL_PATH = 'models/environ/tire/tire.egg'

	'''
	    Constructor creates instance variables for the name and position or the token as well
	    as a reference to the game.
	    @param name - name of the token can either be 'Token' or 'BigToken'
	    @param location - position where the token will be placed
	    @param game - reference to the current game
	'''	
	def __init__(self,name,location,game):
		self.name = name
		(self.x,self.y,self.z) = location
		self.__game = game

		self.collect = base.loader.loadSfx("sfx/coin_collect.wav")
		self.collect.setVolume(.04)	

	
	'''
	    Creates regular token
	'''	
	def create_token(self):
		# Create a cylindrical collision shape
		collisionShape = BulletCylinderShape(Token.R_HEIGHT,Token.R_RADIUS,XUp)

		# Create a ghost node and attach to render
		self.ghostNode = BulletGhostNode(self.name)
		self.ghostNode.addShape(collisionShape)
		self.np = self.__game.render.attachNewNode(self.ghostNode)
			
		self.np.setCollideMask(BitMask32.allOff())
		self.np.setPos(self.x, self.y, self.z)
		self.__game.world.attachGhost(self.ghostNode)

		token = self.__game.loader.loadModel(Token.MODEL_PATH)
		token.setScale((Token.R_TOKEN_SCALE[0],Token.R_TOKEN_SCALE[1],Token.R_TOKEN_SCALE[2]))
                token.setPos(-.5,0,0)

                token.reparentTo(self.np)
		self.__game.e.tokens.append(self)


	'''
	    Create big token for end of stage
	'''
	def create_big_token(self):
		# Create a cylindrical collision shape
		collisionShape = BulletCylinderShape(Token.L_HEIGHT,Token.L_RADIUS,XUp)

		# Create a ghost node and attach to render
		self.ghostNode = BulletGhostNode(self.name)
		self.ghostNode.addShape(collisionShape)
		self.np = self.__game.render.attachNewNode(self.ghostNode)
			
		self.np.setCollideMask(BitMask32.allOff())
		self.np.setPos(self.x, self.y, self.z)
		self.__game.world.attachGhost(self.ghostNode)

		token = self.__game.loader.loadModel(Token.MODEL_PATH)
		token.setScale(Token.L_TOKEN_SCALE[0],Token.L_TOKEN_SCALE[1],Token.L_TOKEN_SCALE[2])
                token.setPos(-.5,0,0)

                token.reparentTo(self.np)
		self.__game.e.tokens.append(self)

    	
	def collected(self):
        	contactResult = self.__game.world.contactTestPair(self.__game.eve.currentControllerNode, self.ghostNode)
        	if len(contactResult.getContacts()) > 0:
			if(self.ghostNode.getName() == 'BigToken'):
				self.__game.levelFinish = True
				self.__game.user.score += Token.L_VALUE
			else:
				self.__game.user.score += Token.L_VALUE
			self.ghostNode.removeChild(0)
			self.__game.world.removeGhost(self.ghostNode)
			self.__game.e.tokens.remove(self)
			self.__game.eve.tiresCollected += 1 
			self.collect.play()

	def spinToken(self):
	        self.np.setH(self.np.getH() + 2)
예제 #29
0
class HGameObject(): #Deprecated
    def __init__(self, name, scene, visualMeshEgg, parent, physicsType, physicsShapeEgg=None, shapeMargin=0.04,
                 animable=False, animationsDict=None, stepHeight=0.5, x=0, y=0, z=0, mass=0, perpixelShading=False):
        """

        :type name: str
        :type scene: HLevel
        :type visualMeshEgg: str
        :type parent: panda3d.core.NodePath
        :type physicsType: int
        :type physicsShapeEgg: str
        :type shapeMargin: float
        :type animable: bool
        :type animationsDict: dict
        :type stepHeight: float
        :type x: float
        :type y: float
        :type z: float
        :type mass: float
        :type perpixelShading: bool
        """
        self.name = name
        self.scene = scene
        if visualMeshEgg is not None:
            if animable:
                if animationsDict is not None:
                    self.vMesh = Actor(visualMeshEgg, animationsDict)
                    self.vMesh.setBlend(frameBlend=True)

                else:
                    self.vMesh = Actor(visualMeshEgg)
                    self.vMesh.setBlend(frameBlend=True)
            else:
                self.vMesh = scene.Base.loader.loadModel(visualMeshEgg)
        else:
            self.vMesh = None
        if physicsType == physicsTypes["character"]:
            print name + " is a character"
            self.shapeModel = self.scene.loadEgg(physicsShapeEgg)
            self.shape = modelToConvex(self.shapeModel)[0]
            self.shape.setMargin(shapeMargin)
            self.body = BulletCharacterControllerNode(self.shape, stepHeight, name)
            self.bodyNP = parent.attachNewNode(self.body)
            if visualMeshEgg is not None:
                self.vMesh.reparentTo(self.bodyNP)
            self.scene.world.attachCharacter(self.body)
            self.bodyNP.setPos(x, y, z)
            self.body.setPythonTag("name", name)
        elif physicsType == physicsTypes["dynamic"]:
            self.shapeModel = self.scene.loadEgg(physicsShapeEgg)
            self.shape = modelToConvex(self.shapeModel)[0]
            self.shape.setMargin(shapeMargin)
            self.body = BulletRigidBodyNode(name)
            self.body.setMass(mass)
            self.body.addShape(self.shape)
            self.bodyNP = parent.attachNewNode(self.body)
            if visualMeshEgg is not None:
                self.vMesh.reparentTo(self.bodyNP)
            self.scene.world.attachRigidBody(self.body)
            self.bodyNP.setPos(x, y, z)
            self.body.setPythonTag("name", name)
        elif physicsType == physicsTypes["ghost"]:
            self.shapeModel = self.scene.loadEgg(physicsShapeEgg)
            self.shape = modelToConvex(self.shapeModel)[0]
            self.shape.setMargin(shapeMargin)
            self.body = BulletGhostNode(name)
            # self.body.setMass(mass)
            self.body.addShape(self.shape)
            self.bodyNP = parent.attachNewNode(self.body)
            if visualMeshEgg is not None:
                self.vMesh.reparentTo(self.bodyNP)
            self.scene.world.attachGhost(self.body)
            self.bodyNP.setPos(x, y, z)
            self.body.setPythonTag("name", name)
        else:
            pass

            # ###3Events
            # self.scene.Base.taskMgr.add(self.onFrame,"onFrame")
        self.shaders = perpixelShading
        if self.vMesh is not None and not self.shaders:
            self.scene.Base.taskMgr.add(self.clearShaderTask, name + "_clearShader")
        # self.scene.Base.taskMgr.add(self._calcVel,self.name+"_calcVelTask")
        self._lastPos = Point3()
        self.velocity = Vec3()

    def _calcVel(self, t):
        if self.scene.pause is False:
            try:
                n = self.bodyNP.getPos()
                self.velocity = (n - self._lastPos) / globalClock.getDt()
                self._lastPos = n
            except:
                # print self.velocity
                pass
        return t.cont

    def clearShaderTask(self, t):
        self.vMesh.clearShader()
        print "Shader clear_", self.name

    def onFrame(self, task):
        pass

    def doRelativeSweepTest(self, relativePoint, BitMask=None, height=0.1):
        globalPoint = self.scene.Base.render.getRelativePoint(self.bodyNP, relativePoint)
        fromT = TransformState.makePos(self.bodyNP.getPos(self.scene.Base.render) + VBase3(0, 0, height))
        toT = TransformState.makePos(globalPoint + VBase3(0, 0, height))
        if BitMask != None:
            r = self.scene.world.sweepTestClosest(self.shape, fromT, toT, BitMask)
        else:
            r = self.scene.world.sweepTestClosest(self.shape, fromT, toT)
        if r.getNode() == self.body:
            return BulletClosestHitSweepResult.empty()
        else:
            return r

    def willCollide(self, relativePoint, bitMask=None, height=0.1):
        r = self.doRelativeSweepTest(relativePoint, bitMask, height)
        if r.getNode() == self.body:
            return False
        else:
            return r.hasHit()

    def doInverseRelativeSweepTest(self, relativePoint, bitMask=None, height=0.1):
        globalPoint = self.scene.Base.render.getRelativePoint(self.bodyNP, relativePoint)
        fromT = TransformState.makePos(self.bodyNP.getPos(self.scene.Base.render) + VBase3(0, 0, height))
        toT = TransformState.makePos(globalPoint + VBase3(0, 0, height))
        if bitMask != None:
            r = self.scene.world.sweepTestClosest(self.shape, toT, fromT, bitMask)
        else:
            r = self.scene.world.sweepTestClosest(self.shape, toT, fromT)
        if r.getNode() == self.body:
            return BulletClosestHitSweepResult.empty()
        else:
            return r

    def inverseWillCollide(self, relativePoint, bitMask=None, height=0.1):
        r = self.doRelativeSweepTest(relativePoint, bitMask, height)
        if r.getNode() == self:
            return False
        else:
            return r.hasHit()

    def destroy(self):
        if "Character" in str(self.body):
            self.scene.world.removeCharacter(self.body)
        elif "Rigid" in str(self.body):
            self.scene.world.removeRigidBody(self.body)
        elif "Ghost" in str(self.body):
            self.scene.world.removeGhost(self.body)
        self.bodyNP.removeNode()
        try:
            self.vMesh.removeNode()
        except:
            pass

    def isOnGround(self):
        r = self.willCollide(Point3(0, 0, -0.1), self.body.getIntoCollideMask(), 0)
        print r
        return r

    def setVelocity(self, v):
        globalV = self.scene.Base.render.getRelativeVector(self.bodyNP, v)
        self.body.setLinearVelocity(globalV)

    def applyForce(self, v):
        globalV = self.scene.Base.render.getRelativeVector(self.bodyNP, v)
        self.body.applyCentralForce(globalV)
예제 #30
0
lightNP.setHpr(180, -20, 0)
lightNP.setPos(0, 10, 10)
lightNP.lookAt(0, 0, 0)
lightNP.node().getLens().setFov(40)
lightNP.node().getLens().setNearFar(10, 100)
#lightNP.node().setShadowCaster(True)
lightNP.node().setShadowCaster(True, 1024, 1024)
# Use a 512x512 resolution shadow map
render.setLight(lightNP)
# Enable the shader generator for the receiving nodes
render.setShaderAuto()

# Delete zone
dzone_shape = BulletBoxShape(Vec3(1, 10, 10))
dzone_ghost = BulletGhostNode('Delete Zone')
dzone_ghost.addShape(dzone_shape)
dzone_ghostNP = render.attachNewNode(dzone_ghost)
dzone_ghostNP.setPos(5.7, 0, 0.0)
dzone_ghostNP.setCollideMask(BitMask32(0x0f))
world.attachGhost(dzone_ghost)

# Penalty zone 1
pzone_shape = BulletBoxShape(Vec3(1, 1, 0.5))
pzone_ghost = BulletGhostNode('Penalty Zone 1')
pzone_ghost.addShape(pzone_shape)
pzone_ghostNP = render.attachNewNode(pzone_ghost)
pzone_ghostNP.setPos(4.2, 0, 0.86)
pzone_ghostNP.setCollideMask(BitMask32(0x0f))
world.attachGhost(pzone_ghost)

# Reward zone
예제 #31
0
class Panel(object):
    def __init__(self, world, x, y, w, h, adir, parent_node):
        self._model = None
        self._initPhysics(world, x, y, w, h, adir, parent_node)
        self._loadModel(x, y, h)
        self._initSound(x, y, h)
        self._broken = False
        self._repair()
        self.resetTime()

        taskMgr.add(self.update, 'panel-task')

    def remove(self):
        if self._model is not None:
            self._model.remove()

    def _loadModel(self, x, y, h):
        self._model_r = loader.loadModel("../data/models/panel_red.egg")
        self._model_g = loader.loadModel("../data/models/panel_green.egg")
        #self._model.setPos(0,0,-h/2)
        self._model_r.reparentTo(self._modulo_node)
        self._model_g.reparentTo(self._modulo_node)

    def _initPhysics(self, world, x, y, w, h, adir, parent_node):
        shape = BulletBoxShape(Vec3(w / 4.0, w / 4.0, h / 4.0))
        self._g_node = BulletGhostNode('Box')
        #self._rb_node.setMass(0)
        self._g_node.addShape(shape)
        #self._rb_node.setAngularFactor(Vec3(0,0,0))
        #self._rb_node.setDeactivationEnabled(False, True)
        world.attachGhost(self._g_node)

        self._modulo_node = parent_node.attachNewNode(self._g_node)
        self._modulo_node.setPos(x, y, h / 2.0)
        self._modulo_node.setHpr(adir, 0, 0)
        self._modulo_node.setPos(self._modulo_node, 0, w / 2.0, 0)

    def _initSound(self, x, y, h):
        audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], camera)
        #base = ShowBase()
        self._sound = audio3d.loadSfx(
            "../data/sounds/A-Tone-His_Self-1266414414.mp3")
        #self._sound.set3dAttributes(x, y, h/2.0,  0, 0, 0)
        audio3d.attachSoundToObject(self._sound, self._modulo_node)
        self._sound.set3dMinDistance(0)
        self._sound.set3dMaxDistance(50)

    def getRBNode(self):
        return self._g_node

    def manipulate(self):
        self._repair()

    def _repair(self):
        self._model_r.hide()
        self._model_g.show()
        self._broken = False

    def _break(self):
        self._model_g.hide()
        self._model_r.show()
        self._broken = True
        self._playSound()

    def isBroken(self):
        return self._broken

    def resetTime(self):
        self._time = random.randint(10, 60)

    def update(self, task):
        if task.frame > 1:
            self._time -= globalClock.getDt()

        if self._time <= 0:
            self.resetTime()
            self._break()

        return task.cont

    def _playSound(self):
        self._sound.play()
        taskMgr.doMethodLater(2, self._soundLoop, 'panel-sound-task')

    def _soundLoop(self, task):
        if not self.isBroken():
            return task.done
        self._sound.play()
        return task.again
예제 #32
0
    def setupItems(self):

        #############Items########################################

        self.iteamsModelsList = [0] * 50
        self.iteamsNodesList = [0] * 50
        self.iteamsNpsList = [0] * 50

        self.index = 0

        for i in range(5):
            x = 4 + i
            y = -20 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 104)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 104)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -4 + i
            y = -42 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 106)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 106)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -25 + i
            y = -42 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 106)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 106)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -25 + i
            y = -64 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 106)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 106)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -22
            y = -120 - (i * 10)
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 108)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 108)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        t1 = loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder1.getX(), self.Cylinder1.getY(),
                  self.Cylinder1.getZ() + 2)
        t1.setHpr(0, 90, 0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder1.getX(), self.Cylinder1.getY(),
                    self.Cylinder1.getZ() + 2)
        npt1.setHpr(0, 90, 0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)

        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1

        self.index += 1

        t1 = loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder2.getX(), self.Cylinder2.getY(),
                  self.Cylinder2.getZ() + 2)
        t1.setHpr(0, 90, 0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder2.getX(), self.Cylinder2.getY(),
                    self.Cylinder2.getZ() + 2)
        npt1.setHpr(0, 90, 0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)

        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1

        self.index += 1

        t1 = loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder3.getX(), self.Cylinder3.getY(),
                  self.Cylinder3.getZ() + 2)
        t1.setHpr(0, 90, 0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder3.getX(), self.Cylinder3.getY(),
                    self.Cylinder3.getZ() + 2)
        npt1.setHpr(0, 90, 0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)

        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1

        self.index += 1
    def setupItems(self):
        
        #############Items########################################
        
        self.iteamsModelsList = [0] * 50
        self.iteamsNodesList = [0] * 50
        self.iteamsNpsList = [0] * 50


        self.index = 0        
            
        n6 = 0
        for i in range(10):
            
            t1= loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(-325,925-(n6*1.2),n6+2)
            t1.setHpr(0,90,0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(-325, 925-(n6*1.2), n6+2)
            npt1.setHpr(0,90,0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)
            
            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1            
            
            n6  += 2
            self.index += 1
            
            
        n7 = 20
        for i in range(5):
            
            t1= loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(-325,880-n7,n6+2)
            t1.setHpr(0,90,0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(-325, 880-n7, n6+2)
            npt1.setHpr(0,90,0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)
            
            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1            
            
            n7  += 20
            self.index += 1
            
   
        t1= loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder1.getX(),self.Cylinder1.getY(),n6+2)
        t1.setHpr(0,90,0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder1.getX(),self.Cylinder1.getY(),n6+2)
        npt1.setHpr(0,90,0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)
            
        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1            
            
        self.index += 1
            
        t1= loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder2.getX(),self.Cylinder2.getY(),n6+2)
        t1.setHpr(0,90,0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder2.getX(),self.Cylinder2.getY(),n6+2)
        npt1.setHpr(0,90,0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)
            
        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1            
            
        self.index += 1
            
            
        t1= loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder3.getX(),self.Cylinder3.getY(),n6+2)
        t1.setHpr(0,90,0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder3.getX(),self.Cylinder3.getY(),n6+2)
        npt1.setHpr(0,90,0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)
            
        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1            
            
        self.index += 1
        

        
            
            
        n6 = 0
        for i in range(30):
            x = random.randint(-50, 50)
            y = random.randint(-50, 50) 
            t1= loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x,y,2)
            t1.setHpr(0,90,0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 2)
            npt1.setHpr(0,90,0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)
            
            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1            
            
            n6  += 2
            self.index += 1
예제 #34
0
class Projectile():
    projectiles = list()
    model = 0
    index = 0
    def __init__(self, ppos, h, p, parent, parentVel, world, worldNP):
        self.world=world
        if Projectile.model==0:
            Projectile.model = Model("../assets/3d/Actors/ball_proj2.egg")
        h = deg2Rad(camera.getH())
        p = deg2Rad(camera.getP())
        dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
        ppos = map(lambda i: ppos[i]+dir[i]*20, range(3))
        self.instance = Projectile.model.createInstance(pos=ppos,hpr=(h,p,0),scale=3)
        
        self.dhpr = [random.random(),random.random(),random.random()]
        
        pmin = LPoint3()
        pmax = LPoint3()
        self.instance.calcTightBounds(pmin,pmax)
        norm = pmin-pmax
        self.off = (norm[0]*.5,norm[1]*.5,norm[2]*.5)
        r = max(norm)
        
        pos = ppos
        
        shape = BulletSphereShape(.5*r)
        self.sphere = BulletGhostNode('ProjectileSphere')
        self.sphere.addShape(shape)
        self.sphere.setDeactivationEnabled(False)
        self.np = worldNP.attachNewNode(self.sphere)
        self.np.setPos(LVecBase3f(ppos[0],ppos[1],ppos[2]))
        self.np.setCollideMask(BitMask32.allOn())
        world.attachGhost(self.sphere)
        
        dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
        self.vel = parentVel
        self.vel = map(lambda i: dir[i]*100, range(3))
        self.index = Projectile.index
        self.parent = parent
        Projectile.index = Projectile.index + 1
        taskMgr.add(self.move,"Proj"+str(Projectile.index)+"MoveTask")
        self.prevTime = 0
        self.lifeTime = 0
        Projectile.projectiles.append(self)
        self.TIMEDLIFE = 120
        self.dead = 0
    def kill(self):
        self.instance.removeNode()
        self.parent.projectiles.remove(self)
        self.world.removeGhost(self.sphere)
        Projectile.projectiles.remove(self)
        self.dead = 1
    def check(self,contacts,human,players):
        if len(contacts)==0:
            return
        contactObject = contacts[0].getNode0()
        if contacts[0].getNode0().getName()=="ProjectileSphere":
            contactObject = contacts[0].getNode1()
        name = contactObject.getName()
        #print name
        if name==human.character.getName():
            human.impact(self.vel)
            self.kill()
            return
        for i in range(len(players)):
            if name==players[i].character.getName():
                players[i].impact(self.vel)
                self.kill()
                return
        return
        
    def move(self,task):
        if self.dead==1:
            return
        dt = task.time-self.prevTime
        #If the projectile exceeds its maximum lifetime or burns out on the arena bounds -
        self.lifeTime += dt
        if(self.lifeTime >= self.TIMEDLIFE):
            #kill projectile
            self.instance.removeNode()
            self.parent.projectiles.remove(self)
            self.world.removeGhost(self.sphere)
            Projectile.projectiles.remove(self)
            return
            #print "Projectile removed"
        if(self.lifeTime < self.TIMEDLIFE):
            #get the position
            pos = self.instance.getPos()
            #get the displacement
            dis = (self.vel[0]*dt,self.vel[1]*dt,self.vel[2]*dt)
            #set the new position
            self.np.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2])
            self.instance.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2])
            
            hpr = self.instance.getHpr()
            hpr = map(lambda i: hpr[i]+dt*100*self.dhpr[i], range(3))
            self.instance.setHpr(hpr[0],hpr[1],hpr[2])
            return task.cont
예제 #35
0
class Eve(Character):
	
	#----- CLASS VARIABLES -----#	
	HEIGHT = 21.00
	WIDTH = 5.0
	INITIAL_HEADING = 90

	MAX_JUMP_HEIGHT = 200.0
	JUMP_SPEED = 70	
	RUNNING_SPEED = 40.0
	INITIAL_ROLL_SPEED = 200.0
	ROLL_ANIM_RATE = 15
	OMEGA = 60.0
	
	#----- CONSTRUCTOR -----#
	def __init__(self,game,render,world,accept,health=100,damage=0):
		super(Eve,self).__init__('Eve',health,damage)
		#----- INSTANCE VARIABLES -----#
		self.state = {'normal': True, 'jumping' : False, 'rolling' : False}
		self.speed = Vec3(0, 0, 0)
        	self.omega = 0.0
		self.tiresCollected = 0
		self.accept = accept
		self.ready = True

		#----- PRIVATE INSTANCE VARIABLES -----#		
		self.__render = render
		self.__world = world
		self.__game = game

		#----- ACTOR SETUP -----#
        	self.actorNP1 = Actor('models/eve/eve.egg', {
                         				    'run' : 'models/eve/eve-run.egg',
                         				    'walk' : 'models/eve/eve-walk.egg',
                         				    'jump' : 'models/eve/eve-jump.egg'})
        	self.actorNP2 = Actor('models/eve/eve-tireroll.egg', {'roll' : 'models/eve/eve-tireroll.egg'})
		self.actorNP1.setPlayRate(2,'walk')
		

		#----- PREPARE SFX -----#
		self.jump = base.loader.loadSfx("sfx/jump.wav")
		self.jump.setVolume(.1)
		self.running = base.loader.loadSfx("sfx/walking.wav")
		self.running.setLoop(True)
		self.running.setPlayRate(1.55)
		self.running.setVolume(.08)
		self.land = base.loader.loadSfx("sfx/land.flac")
		self.land.setLoop(False)
		self.land.setVolume(.05)
		self.roll = base.loader.loadSfx("sfx/rolling.wav")
		self.roll.setLoop(True)
		self.roll.setVolume(.09)
		self.ouch = base.loader.loadSfx("sfx/ouch.wav")
		self.ouch.setLoop(False)
		self.ouch.setVolume(.75)
		self.ouch.setPlayRate(1.25)
		self.throw = base.loader.loadSfx("sfx/throw.wav")
		self.throw.setLoop(False)
		self.throw.setVolume(.75)
		self.blocked = base.loader.loadSfx("sfx/blocked.wav")
		self.blocked.setVolume(.05)
		
		#----- SETUP CONTROL FOR EVE -----#
        	inputState.watchWithModifiers('forward', 'w')
        	inputState.watchWithModifiers('turnLeft', 'a')
        	inputState.watchWithModifiers('turnRight', 'd')	
        	inputState.watchWithModifiers('backwards', 's')	
		

	def render_eve(self,pos):
		self.searchMode(pos,Eve.INITIAL_HEADING)

		# Changing jump animation play rate
		self.currentNode.setPlayRate(1,'jump')
		self.__game.taskMgr.add(self.process_contacts,'attacks')

	def disable_character_controls(self):
		self.accept('m', self.do_nothing)
		self.accept('space', self.do_nothing)
		self.accept('enter',self.do_nothing)

	def enable_character_controls(self):
		self.accept('m', self.toggle_modes)
		self.accept('space', self.doJump)
		self.accept('enter',self.attack)

	def do_nothing(self):
		pass
	
	#------ METHODS USED TO MODIFY JUMP ANIMATION ------#
	def firstPart(self): self.currentNode.play('jump', fromFrame=0)

	def stopInJump(self): 
		self.currentNode.stop()

	def finishJump(self):  
		self.currentNode.play('jump', fromFrame=11)
		self.land.play()
	#self.currentNode.play('jump', fromFrame=self.currentNode.getCurrentFrame('jump'))
	
	def doJump(self):
		if self.currentControllerNode.isOnGround() is True:
			if self.currentState() is 'normal':
				if self.speed.getY() > 0: self.running.stop()
				self.state['jumping'] = True
				self.jump.play()
				self.currentControllerNode.doJump()

				#sequence = Sequence(Func(self.firstPart),Wait(.3),Func(self.stopInJump),Wait(2.95),Func(self.finishJump))
				sequence = Sequence(Func(self.firstPart),Wait(.3),Func(self.stopInJump),Wait(2.95))
				sequence.start()			

	def searchMode(self,location,heading):
		self.state['normal'] = True
		self.state['rolling'] = False
		(self.init_x,self.init_y,self.init_z) = location

		self.__capsule_shape = BulletCapsuleShape(Eve.WIDTH, Eve.HEIGHT - 2 * Eve.WIDTH, ZUp)
		
		# Create bullet character controller
		self.character1= BulletCharacterControllerNode(self.__capsule_shape,0.4,self.name)		
		#self.character1.setMaxJumpHeight(Eve.MAX_JUMP_HEIGHT)
        	self.character1.setJumpSpeed(Eve.JUMP_SPEED)
		self.character1.setGravity(70)

		self.characterNP1 = self.__render.attachNewNode(self.character1)
		self.characterNP1.setPos(self.init_x,self.init_y,self.init_z)
		self.characterNP1.setH(heading)
		self.characterNP1.setCollideMask(BitMask32.allOn())
		self.__world.attachCharacter(self.character1)

        	self.actorNP1.reparentTo(self.characterNP1)
        	self.actorNP1.setScale(4.0)
        	self.actorNP1.setH(180)
        	self.actorNP1.setPos(0,0,-9)

		self.currentNode = self.actorNP1
		self.currentNP = self.characterNP1
		self.currentControllerNode = self.character1

		# Create a cylindrical collision shape
		collisionShape = BulletCylinderShape(6.5,3,XUp)

		# Create a ghost node and attach to render
		self.ghostNode = BulletGhostNode('Weapon')
		self.ghostNode.addShape(collisionShape)
		self.weaponNP = self.__game.render.attachNewNode(self.ghostNode)
			
		self.weaponNP.setCollideMask(BitMask32.allOff())
		self.weaponNP.setPos(self.init_x, self.init_y, self.init_z)
		self.__game.world.attachGhost(self.ghostNode)

		self.weapon = self.__game.loader.loadModel('models/environ/tire/tire.egg')
		self.weapon.setScale(4,4,4)
                self.weapon.setPos(-.5,0,0)

                self.weapon.reparentTo(self.weaponNP)

		self.weapon.hide()

		self.__game.taskMgr.add(self.update_weapon_pos,"weapon")

	def reset(self):
		self.characterNP1.setPos(self.init_x,self.init_y,self.init_z)
		

	def update_weapon_pos(self,task):
		self.weaponNP.setPos(self.characterNP1.getX(),self.characterNP1.getY(), self.characterNP1.getZ() + 5)
		self.weaponNP.setH(self.characterNP1.getH())

		return task.cont

	def attack(self):
		if self.tiresCollected > 0 and self.ready is True: 
			self.throw.play()
			self.weapon.show()

			xpos = 100 * cos((90 - self.characterNP1.getH()) * (pi / 180.0))
			ypos = -100 * sin((90 - self.characterNP1.getH()) * (pi / 180.0))
		
			trajectory = ProjectileInterval(self.weaponNP,
                                    	 startPos = self.weaponNP.getPos(),
                                    	 endPos = Point3(self.weaponNP.getX() - xpos,self.weaponNP.getY() - ypos, self.weaponNP.getZ()-10), duration = .5, gravityMult = 15)
		
			Sequence(Func(self.set_weapon_busy),trajectory,Func(self.weapon.hide),Func(self.set_weapon_ready)).start()
			self.tiresCollected -= 1
		else:
			self.blocked.play()		

	def set_weapon_ready(self):
		self.ready = True
	def set_weapon_busy(self):
		self.ready = False

	def process_contacts(self,task):
		for enemy in self.__game.e.enemies:
			self.check_impact(enemy)
		return task.cont

	def check_impact(self,enemy):
		result = self.__game.world.contactTestPair(self.ghostNode,enemy.np.node())
		if len(result.getContacts()) > 0:
			if self.weapon.isHidden() is False:
				self.weapon.hide()
			if self.ready is False:	
				enemy.take_damage(self.damage)

	def attackMode(self,location,heading):
		self.state['normal'] = False
		self.state['rolling'] = True
		(self.init_x,self.init_y,self.init_z) = location

		self.__cylinder_shape = BulletCylinderShape(Eve.WIDTH + 2, Eve.HEIGHT - 4, XUp)
		
		# Create bullet character controller
		self.character2= BulletCharacterControllerNode(self.__cylinder_shape,0.4,self.name)		

		self.characterNP2 = self.__render.attachNewNode(self.character2)
		self.characterNP2.setPos(self.init_x,self.init_y,self.init_z-2)
		self.characterNP2.setH(heading)
		self.characterNP2.setCollideMask(BitMask32.allOn())
		self.__world.attachCharacter(self.character2)
		self.character2.setGravity(70)

        	self.actorNP2.reparentTo(self.characterNP2)
        	self.actorNP2.setScale(4.0)
        	self.actorNP2.setH(180)
        	self.actorNP2.setPos(0,0,0)

		self.currentNode = self.actorNP2
		self.currentNP = self.characterNP2
		self.currentControllerNode = self.character2

		# Set play rate of the rolling animation		
		self.currentNode.setPlayRate(15,'roll')

	def is_attack_mode(self):
		return self.state['rolling']

	
	def toggle_modes(self):
		if self.is_attack_mode() is False:
			loc = (self.characterNP1.getX(),self.characterNP1.getY(),self.characterNP1.getZ())
			heading = self.characterNP1.getH()
			self.__world.removeCharacter(self.character1)
			self.character1.removeChild(0)
			self.attackMode(loc,heading)
		else:
			loc = (self.characterNP2.getX(),self.characterNP2.getY(),self.characterNP2.getZ())
			heading = self.characterNP2.getH()
			self.__world.removeCharacter(self.character2)
			self.character2.removeChild(0)
			self.searchMode(loc,heading)
		

	def processEveInput(self):
		if self.currentControllerNode.isOnGround() is True:	
			self.speed = Vec3(0, 0, 0)
        		self.omega = 0.0
		
        		if inputState.isSet('forward'):
				if self.state['rolling'] == True:
					self.speed.setY( Eve.INITIAL_ROLL_SPEED)
				else:
					self.speed.setY( Eve.RUNNING_SPEED)
					self.currentNode.setP(15)
        		if inputState.isSet('backwards'):
				if self.state['rolling'] == True:
					self.speed.setY( Eve.INITIAL_ROLL_SPEED - 300)
				else:
					self.speed.setY(-1 * Eve.RUNNING_SPEED - 10)
        		if inputState.isSet('turnLeft'):
				self.omega = Eve.OMEGA
				if self.speed.getY() == 0:
					self.currentNode.setR(0)
				else:
					self.currentNode.setR(15)
        		if inputState.isSet('turnRight'): 
				self.omega = Eve.OMEGA * -1 
				if self.speed.getY() == 0:
					self.currentNode.setR(0)
				else:
					self.currentNode.setR(-15)
        	self.currentControllerNode.setAngularMovement(self.omega)

		if self.currentControllerNode.isOnGround() is False:
        		self.currentControllerNode.setAngularMovement(0.0)
			self.currentControllerNode.setLinearMovement(self.speed, True)
			self.currentNode.setR(0)

		if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() == 'jump':
			self.currentNode.setR(0)
			self.currentControllerNode.setAngularMovement(0.0)
        		self.currentControllerNode.setLinearMovement(0.0, True)

		if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump':
			self.currentControllerNode.setAngularMovement(self.omega)
        		self.currentControllerNode.setLinearMovement(self.speed, True)
        		

	def currentState(self):
		if self.state['rolling'] is True:
			return 'rolling'
		else:
			return 'normal'

	def updateEveAnim(self):
		self.processEveInput()
		if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump':	
			if self.speed.getY() > 0:
				if self.omega == 0.0:	self.currentNode.setR(0)
				if self.currentState() is 'rolling':
					if self.running.status() == self.running.PLAYING: self.running.stop()
					if self.roll.status() != self.roll.PLAYING: self.roll.play()
					if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll')	
				elif self.currentState() is 'normal':	
					if self.roll.status() == self.roll.PLAYING: self.roll.stop()
					if self.running.status() != self.running.PLAYING: self.running.play()
					if self.currentNode.getCurrentAnim() != 'run': self.currentNode.loop('run')	
			elif self.speed.getY() < 0:
				if self.currentState() is 'rolling':
					if self.running.status() == self.running.PLAYING: self.running.stop()
					if self.roll.status() != self.roll.PLAYING: self.roll.play()
					if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll')	
				elif self.currentState() is 'normal':	
					if self.roll.status() == self.roll.PLAYING: self.roll.stop()
					if self.running.status() != self.running.PLAYING: self.running.play()
					if self.currentNode.getCurrentAnim() != 'walk': self.currentNode.loop('walk')
			else:	
				if self.omega != 0:
					if self.currentState() is 'rolling':		
						if self.currentNode.getCurrentAnim() != 'roll': self.currentNode.loop('roll')
					elif self.currentState() is 'normal':
						if self.currentNode.getCurrentAnim() != 'walk': 
							self.actorNP1.setPlayRate(1,'walk')
							self.currentNode.loop('walk')
				else:
					self.currentNode.stop(self.currentNode.getCurrentAnim())
					self.actorNP1.setPlayRate(2,'walk')
					self.currentNode.setP(0)
					self.currentNode.setR(0)
					if self.running.status() == self.running.PLAYING: self.running.stop()
					if self.roll.status() == self.roll.PLAYING: self.roll.stop()
					if self.state['rolling'] is True:
						frame = self.currentNode.getCurrentFrame('roll')
						if frame is None: frame = 0
						else: frame = self.currentNode.getCurrentFrame('roll')
						self.currentNode.pose('roll',frame) 			
					elif self.state['normal'] is True:
						self.currentNode.pose('walk',5) 
		elif self.currentControllerNode.isOnGround() is False and self.state['jumping'] is False:
			self.currentNode.pose('jump',7)
			

	def take_damage(self,damage):
		self.ouch.play()
		color_scale_interval1 = LerpColorScaleInterval(self.currentNode, .5, (1,0,0,.1), (1,0,0,0))
		Sequence(color_scale_interval1,Wait(.005),Func(self.currentNode.clearColorScale)).start()
		self.health -= damage
예제 #36
0
class Models2(object):
    def __init__(self):

        self.setup()

        self.angel = 1

        # Set up the environment
        #

        self.sky = loader.loadModel("models/solar_sky_sphere")
        self.sky.reparentTo(render)
        self.sky.setScale(10000)
        self.sky.setPos(0, 0, 0)
        self.sky_tex = loader.loadTexture("models/stars_1k_tex.jpg")
        self.sky.setTexture(self.sky_tex, 1)

    def setup(self):

        #World
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -9.81))

        #Ground
        shape = BulletPlaneShape(Vec3(0, 0, 1), 1)
        self.ground = BulletRigidBodyNode('Ground')
        self.ground.addShape(shape)
        self.groundNp = render.attachNewNode(self.ground)
        self.groundNp.setPos(0, 0, 0)
        self.groundNp.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.ground)

        #build
        self.shape1 = BulletBoxShape(Vec3(8, 8, 0.75))
        self.node1 = BulletRigidBodyNode('Box1')
        self.node1.setMass(0)
        self.node1.addShape(self.shape1)
        self.np1 = render.attachNewNode(self.node1)
        self.np1.setPos(0, 0, 100)
        self.np1.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node1)
        self.box1 = loader.loadModel("models/box/box1")
        self.box1.reparentTo(render)
        self.box1.setScale(10, 10, 0.2)
        self.box1.setPos(0, 0, 100)

        self.shape2 = BulletBoxShape(Vec3(8, 8, 0.75))
        self.node2 = BulletRigidBodyNode('Box2')
        self.node2.setMass(0)
        self.node2.addShape(self.shape2)
        self.np2 = render.attachNewNode(self.node2)
        self.np2.setPos(5, -22, 102)
        self.np2.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node2)
        self.box2 = loader.loadModel("models/box/box1")
        self.box2.reparentTo(render)
        self.box2.setScale(10, 10, 0.2)
        self.box2.setPos(5, -22, 102)

        self.shape3 = BulletBoxShape(Vec3(8, 8, 0.75))
        self.node3 = BulletRigidBodyNode('Box3')
        self.node3.setMass(0)
        self.node3.addShape(self.shape3)
        self.np3 = render.attachNewNode(self.node3)
        self.np3.setPos(-5, -44, 104)
        self.np3.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node3)
        self.box3 = loader.loadModel("models/box/box1")
        self.box3.reparentTo(render)
        self.box3.setScale(10, 10, 0.2)
        self.box3.setPos(-5, -44, 104)

        self.shape4 = BulletBoxShape(Vec3(8, 8, 0.75))
        self.node4 = BulletRigidBodyNode('Box4')
        self.node4.setMass(0)
        self.node4.addShape(self.shape4)
        self.np4 = render.attachNewNode(self.node4)
        self.np4.setPos(-27, -44, 104)
        self.np4.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node4)
        self.box4 = loader.loadModel("models/box/box1")
        self.box4.reparentTo(render)
        self.box4.setScale(10, 10, 0.2)
        self.box4.setPos(-27, -44, 104)

        self.shape5 = BulletBoxShape(Vec3(8, 8, 0.75))
        self.node5 = BulletRigidBodyNode('Box5')
        self.node5.setMass(0)
        self.node5.addShape(self.shape5)
        self.np5 = render.attachNewNode(self.node5)
        self.np5.setPos(-27, -66, 104)
        self.np5.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node5)
        self.box5 = loader.loadModel("models/box/box1")
        self.box5.reparentTo(render)
        self.box5.setScale(10, 10, 0.2)
        self.box5.setPos(-27, -66, 104)

        self.box6 = loader.loadModel("models/box/box1")
        self.box6.reparentTo(render)
        self.box6.setScale(10, 87, 0.2)
        self.box6.setPos(-22, -150, 106)
        self.shape6 = BulletBoxShape(Vec3(8, 70, 0.75))
        self.node6 = BulletRigidBodyNode('Box6')
        self.node6.setMass(0)
        self.node6.addShape(self.shape6)
        self.np6 = render.attachNewNode(self.node6)
        self.np6.setPos(-22, -150, 106)
        self.np6.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node6)

        blocks_tex6 = loader.loadTexture("models/blocks_tex6.jpg")

        self.Cylinder1 = loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder1.reparentTo(render)
        self.Cylinder1.setScale(8, 8, 0.2)
        self.Cylinder1.setPos(-22, -230, 108)
        self.Cylinder1.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape16 = BulletCylinderShape(radius, height, ZUp)
        self.node16 = BulletRigidBodyNode('Cylinder1')
        self.node16.setMass(0)
        self.node16.addShape(shape16)
        self.np16 = render.attachNewNode(self.node16)
        self.np16.setPos(-22, -230, 108)
        self.np16.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node16)

        self.Cylinder2 = loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder2.reparentTo(render)
        self.Cylinder2.setScale(8, 8, 0.2)
        self.Cylinder2.setPos(-15, -250, 110)
        self.Cylinder2.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape17 = BulletCylinderShape(radius, height, ZUp)
        self.node17 = BulletRigidBodyNode('Cylinder2')
        self.node17.setMass(0)
        self.node17.addShape(shape17)
        self.np17 = render.attachNewNode(self.node17)
        self.np17.setPos(-15, -250, 110)
        self.np17.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node17)

        self.Cylinder3 = loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder3.reparentTo(render)
        self.Cylinder3.setScale(8, 8, 0.2)
        self.Cylinder3.setPos(-25, -270, 112)
        self.Cylinder3.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape18 = BulletCylinderShape(radius, height, ZUp)
        self.node18 = BulletRigidBodyNode('Cylinder3')
        self.node18.setMass(0)
        self.node18.addShape(shape18)
        self.np18 = render.attachNewNode(self.node18)
        self.np18.setPos(-25, -270, 112)
        self.np18.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node18)

        self.Cylinder4 = loader.loadModel("models/Cylinder/Cylinder")
        self.Cylinder4.reparentTo(render)
        self.Cylinder4.setScale(8, 8, 0.2)
        self.Cylinder4.setPos(-30, -290, 114)
        self.Cylinder4.setTexture(blocks_tex6, 1)
        radius = 8
        height = 1
        shape19 = BulletCylinderShape(radius, height, ZUp)
        self.node19 = BulletRigidBodyNode('Cylinder4')
        self.node19.setMass(0)
        self.node19.addShape(shape19)
        self.np19 = render.attachNewNode(self.node19)
        self.np19.setPos(-30, -290, 114)
        self.np19.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node19)

        self.fire = loader.loadModel("models/stop_sign/stop_sign")
        self.fire.setScale(0.01)
        self.fire.reparentTo(render)
        self.fire.setPos(-30, -290, 114 + 6)

        self.shape7 = BulletBoxShape(Vec3(8, 8, 0.75))
        self.node7 = BulletRigidBodyNode('Box7')
        self.node7.setMass(0)
        self.node7.addShape(self.shape7)
        self.np7 = render.attachNewNode(self.node7)
        self.np7.setPos(0, 0, 200)
        self.np7.setCollideMask(BitMask32.allOn())
        self.world.attachRigidBody(self.node7)
        self.box7 = loader.loadModel("models/box/box1")
        self.box7.reparentTo(render)
        self.box7.setScale(10, 10, 0.2)
        self.box7.setPos(0, 0, 200)

        #setup the items to be collected
        self.setupItems()
        self.setupEndPoint()

    def setupEndPoint(self):

        blocks_tex8 = loader.loadTexture("models/blocks_tex8.jpg")

        self.endpoint = loader.loadModel(
            "models/Sphere_HighPoly/Sphere_HighPoly")
        self.endpoint.reparentTo(render)
        self.endpoint.setScale(.5)
        self.endpoint.setPos(0, 0, 202)
        self.endpoint.setTexture(blocks_tex8, 1)
        radius = 2.65
        self.shapeEnd = BulletSphereShape(radius)
        self.nodeEnd = BulletGhostNode('EndPoint')
        self.nodeEnd.addShape(self.shapeEnd)
        self.npEnd = render.attachNewNode(self.nodeEnd)
        self.npEnd.setPos(0, 5, 202)
        self.npEnd.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(self.nodeEnd)

    def setupItems(self):

        #############Items########################################

        self.iteamsModelsList = [0] * 50
        self.iteamsNodesList = [0] * 50
        self.iteamsNpsList = [0] * 50

        self.index = 0

        for i in range(5):
            x = 4 + i
            y = -20 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 104)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 104)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -4 + i
            y = -42 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 106)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 106)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -25 + i
            y = -42 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 106)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 106)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -25 + i
            y = -64 + i
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 106)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 106)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        for i in range(5):
            x = -22
            y = -120 - (i * 10)
            t1 = loader.loadModel("models/Torus/Torus")
            t1.reparentTo(render)
            t1.setScale(.6)
            t1.setPos(x, y, 108)
            t1.setHpr(0, 90, 0)
            radius = .8
            height = .5
            shape19 = BulletCylinderShape(radius, height, ZUp)
            nodet1 = BulletGhostNode('t1')
            nodet1.addShape(shape19)
            npt1 = render.attachNewNode(nodet1)
            npt1.setPos(x, y, 108)
            npt1.setHpr(0, 90, 0)
            npt1.setCollideMask(BitMask32.allOn())
            self.world.attachGhost(nodet1)

            self.iteamsModelsList[self.index] = t1
            self.iteamsNodesList[self.index] = nodet1
            self.iteamsNpsList[self.index] = npt1

            self.index += 1

        t1 = loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder1.getX(), self.Cylinder1.getY(),
                  self.Cylinder1.getZ() + 2)
        t1.setHpr(0, 90, 0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder1.getX(), self.Cylinder1.getY(),
                    self.Cylinder1.getZ() + 2)
        npt1.setHpr(0, 90, 0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)

        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1

        self.index += 1

        t1 = loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder2.getX(), self.Cylinder2.getY(),
                  self.Cylinder2.getZ() + 2)
        t1.setHpr(0, 90, 0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder2.getX(), self.Cylinder2.getY(),
                    self.Cylinder2.getZ() + 2)
        npt1.setHpr(0, 90, 0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)

        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1

        self.index += 1

        t1 = loader.loadModel("models/Torus/Torus")
        t1.reparentTo(render)
        t1.setScale(.6)
        t1.setPos(self.Cylinder3.getX(), self.Cylinder3.getY(),
                  self.Cylinder3.getZ() + 2)
        t1.setHpr(0, 90, 0)
        radius = .8
        height = .5
        shape19 = BulletCylinderShape(radius, height, ZUp)
        nodet1 = BulletGhostNode('t1')
        nodet1.addShape(shape19)
        npt1 = render.attachNewNode(nodet1)
        npt1.setPos(self.Cylinder3.getX(), self.Cylinder3.getY(),
                    self.Cylinder3.getZ() + 2)
        npt1.setHpr(0, 90, 0)
        npt1.setCollideMask(BitMask32.allOn())
        self.world.attachGhost(nodet1)

        self.iteamsModelsList[self.index] = t1
        self.iteamsNodesList[self.index] = nodet1
        self.iteamsNpsList[self.index] = npt1

        self.index += 1