예제 #1
0
 def __init__(self, base, name, speed, scale, color, mask, relA, xyz, relB, lookat, life):
     an = ActorNode()
     self.anp = base.render.attachNewNode(an)
     base.physicsMgr.attachPhysicalNode(an)
     self.anpo = an.getPhysicsObject()
     fn = ForceNode("force-missile")
     self.anp.attachNewNode(fn)
     bft = LinearVectorForce(Vec3(0, 1, 0)*speed)
     fn.addForce(bft)
     an.getPhysical(0).addLinearForce(bft)
     missile = base.loader.loadModel("./mdl/missile.egg")
     missile.setColor(color)
     missile.setScale(scale)
     missile.reparentTo(self.anp)
     missile.setTag(name, '1')
     missile_from_obj = missile.attachNewNode(CollisionNode(name))
     missile_from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1))
     missile_from_obj.node().setFromCollideMask(mask)
     missile_from_obj.setCollideMask(mask)
     base.pusher.addCollider(missile_from_obj, self.anp)
     base.cTrav.addCollider(missile_from_obj, base.pusher)
     self.anp.setPos(relA, xyz)
     self.anp.lookAt(relB, lookat)
     # light the missile
     mlight = DirectionalLight('mlight')
     mlight.setColor(VBase4(1., 1., 1., 1))
     mlnp = base.render.attachNewNode(mlight)
     mlnp.setHpr(self.anp.getHpr())
     self.anp.setLightOff()
     self.anp.setLight(mlnp)
     # remove the missile
     base.taskMgr.doMethodLater(life, self.remove_missile, 'task-remove-missile', extraArgs=[self.anp], appendTask=True)
예제 #2
0
class Zombie:
    def __init__(self,zombie,app,i=0):
        self.app = app
        self.zombie = zombie
        self.zombie.setPythonTag('health',10+30*self.app.level)
        self.zombie.setTag('zombie','1')
        self.zombie.setPythonTag('dead',False)
        self.zombie.setScale(0.5,0.5,0.5)
        self.zombie.setX(-40)
        self.zombie.setY(-i*10)
        self.zombie.setZ(20)
        self.zombie.loop("walk")
        self.zombie.reparentTo(self.app.render)
        #Collision detection
        self.create_collider()
        
    def addPhy(self):
        self.zombieAN = ActorNode("ZombieActor")
        self.zombieActorPhysicsP = self.app.phy.attachNewNode(self.zombieAN)
        
        self.app.physicsMgr.attachPhysicalNode(self.zombieAN)
        self.zombie.reparentTo(self.zombieActorPhysicsP)
        self.zombieAN.getPhysicsObject().setMass(150)
    def create_collider(self):
        self.addPhy()
        
        #walker this has been commented because two collision detectors per panda were decreasing the fps
        #self.collision_sphere = CollisionSphere(0,0,2,2)
        #self.cnodePath = self.zombie.attachNewNode(CollisionNode('zombieWalker'))
        #self.cnodePath.node().addSolid(self.collision_sphere)
        #self.cnodePath.show()
        
        #body
        #self.zombie_body = CollisionSphere(0,0,10,4)
        self.zombie_body = CollisionSphere(0,0,7,7)
        self.zombie_body_NP = self.zombie.attachNewNode(CollisionNode('zombieBody'))
        self.zombie_body_NP.node().addSolid(self.zombie_body)
        #self.zombie_body_NP.show()
        
        #self.app.pusher.addCollider(self.cnodePath,self.zombieActorPhysicsP)
        self.app.pusher.addCollider(self.zombie_body_NP,self.zombieActorPhysicsP)
        #self.app.cTrav.addCollider(self.cnodePath,self.app.pusher)
        self.app.cTrav.addCollider(self.zombie_body_NP,self.app.pusher)
        
    
    def meelee(self):
        point = self.app.pandaActor.getRelativePoint(self.zombie,Point3(0,0,0))
        dist = point.getX()**2 + point.getY()**2 + point.getZ()**2
        if dist < 300:
            self.app.kicked.play()
            self.zombieAN.getPhysicsObject().setVelocity(self.app.render.getRelativeVector(self.app.pandaActor,Vec3(0,-30,0)))
            self.zombie.setPythonTag('health',self.zombie.getPythonTag('health')-10)
            if self.zombie.getPythonTag('health') <= 0 and self.zombie.getPythonTag('dead') <> True:
                self.zombie.setPythonTag('dead',True)
                self.app.panda_kill_count += 1
                self.app.zombie_die.play()
예제 #3
0
	def __init__(self, name):
		self.name = name
		self.cell_x = 0
		self.cell_y = 0
		self.vel = LPoint3(0, 0, 0)

		self.c_node = base.render.attachNewNode(
			self.name+"_camera_node")


		self.panda_actor = Actor("models/panda-model", {"walk": "models/panda-walk4"})
		self.panda_actor.setScale(0.05, 0.05, 0.05)

		self.p_node = NodePath(self.name+"_phys_node")
		self.p_node.reparentTo(render)

		self.an = ActorNode("panda-phys")
		self.anp = self.p_node.attachNewNode(self.an)
		base.enableParticles()
		base.physicsMgr.attachPhysicalNode(self.an)
		self.panda_actor.reparentTo(self.anp)

		gravityFN=ForceNode('world-forces')
		gravityFNP=render.attachNewNode(gravityFN)
		#gravityForce=LinearVectorForce(0,0,-9.81) #gravity acceleration
		self.gravityForce=LinearVectorForce(0,0,-9.81)
		gravityFN.addForce(self.gravityForce)

		base.physicsMgr.addLinearForce(self.gravityForce)


		self.c_node.reparentTo(self.panda_actor)
		self.c_node.setCompass()
		#self.panda_actor.reparentTo(base.render)
		base.camera.reparentTo(self.c_node)

		self.box = loader.loadModel("box.egg")
		self.box.setScale(100, 100, 100)
		self.box.setPos(-180, 0, 0)
		self.boxc = self.box.find("**/Cube")
		self.boxc.node().setIntoCollideMask(BitMask32.bit(0))
		self.boxc.node().setFromCollideMask(BitMask32.allOff())

		self.ban = ActorNode("box-phys")
		base.physicsMgr.attachPhysicalNode(self.ban)

		self.bp_node = NodePath(self.name+"_phys_node2")
		self.bp_node.reparentTo(render)

		self.banp = self.bp_node.attachNewNode(self.ban)
		self.box.reparentTo(self.banp)

		self.boxc.show()
 def setupPhysics(self, name):
     an = ActorNode('%s-%s' % (name, self.doId))
     anp = NodePath(an)
     if not self.isEmpty():
         self.reparentTo(anp)
     NodePath.assign(self, anp)
     self.physicsObject = an.getPhysicsObject()
     self.setTag('object', str(self.doId))
     self.collisionNodePath.reparentTo(self)
     self.handler = PhysicsCollisionHandler()
     self.handler.addCollider(self.collisionNodePath, self)
     self.collideName = self.uniqueName('collide')
     self.handler.addInPattern(self.collideName + '-%in')
     self.handler.addAgainPattern(self.collideName + '-%in')
     self.watchDriftName = self.uniqueName('watchDrift')
예제 #5
0
 def addPhy(self):
     self.zombieAN = ActorNode("ZombieActor")
     self.zombieActorPhysicsP = self.app.phy.attachNewNode(self.zombieAN)
     
     self.app.physicsMgr.attachPhysicalNode(self.zombieAN)
     self.zombie.reparentTo(self.zombieActorPhysicsP)
     self.zombieAN.getPhysicsObject().setMass(150)
예제 #6
0
def phyball_dispenser(modelname, scale=1.):
    # first off we gotta define the topmost node that should be a PandaNode wrapped into a nodepath - this is mandatory cos if we try to directly use the  Actornode defined below, we'll face inexpected behavior manipulating the object.
    ballNP = NodePath(PandaNode("phisicsball"))
    # we then need an ActorNode - this is required when playing with physics cos it got an interface suitable for this
    #  task while the usual nodepath ain't. Then we'll stick it to the main nodepath we'll put into the scene render node, wrapped into a nodepath of course.
    ballAN = ActorNode("ballactnode")
    ballANP = ballNP.attachNewNode(ballAN)
    ballmodel = loader.loadModel(modelname)
    ballmodel.reparentTo(ballANP)
    ballmodel.setScale(scale)

    # as usual we need to provide a sphere collision node for our object. Note that the sphere collider is the only solid allowed to act either as FROM and  INTO object.
    ballCollider = ballANP.attachNewNode(CollisionNode('ballcnode'))
    ballCollider.node().addSolid(CollisionSphere(0, 0, 0, 1 * scale))
    # now it's a good time to dip our object into the physics environment (the Actornode btw)
    base.physicsMgr.attachPhysicalNode(ballAN)
    # then tell to the PhysicsCollisionHandler what are its collider and main nodepath to handle -
    # this means that the ballANP nodepath will be phisically moved to react to all the physics forces we applied in the environment (the gravity force in the specific).
    # Note that due we are using a particular collison handler (PhysicsCollisionHandler) we cannot pass a common nodepath as we did in all the previous steps but a nodepath-wrapped Actornode.
    collisionHandler.addCollider(ballCollider, ballANP)
    # and inform the main traverser as well
    base.cTrav.addCollider(ballCollider, collisionHandler)
    # now the physic ball is ready to exit off the dispenser - Note we reparent it to render by default
    ballNP.reparentTo(base.render)
    return ballNP
예제 #7
0
    def __init__(self, playerID, color=LPoint3f(0,0,0)):
        self.color = color
        self.playerID = playerID

        self.bulletNP = NodePath("Bullet-%d" % id(self))
        self.bulletAN = ActorNode("bullet-physics-%d" % id(self))
        # set the mass of the ball to 3.3g = average weight of a paintball
        self.bulletAN.getPhysicsObject().setMass(0.033)
        self.bulletANP = self.bulletNP.attachNewNode(self.bulletAN)
        base.physicsMgr.attachPhysicalNode(self.bulletAN)
        self.bullet = loader.loadModel("Bullet")
        self.bullet.setScale(2)
        self.bullet.setColorScale(
            self.color.getX(),
            self.color.getY(),
            self.color.getZ(),
            1.0)
        self.bullet.reparentTo(self.bulletANP)

        # setup the collision detection
        # 17.3 mm (0.0173) = size of a .68cal paintball
        self.bulletColName = "bulletCollision-%02d" % id(self)
        self.bulletSphere = CollisionSphere(0, 0, 0, 0.0173*2)
        self.bulletCollision = self.bulletANP.attachNewNode(CollisionNode(self.bulletColName))
        self.bulletCollision.node().addSolid(self.bulletSphere)
        #self.bulletCollision.show()
        base.physicpusher.addCollider(self.bulletCollision, self.bulletANP)
        base.cTrav.addCollider(self.bulletCollision, base.physicpusher)
예제 #8
0
 def ship(self):
     an = ActorNode()
     an.getPhysicsObject().setMass(100)
     self.fighter = self.render.attachNewNode(an)
     self.physicsMgr.attachPhysicalNode(an)
     self.anpo = an.getPhysicsObject()
     fn = ForceNode("force-node-fighter")
     self.fighter.attachNewNode(fn)
     self.pft = LinearVectorForce(Vec3(0, +1, 0) * 500)  # forward thrust
     self.prt = LinearVectorForce(Vec3(0, -1, 0) * 500)  # reverse thrust
     self.pft.setMassDependent(1)
     self.prt.setMassDependent(1)
     self.pft.setActive(False)
     self.prt.setActive(False)
     fn.addForce(self.pft)
     fn.addForce(self.prt)
     an.getPhysical(0).addLinearForce(self.pft)
     an.getPhysical(0).addLinearForce(self.prt)
     self.camera.reparentTo(self.fighter)
     from_obj = self.fighter.attachNewNode(CollisionNode('fighter'))
     from_obj.node().setFromCollideMask(BitMask32(0x1))
     from_obj.setCollideMask(BitMask32(0x1))
     from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1))
     # from_obj.show()
     self.pusher.addCollider(from_obj, self.fighter)
     self.cTrav.addCollider(from_obj, self.pusher)
예제 #9
0
 def __init__(self, base, name, speed, scale, color, mask, relA, xyz, relB,
              lookat, life):
     an = ActorNode()
     self.anp = base.render.attachNewNode(an)
     base.physicsMgr.attachPhysicalNode(an)
     self.anpo = an.getPhysicsObject()
     fn = ForceNode("force-missile")
     self.anp.attachNewNode(fn)
     bft = LinearVectorForce(Vec3(0, 1, 0) * speed)
     fn.addForce(bft)
     an.getPhysical(0).addLinearForce(bft)
     missile = base.loader.loadModel("./mdl/missile.egg")
     missile.setColor(color)
     missile.setScale(scale)
     missile.reparentTo(self.anp)
     missile.setTag(name, '1')
     missile_from_obj = missile.attachNewNode(CollisionNode(name))
     missile_from_obj.node().addSolid(CollisionSphere(0, 0, 0, 1))
     missile_from_obj.node().setFromCollideMask(mask)
     missile_from_obj.setCollideMask(mask)
     base.pusher.addCollider(missile_from_obj, self.anp)
     base.cTrav.addCollider(missile_from_obj, base.pusher)
     self.anp.setPos(relA, xyz)
     self.anp.lookAt(relB, lookat)
     # light the missile
     mlight = DirectionalLight('mlight')
     mlight.setColor(VBase4(1., 1., 1., 1))
     mlnp = base.render.attachNewNode(mlight)
     mlnp.setHpr(self.anp.getHpr())
     self.anp.setLightOff()
     self.anp.setLight(mlnp)
     # remove the missile
     base.taskMgr.doMethodLater(life,
                                self.remove_missile,
                                'task-remove-missile',
                                extraArgs=[self.anp],
                                appendTask=True)
예제 #10
0
 def enliven_ball(self, ball):
     # create an actor node for the balls
     ball_actor = self.base.render.attachNewNode(
         ActorNode("ball_actor_node"))
     # choose a random color
     #ball_actor.setColor(random.random(), random.random(), random.random(), random.random())
     self.create_ball_coll(ball_actor)
     # apply forces to it
     self.base.physicsMgr.attachPhysicalNode(ball_actor.node())
     #spurt_force = LinearVectorForce(0.0, 0.0, self.force_mag)
     #spurt_force.setMassDependent(True)
     #self.spurt.addForce(spurt_force)
     #self.spurt.addForce()
     self.apply_spurt(ball_actor.node())
     ball.reparentTo(ball_actor)
     self.ball_actors.append(ball_actor)
예제 #11
0
 def __init__(self, name, geom=None):
     an = ActorNode('flyingGagAN')
     NodePath.__init__(self, an)
     self.actorNode = an
     self.gag = None
     self.gagNode = None
     ShadowCaster.__init__(self, False)
     if geom:
         self.gagNode = self.attachNewNode('PieNode')
         self.gag = geom.copyTo(self.gagNode)
         self.gag.setScale(3)
         self.gagNode.setHpr(0, -45, 0)
         self.gagNode.setPos(0, 0, 2)
         self.initializeDropShadow()
         self.setActiveShadow()
         self.dropShadow.setPos(0, 0, 2)
         self.dropShadow.setScale(3)
     return
예제 #12
0
 def __init__(self):
     NodePath.__init__(self)
     an = ActorNode('vehicle-test')
     anp = NodePath(an)
     NodePath.assign(self, anp)
     self.actorNode = an
     ShadowCaster.ShadowCaster.__init__(self, False)
     Kart.index += 1
     self.updateFields = []
     self.kartDNA = [-1] * getNumFields()
     self.kartAccessories = {
         KartDNA.ebType: None,
         KartDNA.spType: None,
         KartDNA.fwwType: (None, None),
         KartDNA.bwwType: (None, None)
     }
     self.texCount = 1
     return
예제 #13
0
    def make_actor_collisions(self, actor):
        pcol = CollisionSphere(0, 400)
        self.collision_node = actor.attachNewNode(CollisionNode('pcol'))
        self.collision_node.node().addSolid(pcol)
        self.collision_node.show()
        #self.collision_node.setHpr(0, 90, 0)
        #self.collision_node.setPos(0, 0, 0)

        self.ray = CollisionRay(LPoint3(0, 0, -500), LVector3f(0, 0, -90))
        self.ray_node = self.char.c_node.attachNewNode(CollisionNode('pray'))
        self.ray_node.reparentTo(self.char.c_node)
        self.ray_node.node().addSolid(self.ray)
        self.ray_node.show()
        self.accept('into-pray', self.hanev)
        self.accept('Cube-again-pray', self.hanev)
        self.accept('pray-again-planecnode', self.hanev)
        self.accept('out-pray', self.hanev)
        #base.cTrav.addCollider(self.ray_node, base.mchandler)
        #base.mchandler.addCollider(self.ray_node, self.ray_node)

        self.accept('into-pcol', self.hanev)
        self.accept('Cube-again-pcol', self.hanev)
        self.accept('pcol-again-Cube', self.hanev)
        self.accept('out-pcol', self.hanev)

        self.accept('into-Cube', self.hanev)
        self.accept('again-Cube', self.hanev)
        a_pcol = ActorNode("a_pcol")
        np_pcol = self.collision_node.attachNewNode(a_pcol)
        base.physicsMgr.attachPhysicalNode(a_pcol)
        base.cTrav.addCollider(np_pcol, base.mchandler)

        base.mchandler.addCollider(self.collision_node, np_pcol)
        base.cTrav.addCollider(self.collision_node, base.mchandler)

        self.char.an.getPhysicsObject().setTerminalVelocity(0.00000001)
        self.char.an.getPhysicsObject().setOriented(True)
        self.boo = 0
예제 #14
0
 def create_bullet(self):
     self.bullet = self.loader.loadModel('models/gun/bullet')
     self.gunshot.play()
     self.bulletAN = ActorNode("BulletNode")
     self.bulletActorPhysicsP = self.phy.attachNewNode(self.bulletAN)
     
     self.physicsMgr.attachPhysicalNode(self.bulletAN)
     self.bullet.reparentTo(self.bulletActorPhysicsP)
     self.bulletAN.getPhysicsObject().setMass(1)
     self.bullet.setPos(self.pandaActor,0,-3,3.5)
     self.bullet.setScale(0.1,0.1,0.1)
     self.bullet.setHpr(self.pandaActor,0,90,0)
     self.bullet.setP(self.camera.getP()+90)
     self.bullet_sphere = CollisionSphere(0,0,0,0.2)
     self.bullet_collNode = CollisionNode('bullet')
     self.bullet_cnodePath = self.bullet.attachNewNode(self.bullet_collNode)
     self.bullet_cnodePath.node().addSolid(self.bullet_sphere)
     
     #self.pusher.addCollider(self.bullet_cnodePath,self.bulletActorPhysicsP)
     self.cTrav.addCollider(self.bullet_cnodePath,self.collisionHandler)
     
     #self.bullet_cnodePath.show()
     self.bullets += [self.bullet]
예제 #15
0
    def createBarrel(self):

        barrelNode = NodePath("PhysicalBarrel")
        barrelNode.reparentTo(self.scene)
        barrelNode.setPos(self.scene, 0,0,0)
        physicsBarrel = ActorNode("physics_barrel")
        physicsBarrel.getPhysicsObject().setMass(0.01) #in what units? (69 kindda 3 lbs)
        barrel = barrelNode.attachNewNode(physicsBarrel)
        base.physicsMgr.attachPhysicalNode(physicsBarrel)

        barrel.setPos(barrelNode, 0,0,0)

        visual_barrel = self.scene.attachNewNode("BarrelCopy")
        originalBarrel = self.scene.find("barrel")
        originalBarrel.instanceTo(visual_barrel)
        visual_barrel.reparentTo(barrel)
        visual_barrel.setPos(self.scene, -6.5,0,-24.5 )

        dataNode = barrelNode.attachNewNode(AuxData("Sequence",None))
        seq = self.createBarrelGraphicSequence(visual_barrel, physicsBarrel, dataNode)
        dataNode.node().getPythonTag("subclass").sequence = seq

        #sphere =  CollisionSphere(6.6,0,4.78, 0.5)
        sphere =  CollisionSphere(6.6,0,24.7, 0.5)
        cnodePath = visual_barrel.attachNewNode(CollisionNode('barrelCollider'))
        cnodePath.node().addSolid(sphere)
        cnodePath.node().setFromCollideMask(0xD) # crash with default and mario body and walls
        cnodePath.node().setIntoCollideMask(0xD) # crash with default and mario body and walls
        self.showCollision(cnodePath)
        #cnodePath.show()
        self.physicsCollisionPusher.addCollider(cnodePath,barrel)
        base.cTrav.addCollider(cnodePath, self.physicsCollisionPusher)

        barrelForceNode = ForceNode('barrelForce')
        barrel.attachNewNode(barrelForceNode)
        barrelForce = LinearVectorForce(-7,0,0, 1, False)
        # barrelForce.setMassDependent(0)
        barrelForceNode.addForce(barrelForce)
        physicsBarrel.getPhysical(0).addLinearForce(barrelForce)
        # starting barrel point :D
        barrelNode.setPos(self.scene,6.5,0,4.5)
예제 #16
0
    def createBarrel(self):

        barrelNode = NodePath("PhysicalBarrel")
        barrelNode.reparentTo(self.scene)

        physicsBarrel = ActorNode("physics_barrel")
        physicsBarrel.getPhysicsObject().setMass(
            0.01)  #in what units? (69 kindda 3 lbs)
        barrel = barrelNode.attachNewNode(physicsBarrel)
        base.physicsMgr.attachPhysicalNode(physicsBarrel)

        barrel.setPos(0, 0, 2)

        visual_barrel = self.scene.attachNewNode("BarrelCopy")
        originalBarrel = self.scene.find("barrel")
        originalBarrel.instanceTo(visual_barrel)
        visual_barrel.reparentTo(barrel)

        sphere = CollisionSphere(6.6, 0, 4.78, 0.5)
        cnodePath = visual_barrel.attachNewNode(
            CollisionNode('barrelCollider'))
        cnodePath.node().addSolid(sphere)
        cnodePath.node().setFromCollideMask(
            0xD)  # crash with default and mario body and walls
        cnodePath.node().setIntoCollideMask(
            0xD)  # crash with default and mario body and walls
        cnodePath.show()
        self.physicsCollisionPusher.addCollider(cnodePath, barrel)
        base.cTrav.addCollider(cnodePath, self.physicsCollisionPusher)

        barrelForceNode = ForceNode('barrelForce')
        barrel.attachNewNode(barrelForceNode)
        barrelForce = LinearVectorForce(-7, 0, 0, 1, False)
        # barrelForce.setMassDependent(0)
        barrelForceNode.addForce(barrelForce)
        physicsBarrel.getPhysical(0).addLinearForce(barrelForce)
class QuadRotorSimulation(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.scene = self.loader.loadModel(models_dir + "hallway.bam")  # Load the environment model
        self.scene.reparentTo(self.render)
        self.scene.setScale(1, 1, 1)
        self.scene.setPos(0, 0, 1)
        self.scene.setHpr(90, 0, 0)

        # Add an ambient light and set sky color
        sky_col = VBase3(135 / 255.0, 206 / 255.0, 235 / 255.0)
        self.set_background_color(sky_col)
        alight = AmbientLight("sky")
        alight.set_color(VBase4(sky_col * 0.04, 1))
        alight_path = self.render.attachNewNode(alight)
        self.render.set_light(alight_path)

        # # 4 perpendicular lights (flood light)
        for light_no in range(4):
            d_light = DirectionalLight('directionalLight')
            d_light.setColor(Vec4(*([0.3] * 4)))
            d_light_NP = self.render.attachNewNode(d_light)
            d_light_NP.setHpr(-90 * light_no, 0, 0)
            self.render.setLight(d_light_NP)

        # # 1 directional light (Sun)
        sun_light = DirectionalLight('directionalLight')
        sun_light.setColor(Vec4(*([0.7] * 4)))  # directional light is dim green
        sun_light.getLens().setFilmSize(Vec2(0.8, 0.8))
        sun_light.getLens().setNearFar(-0.3, 12)
        sun_light.setShadowCaster(True, 2 ** 7, 2 ** 7)
        self.dlightNP = self.render.attachNewNode(sun_light)
        self.dlightNP.setHpr(0, -65, 0)

        # Turning shader and lights on
        self.render.setLight(self.dlightNP)

        # Load and transform the quadrotor actor.
        self.quad_model = self.loader.loadModel(models_dir + f'{quad_model_filename}.egg')
        self.prop_models = []

        for prop_no in range(4):
            prop = self.loader.loadModel(models_dir + 'propeller.egg')
            x = 0 if prop_no % 2 == 1 else (-0.26 if prop_no == 0 else 0.26)
            y = 0 if prop_no % 2 == 0 else (-0.26 if prop_no == 3 else 0.26)
            prop.setPos(x, y, 0)
            prop.reparentTo(self.quad_model)
            self.prop_models.append(prop)

        self.prop_models = tuple(self.prop_models)
        # self.quad_model.reparentTo(self.scene)
        self.quad_model.setPos(0, 0, 2)
        self.quad_neutral_hpr = (90, 0, 0)
        self.quad_model.setHpr(*self.quad_neutral_hpr)

        # env cam
        self.cam_neutral_pos = (0, -4, 3)
        self.cam.reparentTo(self.scene)
        # self.cam_neutral_pos = (-4, 0, 1)
        # self.cam.reparentTo(self.quad_model)

        self.cam.setPos(*self.cam_neutral_pos)
        self.cam.lookAt(self.quad_model)

        self.enableParticles()
        node = NodePath("PhysicsNode")
        node.reparentTo(self.scene)
        self.actor_node = ActorNode("quadrotor-physics")
        # self.actor_node.getPhysicsObject().setMass(1)
        self.actor_node_physics = node.attachNewNode(self.actor_node)
        self.physicsMgr.attachPhysicalNode(self.actor_node)
        self.quad_model.reparentTo(self.actor_node_physics)

        # add gravity
        # gravity_force_node = ForceNode('world-forces')
        # gravityForce = LinearVectorForce(0, 0, -0.1)  # gravity acceleration
        # gravity_force_node.addForce(gravityForce)
        # self.physicsMgr.addLinearForce(gravityForce)

        self.time = datetime.datetime.today().strftime('%Y-%m-%d-%H.%M.%S')
        self.simulation_folder = "\sims\\" + self.time + '\\'
        self.simulation_folder_path = ROOT_DIR + self.simulation_folder
        os.makedirs(self.simulation_folder_path)
        self.movements = ''

        self.taskMgr.add(self.camera_move, 'Camera Movement')
        self.taskMgr.add(self.quad_move, 'Quad Movement')
        self.taskMgr.add(self.rotate_propellers, 'Propellers Rotation')
        self.taskMgr.add(self.save_image, 'Screenshot Capture')

        # self.buffer: GraphicsBuffer = self.win.makeTextureBuffer(name='buffer', x_size=84, y_size=84, tex=None, to_ram=True)
        # self.buffer.setActive(1)
        self.images = []
        self.image_index = 1

    def camera_move(self, task):
        """
        Moves the camera about the quadcopter
        """

        keys_vs_moves = {'k': i,
                         'h': -i,
                         'i': j,
                         'y': -j,
                         'u': k,
                         'j': -k
                         }

        mat = np.array(self.cam.getMat())[0:3, 0:3]
        move_total = LPoint3f(0, 0, 0)

        for key, move in keys_vs_moves.items():
            pressed_key = self.mouseWatcherNode.is_button_down(KeyboardButton.asciiKey(key))
            if pressed_key:
                move = LPoint3f(move)
                move_total += move

        # if any([abs(coordinate) > 0 for coordinate in move_total]):
        # ROTATE COORDINATE SYSTEM (TO CAMERA)
        move_total = LPoint3f(*tuple(np.dot(mat.T, np.array(move_total))))
        proportionality_constant = 0.05
        cam_pos = self.cam.getPos() + move_total * proportionality_constant
        self.cam.setPos(cam_pos)
        self.cam.lookAt(self.quad_model)

        return task.cont

    def quad_move(self, task):
        position_proportionality_constant = 0.0007
        angle_proportionality_constant = 0.2
        angle_max = 10
        angle_directions = {i: k, j: -j}

        keys_vs_moves = {'w': i,
                         's': -i,
                         'a': j,
                         'd': -j,
                         'e': k,
                         'q': -k}

        move_total = LPoint3f(0, 0, 0)
        angle_total = LPoint3f(0, 0, 0)

        for key, move in keys_vs_moves.items():
            pressed_key = self.mouseWatcherNode.is_button_down(KeyboardButton.asciiKey(key))
            if pressed_key:
                move_total += move

                if key not in ['e', 'q', 'm']:
                    angle_total += LPoint3f(*tuple(sign(move) *
                                                   np.array(
                                                       angle_directions[LPoint3f(*tuple(int(abs(c)) for c in move))])
                                                   * angle_proportionality_constant))
                else:
                    prop_sign = 1 if key == 'e' else -1

                    for prop in self.prop_models:
                        prop.setHpr(prop.get_hpr() + LPoint3f(10 * prop_sign, 0, 0))

                self.movements += key

                with open(ROOT_DIR + self.simulation_folder + 'movements.txt', 'w') as file:
                    file.write(self.movements)

                    # self.movie(namePrefix=self.simulation_folder, duration=1.0, fps=30,
                    #       format='png', sd=4, source=None)

        if any([abs(coordinate) > 0 for coordinate in angle_total]):
            # tilt_force_node = ForceNode('tilt-force')
            # tilt_force = AngularVectorForce(*angle_total)
            # tilt_force_node.addForce(tilt_force)
            #
            # self.actor_node.getPhysical(0).addAngularForce(tilt_force)

            desired_quad_hpr = list(self.quad_model.getHpr() + angle_total)

            for index, coordinate in enumerate(desired_quad_hpr):
                if coordinate:
                    desired_quad_hpr[index] = sign(coordinate) * min(abs(coordinate), 90 + angle_max
                    if index == 0 else angle_max)

            desired_quad_hpr = LPoint3f(*desired_quad_hpr)
            self.quad_model.setHpr(desired_quad_hpr)

        if any([abs(coordinate) > 0 for coordinate in move_total]):

            movement_force_node = ForceNode('movement-force')
            movement_force = LinearVectorForce(*(- move_total * position_proportionality_constant))
            # movement_force.setMassDependent(1)
            movement_force_node.addForce(movement_force)

            self.actor_node.getPhysical(0).addLinearForce(movement_force)

            # time.sleep(0.1)

            # thruster.setP(-45)  # bend the thruster nozzle out at 45 degrees

            # desired_quad_pos = self.quad_model.getPos() + move_total * position_proportionality_constant
            # self.quad_model.setPos(desired_quad_pos)

        return task.cont

    def rotate_propellers(self, task):
        for prop in self.prop_models:
            prop.setHpr(prop.get_hpr() + LPoint3f(30, 0, 0))

        return task.cont

    # def produce_video(self):

    def save_image(self, task):
        self.image_index += 1
        if self.image_index % 10 == 0:
            self.screenshot(namePrefix=rf'{self.simulation_folder}\image')

        if self.image_index % 100 == 0:
            # p = Process(target=my_function, args=(queue, 1))
            # p.start()

            video_name = rf'{self.simulation_folder_path}\video.avi'

            images = [img for img in os.listdir(self.simulation_folder_path) if img.endswith(".jpg")]
            frame = cv2.imread(os.path.join(self.simulation_folder_path, images[0]))
            height, width, layers = frame.shape

            video = cv2.VideoWriter(video_name, 0, 30, (width, height))

            for image in images:
                video.write(cv2.imread(os.path.join(self.simulation_folder_path, image)))

            cv2.destroyAllWindows()
            video.release()

        return task.cont
예제 #18
0
class MyApp(ShowBase):
    def center_mouse(self):
        self.win.movePointer(0,self.win.getXSize()/2,self.win.getYSize()/2)
    def __init__(self):
        #Game variables
        self.health = 100
        self.panda_kill_count = 0
        self.level = 0
        
        #Implementation variables
        #self.color = [Vec4((204.0/255), (255.0/255), (204/255), 0.1),Vec4((0/255), (255.0/255), (255.0/255), 0.1),Vec4((255.0/255), (51.0/255), (255.0/255), 0.1),Vec4((153.0/255), (255.0/255), (153.0/255), 0.1),Vec4((255.0/255), (178.0/255), (102.0/255), 0.1),Vec4((229.0/255), (204.0/255), (255.0/255), 0.1)]
        self.color = [Vec4(0.4,0.4,0.4,0.1)]
        self.mirror=False
        self.paused=False
        self.displayed=False
        self.game_started=False
        self.randomthings_ = randomthings.RandomThings(self)
        self.shifted_cam=False
        self.is_firstP=False
        self.old_anim2 = None
        self.old_anim=None
        self.timeout=False
        (self.r,self.f,self.b,self.l)=(0,0,0,0)
        self.inside_level=False
        self.move_anim_queue=[]
        self.anim_queue=[]
        self.prev_time=0.0
        self.bullets = []
        self.rightspeed=0
        self.forwardspeed=0
        ShowBase.__init__(self)
        self.makeDefaultPipe()
        bb=self.pipe.getDisplayHeight()
        aa=self.pipe.getDisplayWidth()
        
        self.openDefaultWindow(size=(aa, bb))
        import layer2d
        self.layer2d = layer2d
        self.layer2d.update_info('Loading...')
        self.keyreader= ReadKeys(self,layer2d)
        
        #Sounds
        self.gunshot = self.loader.loadSfx("sounds/gunshot_se.ogg")
        self.gunshot.setLoop(False)
        
        self.music = self.loader.loadSfx("sounds/music.ogg")
        self.music.setLoop(True)
        
        
        self.zombie_die = self.loader.loadSfx('sounds/zombie_die.ogg')
        self.zombie_die.setLoop(False)
        
        self.kicked = self.loader.loadSfx('sounds/kicked.ogg')
        self.kicked.setLoop(False)
        
        self.hurt_sound = self.loader.loadSfx('sounds/hurt.ogg')
        self.hurt_sound.setLoop(False)
        
        self.dead_sound = self.loader.loadSfx('sounds/dead.ogg')
        self.dead_sound.setLoop(False)
        
        self.intro_sound = self.loader.loadSfx('sounds/intro.ogg')
        self.intro_sound.setLoop(False)
        self.intro_sound.play()
        
        
        self.enableParticles()
        self.center_mouse()
        #self.disableMouse()
        self.prev_pos = None
        if base.mouseWatcherNode.hasMouse():
            x=base.mouseWatcherNode.getMouseX()
            y=base.mouseWatcherNode.getMouseY()
            self.prev_pos = (x,y)
        #Hide cursor
        props = WindowProperties()
        props.setCursorHidden(True) 
        self.win.requestProperties(props)
        
        
        self.environ = self.loader.loadModel('models/ourworld')
        self.environ.setPos(0,0,0)
        self.environ.reparentTo(self.render)
        
        
        self.pandaActor = Actor("models/hero_anim", {'kick':'models/hero_anim-kick','unready_to_shoot':'models/hero_anim-unready_to_shoot','jump':'models/hero_anim-jump',"shooting":"models/hero_anim-shooting","ready_to_shoot":"models/hero_anim-ready_to_shoot","ready_to_walk":"models/hero_anim-ready_to_run","ready_to_run":"models/hero_anim-ready_to_run","walk4":"models/hero_anim-walk1", "breathe": "models/hero_anim-breathe", "run": "models/hero_anim-walk"})
        self.pandaActor.setPlayRate(3,'ready_to_shoot')
        self.pandaActor.setPlayRate(-1.0,"ready_to_walk")
        self.pandaActor.setPlayRate(1.5,'run')
        self.pandaActor.setPlayRate(1.5,'ready_to_run')
        self.pandaActor.reparentTo(self.render)
        self.pandaActor.setPos(self.environ,0,0,100)
        self.pandaActor.loop("breathe")
        
        self.phy = NodePath("PhysicsNode")
        self.phy.reparentTo(self.render)
        
        self.pandaAN = ActorNode("PandaActor")
        self.pandaActorPhysicsP = self.phy.attachNewNode(self.pandaAN)
        
        self.physicsMgr.attachPhysicalNode(self.pandaAN)
        self.pandaActor.reparentTo(self.pandaActorPhysicsP)
        
        
        #set mass of panda
        self.pandaAN.getPhysicsObject().setMass(100)
        
        #apply gravity
        self.gravityFN=ForceNode('world-forces')
        self.gravityFNP=self.environ.attachNewNode(self.gravityFN)
        self.gravityForce=LinearVectorForce(0,0,-30.81) #gravity acceleration
        self.gravityFN.addForce(self.gravityForce)
        self.physicsMgr.addLinearForce(self.gravityForce)
        
        
        #camera stuff
        self.camera.reparentTo(self.pandaActor)
        self.camera.lookAt(self.pandaActor)
        self.taskMgr.add(self.spinCameraTask, "zombieTask_SpinCameraTask")
        self.taskMgr.doMethodLater(0.01,self.movePandaTask,"zombieTask_movePandaTask")
        
        
        #Collision Handling
        self.cTrav = CollisionTraverser()
        self.collisionHandler = CollisionHandlerEvent()
        
        #Add collider for terrain
        self.groundCollider = self.environ.find("**/terrain")
        
        #Add walker for panda
        self.collision_sphere = CollisionSphere(0,0,1,1)
        self.collNode = CollisionNode('pandaWalker')
        self.cnodePath = self.pandaActor.attachNewNode(self.collNode)
        self.cnodePath.node().addSolid(self.collision_sphere)
        
        #AddZombieDetector for panda
        self.zombie_sphere = CollisionSphere(0,0,3,1)
        self.zomb_detector_node = CollisionNode('zombieDetector')
        self.zomb_detector_NP = self.pandaActor.attachNewNode(self.zomb_detector_node)
        self.zomb_detector_NP.node().addSolid(self.zombie_sphere)
        #self.zomb_detector_NP.show()
        
        #Add pusher against gravity
        self.pusher = PhysicsCollisionHandler()
        self.pusher.addCollider(self.cnodePath, self.pandaActorPhysicsP)
        self.pusher.addCollider(self.zomb_detector_NP,self.pandaActorPhysicsP)
        self.cTrav.addCollider(self.cnodePath,self.pusher)
        self.cTrav.addCollider(self.zomb_detector_NP,self.pusher)
        
        self.pusher.addInPattern('%fn-into-%in')
        self.pusher.addAgainPattern('%fn-again-%in')
        
        #Add collision handler patterns
        self.collisionHandler.addInPattern('%fn-into-%in')
        self.collisionHandler.addAgainPattern('%fn-again-%in')
        
        self.abientLight = AmbientLight("ambientLight")
        self.abientLight.setColor(Vec4(0.1, 0.1, 0.1, 1))
        self.directionalLight = DirectionalLight("directionalLight")
        self.directionalLight.setDirection(Vec3(-5, -5, -5))
        self.directionalLight.setColor(Vec4((229.0/255), (204.0/255), (255.0/255), 0.7))
        self.directionalLight.setSpecularColor(Vec4(0.4, 0.4, 0.4, 0.1))
        self.directionalLight.setShadowCaster(True,512,512)
        self.render.setLight(self.render.attachNewNode(self.abientLight))
        self.render.setLight(self.render.attachNewNode(self.directionalLight))
        self.render.setShaderAuto()
        
        #create zombie land
        self.zombieland = zombie.Zombies(self)
        self.taskMgr.doMethodLater(0.01,self.zombieland.moveZombie, "zombieTask_ZombieMover")
        layer2d.incBar(self.health)
        self.taskMgr.add(self.game_monitor,"zombieTask_gameMonitor")
        self.taskMgr.doMethodLater(2.7,self.music_play, "zombieTask_music")
        
        #Add random useless things:
        self.randomthings_.add_random_things()
    def music_play(self,task):
        self.music.play()
        return Task.done
    #def get_color(self):
     #   return self.color[min(len(self.color)-1,self.level)]
    
    #GameMonitor
    def game_monitor(self,task):
        if self.paused:
            return Task.cont
        #Update Score
        self.layer2d.update_score(self.panda_kill_count)
        #Check for health of actor
        if self.health <= 0:
            self.dead_sound.play()
            self.pandaActor.detachNode()
            print "LOL u ded"
            self.info = """Game Over..
    Score: """ + str(self.panda_kill_count) + """
    Press alt+f4 to quit the game.
    
    """
            self.layer2d.update_info(self.info)
            self.taskMgr.removeTasksMatching('zombieTask_*')
        
        if self.game_started<>True:
            if not self.displayed:
                self.display_information()
            self.pandaActor.setPos(self.pandaActorPhysicsP.getRelativePoint(self.render,Point3(10,10,100)))
            return Task.cont
        
        #Check if user is inside some level. if yes, pass.
        if self.inside_level or self.timeout:
            return Task.cont
        self.inside_level = True
        #self.health=100
        self.timeout=True
        print ".."
        #The next lines will be executed only when the user is in between two levels (or at the beginning of the game)
        #Display information based on game level
        self.display_information()
        print "HUEHUEHUEHUE"    
        #Schedule wave of zombies
        self.taskMgr.doMethodLater(10,self.addWave, "zombieTask_ZombieAdder")
        
        return Task.cont
        
            
    
    def addWave(self,task):
        ##add a wave of 5 zombies, depending on the level.
        ##speed of zombie increases with each level
        ##durability of zombie increases with each level.
        ##Wave ends when all zombies die.
        self.directionalLight.setSpecularColor(Vec4(0.4, 0.4, 0.4, 0.1))
        self.layer2d.update_info("level"+str(self.level))
        self.timeout=False
        self.zombieland.add(5)
        return Task.done
        
    
    #information displayer
    def display_information(self):
        #display information based on levels.
        print self.game_started
        self.displayed=True
        if self.game_started==False:
            info = """
    Welcome to PandaLand. Once upon a time, there used to be these cute

    little creatures called Pandas. They were lazy, funny, and

    adorable. But that is what we humans thought. Pandas are

    actually an evil alien race that spread from planet to planet,

    spreading destruction and terror everywhere. They ruled earth

    several billion years ago. But our super ancestors (Dinosaurs)

    fought agaisnt them with great valour and selflessness; and managed

    to save planet Earth from doom. But the pandas went into hiding

    (and became cute); until few days back! Now they seek to kill all.

    You, the Joker, are our only hope,since Batman has retired.

    Go Kill Pandas.For Mother Earth!
    
    

    """
            self.layer2d.information['bg'] = (0,0,0,0.8)
        else:
            self.layer2d.update_info('')
            if self.level==0:
                info="""
    Your game will start in a few seconds.
    This is the first level. Pandas will spawn
    and follow you. Shoot to kill.

    Test out your controls while
    they are still cute and harmless :)
    
    Jump: Space
    Shoot: LeftClick
    Kick: RightClick
    Walk: A/W/S/D
    
    For more information, press P.

"""
                
                self.layer2d.information['bg'] = (0,0,0,0.6)
            elif self.level==1:
                info="""
    Level 0 Completed!
    Starting Level 1.
    
    Pandas have turned evil
    and stronger. They will try
    to eat you up.

    To run:
    Press Shift + A/S/W/D

"""
            elif self.level==2:
                info="""
    Level 1 Completed!
    Starting Level 2.
    
    Pandas are even stronger now.
    They will get stronger by
    each level.

    Your automatic shooting speed has
    also improved due to experience
    gained.

"""
            elif self.level==3:
                info="""
    Level 2 Completed!
    Starting Level 3.
    
    Pandas also move faster
    by each level. They really
    want to eat you.

    But don't worry, you also 
    run faster as the levels
    proceed.
    
"""
            else:
                info = """
    Level """ + str(self.level-1) + """ Completed!
    Starting """ + str(self.level) + """ .
    
    Well done!
    Keep fighting, our fate lies
    in your hands.
    
"""
        self.layer2d.update_info(info)
    #self.create_bullet()
    def create_bullet(self):
        self.bullet = self.loader.loadModel('models/gun/bullet')
        self.gunshot.play()
        self.bulletAN = ActorNode("BulletNode")
        self.bulletActorPhysicsP = self.phy.attachNewNode(self.bulletAN)
        
        self.physicsMgr.attachPhysicalNode(self.bulletAN)
        self.bullet.reparentTo(self.bulletActorPhysicsP)
        self.bulletAN.getPhysicsObject().setMass(1)
        self.bullet.setPos(self.pandaActor,0,-3,3.5)
        self.bullet.setScale(0.1,0.1,0.1)
        self.bullet.setHpr(self.pandaActor,0,90,0)
        self.bullet.setP(self.camera.getP()+90)
        self.bullet_sphere = CollisionSphere(0,0,0,0.2)
        self.bullet_collNode = CollisionNode('bullet')
        self.bullet_cnodePath = self.bullet.attachNewNode(self.bullet_collNode)
        self.bullet_cnodePath.node().addSolid(self.bullet_sphere)
        
        #self.pusher.addCollider(self.bullet_cnodePath,self.bulletActorPhysicsP)
        self.cTrav.addCollider(self.bullet_cnodePath,self.collisionHandler)
        
        #self.bullet_cnodePath.show()
        self.bullets += [self.bullet]
    def bulletKiller(self,task):
        if self.paused:
            return Task.cont
        self.bullets[0].remove_node()
        self.bullets = self.bullets[1:]
        return Task.done
    
    
    def bulletThrower(self,task):
        if self.paused:
            return Task.cont
        #make bullet move
        if self.pandaActor.getCurrentAnim()<>'shooting' and self.pandaActor.getCurrentAnim()<>'ready_to_shoot':
            self.pandaActor.play('shooting')
        print "loL"
        self.create_bullet()
        
        self.bulletAN.getPhysicsObject().setVelocity(self.render.getRelativeVector(self.camera,Vec3(0,200,0)))
        
        self.taskMgr.doMethodLater(max(0.05,0.1*(5-self.level)),self.bulletThrower, "zombieTask_bulletThrower")
        self.taskMgr.doMethodLater(0.5,self.bulletKiller, "zombieTask_bulletKiller")
        
        self.prev=True
        
        if self.old_anim2==None:
            self.old_anim2='breathe'
        if self.old_anim2 not in ['run','walk4']:
            self.old_anim2='breathe'
        self.anim_queue = [(self.pandaActor,True,'unready_to_shoot'),(self.pandaActor,False,self.old_anim2)]
        return Task.done
        
    def movePandaTask(self,task):
        
        if self.paused:
            return Task.cont
        tempos = self.pandaActor.getPos()
        speed = 0.1
        if self.run_:
            speed+=0.3*self.level
        self.rightspeed = -(self.r-self.l)*speed
        self.forwardspeed = -(self.f-self.b)*speed
        if (self.r-self.l)<>0 and (self.f-self.b)<>0:
            #print self.forwardspeed
            #print self.rightspeed
            #sys.exit(0)
            self.rightspeed *= 0.7
            self.forwardspeed *= 0.7
        self.pandaActor.setPos(self.pandaActor,self.rightspeed, self.forwardspeed,0)
        return Task.again
    def spinCameraTask(self, task):
        if self.paused:
           
            return Task.cont
        if self.render.getRelativePoint(self.pandaActorPhysicsP,self.pandaActor.getPos())[2] < -10:
            self.pandaAN.getPhysicsObject().setVelocity(0,0,30)
            #self.pandaActor.setPos(self.pandaActorPhysicsP.getRelativePoint(self.render,Point3(10,10,100)))
        self.prev_time=task.time
        
            
            
        #play queued animations:
        for x in self.move_anim_queue+self.anim_queue:
            if x[0].getCurrentAnim()==None:
                if x[1]:
                    x[0].play(x[2])
                else:
                    x[0].loop(x[2])
                if x in self.move_anim_queue:
                    self.move_anim_queue.remove(x)
                elif x in self.anim_queue:
                    self.anim_queue.remove(x)
                    
        
        #Do other stuff
        if self.mouseWatcherNode.hasMouse():
            x=base.mouseWatcherNode.getMouseX()
            y=base.mouseWatcherNode.getMouseY()
            if self.prev_pos==None:
                self.prev_pos = (x,y)
            xx = self.prev_pos[0] - x
            yy = self.prev_pos[1] + y
            self.prev_pos = (xx,yy)
            
            self.pandaActor.setHpr(self.pandaActor,-20*(pi/2.0)*x,0,0)
            
            #self.camera.setHpr(self.pandaActor, 20*(pi/2.0)*x, 20*(pi/2.0)*yy, 0)
            if self.is_firstP:
                self.camera.lookAt(self.pandaActor)
                self.camera.setPos(self.pandaActor,0,0,4)
                self.camera.setHpr(self.camera,180,0,0)
                
            else:
                self.camera.setPos(self.pandaActor,0,8,5)
                self.camera.lookAt(self.pandaActor)
                if self.mirror:
                    self.camera.setY(-self.camera.getY())
                    self.camera.lookAt(self.pandaActor)
            self.camera.setHpr(self.camera,0,20*(pi/2.0)*yy,0)
        self.center_mouse()
        
        #zombie collisions
        return Task.cont
    
    #User Actions:
    def meelee(self):
        #Make actor stomp here. or something
        #Load animation
        self.zombieland.meelee()
        self.anim_queue += [(self.pandaActor,True,self.pandaActor.getCurrentAnim())]
        self.pandaActor.play('kick')
        #pass
    def ranged_start(self):
        #put animation here
        self.old_anim = self.pandaActor.getCurrentAnim()
        if self.old_anim not in  ['shooting','unready_to_shoot','ready_to_shoot'] :
            self.old_anim2 = self.old_anim
        if self.old_anim not in ['ready_to_shoot','shooting','unready_to_shoot']:
            self.pandaActor.play('ready_to_shoot')
        
        self.taskMgr.add(self.bulletThrower, "zombieTask_bulletThrower")
    def ranged_stop(self,task=None):
        if self.paused:
            return Task.cont
        #stop animation here
        if self.pandaActor.getCurrentAnim()<>'shooting' and task==None:
            self.pandaActor.play('shooting')
            self.taskMgr.remove("zombieTask_bulletThrower")
            self.taskMgr.doMethodLater(0.5,self.ranged_stop,'zombieTask_rangedStop')
            return Task.done
        self.taskMgr.remove("zombieTask_bulletThrower")
        return Task.done
예제 #19
0
 def __init__(self):
     #Game variables
     self.health = 100
     self.panda_kill_count = 0
     self.level = 0
     
     #Implementation variables
     #self.color = [Vec4((204.0/255), (255.0/255), (204/255), 0.1),Vec4((0/255), (255.0/255), (255.0/255), 0.1),Vec4((255.0/255), (51.0/255), (255.0/255), 0.1),Vec4((153.0/255), (255.0/255), (153.0/255), 0.1),Vec4((255.0/255), (178.0/255), (102.0/255), 0.1),Vec4((229.0/255), (204.0/255), (255.0/255), 0.1)]
     self.color = [Vec4(0.4,0.4,0.4,0.1)]
     self.mirror=False
     self.paused=False
     self.displayed=False
     self.game_started=False
     self.randomthings_ = randomthings.RandomThings(self)
     self.shifted_cam=False
     self.is_firstP=False
     self.old_anim2 = None
     self.old_anim=None
     self.timeout=False
     (self.r,self.f,self.b,self.l)=(0,0,0,0)
     self.inside_level=False
     self.move_anim_queue=[]
     self.anim_queue=[]
     self.prev_time=0.0
     self.bullets = []
     self.rightspeed=0
     self.forwardspeed=0
     ShowBase.__init__(self)
     self.makeDefaultPipe()
     bb=self.pipe.getDisplayHeight()
     aa=self.pipe.getDisplayWidth()
     
     self.openDefaultWindow(size=(aa, bb))
     import layer2d
     self.layer2d = layer2d
     self.layer2d.update_info('Loading...')
     self.keyreader= ReadKeys(self,layer2d)
     
     #Sounds
     self.gunshot = self.loader.loadSfx("sounds/gunshot_se.ogg")
     self.gunshot.setLoop(False)
     
     self.music = self.loader.loadSfx("sounds/music.ogg")
     self.music.setLoop(True)
     
     
     self.zombie_die = self.loader.loadSfx('sounds/zombie_die.ogg')
     self.zombie_die.setLoop(False)
     
     self.kicked = self.loader.loadSfx('sounds/kicked.ogg')
     self.kicked.setLoop(False)
     
     self.hurt_sound = self.loader.loadSfx('sounds/hurt.ogg')
     self.hurt_sound.setLoop(False)
     
     self.dead_sound = self.loader.loadSfx('sounds/dead.ogg')
     self.dead_sound.setLoop(False)
     
     self.intro_sound = self.loader.loadSfx('sounds/intro.ogg')
     self.intro_sound.setLoop(False)
     self.intro_sound.play()
     
     
     self.enableParticles()
     self.center_mouse()
     #self.disableMouse()
     self.prev_pos = None
     if base.mouseWatcherNode.hasMouse():
         x=base.mouseWatcherNode.getMouseX()
         y=base.mouseWatcherNode.getMouseY()
         self.prev_pos = (x,y)
     #Hide cursor
     props = WindowProperties()
     props.setCursorHidden(True) 
     self.win.requestProperties(props)
     
     
     self.environ = self.loader.loadModel('models/ourworld')
     self.environ.setPos(0,0,0)
     self.environ.reparentTo(self.render)
     
     
     self.pandaActor = Actor("models/hero_anim", {'kick':'models/hero_anim-kick','unready_to_shoot':'models/hero_anim-unready_to_shoot','jump':'models/hero_anim-jump',"shooting":"models/hero_anim-shooting","ready_to_shoot":"models/hero_anim-ready_to_shoot","ready_to_walk":"models/hero_anim-ready_to_run","ready_to_run":"models/hero_anim-ready_to_run","walk4":"models/hero_anim-walk1", "breathe": "models/hero_anim-breathe", "run": "models/hero_anim-walk"})
     self.pandaActor.setPlayRate(3,'ready_to_shoot')
     self.pandaActor.setPlayRate(-1.0,"ready_to_walk")
     self.pandaActor.setPlayRate(1.5,'run')
     self.pandaActor.setPlayRate(1.5,'ready_to_run')
     self.pandaActor.reparentTo(self.render)
     self.pandaActor.setPos(self.environ,0,0,100)
     self.pandaActor.loop("breathe")
     
     self.phy = NodePath("PhysicsNode")
     self.phy.reparentTo(self.render)
     
     self.pandaAN = ActorNode("PandaActor")
     self.pandaActorPhysicsP = self.phy.attachNewNode(self.pandaAN)
     
     self.physicsMgr.attachPhysicalNode(self.pandaAN)
     self.pandaActor.reparentTo(self.pandaActorPhysicsP)
     
     
     #set mass of panda
     self.pandaAN.getPhysicsObject().setMass(100)
     
     #apply gravity
     self.gravityFN=ForceNode('world-forces')
     self.gravityFNP=self.environ.attachNewNode(self.gravityFN)
     self.gravityForce=LinearVectorForce(0,0,-30.81) #gravity acceleration
     self.gravityFN.addForce(self.gravityForce)
     self.physicsMgr.addLinearForce(self.gravityForce)
     
     
     #camera stuff
     self.camera.reparentTo(self.pandaActor)
     self.camera.lookAt(self.pandaActor)
     self.taskMgr.add(self.spinCameraTask, "zombieTask_SpinCameraTask")
     self.taskMgr.doMethodLater(0.01,self.movePandaTask,"zombieTask_movePandaTask")
     
     
     #Collision Handling
     self.cTrav = CollisionTraverser()
     self.collisionHandler = CollisionHandlerEvent()
     
     #Add collider for terrain
     self.groundCollider = self.environ.find("**/terrain")
     
     #Add walker for panda
     self.collision_sphere = CollisionSphere(0,0,1,1)
     self.collNode = CollisionNode('pandaWalker')
     self.cnodePath = self.pandaActor.attachNewNode(self.collNode)
     self.cnodePath.node().addSolid(self.collision_sphere)
     
     #AddZombieDetector for panda
     self.zombie_sphere = CollisionSphere(0,0,3,1)
     self.zomb_detector_node = CollisionNode('zombieDetector')
     self.zomb_detector_NP = self.pandaActor.attachNewNode(self.zomb_detector_node)
     self.zomb_detector_NP.node().addSolid(self.zombie_sphere)
     #self.zomb_detector_NP.show()
     
     #Add pusher against gravity
     self.pusher = PhysicsCollisionHandler()
     self.pusher.addCollider(self.cnodePath, self.pandaActorPhysicsP)
     self.pusher.addCollider(self.zomb_detector_NP,self.pandaActorPhysicsP)
     self.cTrav.addCollider(self.cnodePath,self.pusher)
     self.cTrav.addCollider(self.zomb_detector_NP,self.pusher)
     
     self.pusher.addInPattern('%fn-into-%in')
     self.pusher.addAgainPattern('%fn-again-%in')
     
     #Add collision handler patterns
     self.collisionHandler.addInPattern('%fn-into-%in')
     self.collisionHandler.addAgainPattern('%fn-again-%in')
     
     self.abientLight = AmbientLight("ambientLight")
     self.abientLight.setColor(Vec4(0.1, 0.1, 0.1, 1))
     self.directionalLight = DirectionalLight("directionalLight")
     self.directionalLight.setDirection(Vec3(-5, -5, -5))
     self.directionalLight.setColor(Vec4((229.0/255), (204.0/255), (255.0/255), 0.7))
     self.directionalLight.setSpecularColor(Vec4(0.4, 0.4, 0.4, 0.1))
     self.directionalLight.setShadowCaster(True,512,512)
     self.render.setLight(self.render.attachNewNode(self.abientLight))
     self.render.setLight(self.render.attachNewNode(self.directionalLight))
     self.render.setShaderAuto()
     
     #create zombie land
     self.zombieland = zombie.Zombies(self)
     self.taskMgr.doMethodLater(0.01,self.zombieland.moveZombie, "zombieTask_ZombieMover")
     layer2d.incBar(self.health)
     self.taskMgr.add(self.game_monitor,"zombieTask_gameMonitor")
     self.taskMgr.doMethodLater(2.7,self.music_play, "zombieTask_music")
     
     #Add random useless things:
     self.randomthings_.add_random_things()
예제 #20
0
    def __init__(self, parent=None):
        '''
        Create a new Vehicle node. Physics should be initialized before any
        instances of Vehicle are created.

        arguments:
          parent -- A PandaNode for the vehicle to attach to. Default is None,
                    in which case the Vehicle should be added to the scene
                    graph via NodePath.attachNewNode().

        '''
        ActorNode.__init__(self, 'VehiclePhysics')
        base.physicsMgr.attachPhysicalNode(self)

        self.getPhysicsObject().setMass(MASS)
        if parent:
            self.myPath = parent.attachNewNode(self)
        else:
            self.myPath = NodePath(self)

        # Load vehicle model and place in the transparent bin.
        vehicleModel = loader.loadModel(MODEL_PATH)
        hull = vehicleModel.find('**/Hull')
        hull.setBin('transparent', 30)
        pwnsEnclosure = vehicleModel.find('**/Pwns_Enclosure')
        pwnsEnclosure.setBin('transparent', 30)
        self.myPath.setPos(0, 0, -0.0)
        selectable = self.myPath.attachNewNode(SelectableNode('vehicle sel'))
        vehicleModel.reparentTo(selectable)

        # ==== Initialize Physics ==== #
        thrusterForceNode = ForceNode('ThrusterForce')
        self.myPath.attachNewNode(thrusterForceNode)

        self.linearForce = LinearVectorForce(0, 0, 0)
        self.linearForce.setMassDependent(1)
        self.angularForce = AngularVectorForce(0, 0, 0)

        thrusterForceNode.addForce(self.linearForce)
        thrusterForceNode.addForce(self.angularForce)

        self.getPhysical(0).addLinearForce(self.linearForce)
        self.getPhysical(0).addAngularForce(self.angularForce)

        self.previousXY = (self.myPath.getX(), self.myPath.getY())

        self.tm = ThrusterManager()

        # Add self.updatePhysics to the task manager and run this task as
        # frequently as possible.
        self.updatePhysicsTask = taskMgr.add(self.updatePhysics,
                                             'UpdatePhysics')

        # ==== Initialize Cameras ==== #
        lens = PerspectiveLens()
        lens.setNearFar(0.05, 100.0)
        #Use either FocalLength or Fov. Fov ~40 is about what actual forward cameras are
        #lens.setFocalLength(0.8)
        lens.setFov(70, 70)
        camera = Camera("Forward_left", lens).getPath()
        camera.reparentTo(vehicleModel.find('**/Forward_Camera'))
        camera.setX(camera.getX() - 0.1)  # Forward cameras 20cm apart
        camera.setY(
            camera.getY() +
            0.05)  # Move in front of torpedo tubes to avoid abstruction
        camera.setHpr(0, 0, 0)

        camera = Camera("Forward_right", lens).getPath()
        camera.reparentTo(vehicleModel.find('**/Forward_Camera'))
        camera.setX(camera.getX() + 0.1)  # Forward cameras 20cm apart
        camera.setY(
            camera.getY() +
            0.05)  # Move in front of torpedo tubes to avoid abstruction
        camera.setHpr(0, 0, 0)

        lens = PerspectiveLens()
        lens.setNearFar(0.05, 100.0)
        lens.setFocalLength(0.8)
        camera = Camera("Downward", lens).getPath()
        camera.reparentTo(vehicleModel.find('**/Downward_Camera'))
        camera.setHpr(0, -90, 0)

        #Layout link (to access hydrophone information)
        self.layout = None

        #Hydrophone variables
        self.start_time = time()
        self.last_hydro_update = time()
예제 #21
0
 def __del__(self):
     ''' Remove update tasks from the panda task manager. '''
     taskMgr.remove(self.updatePhysicsTask)
     ActorNode.__del__(self)
예제 #22
0
class Bullet(DirectObject):
    def __init__(self, playerID, color=LPoint3f(0,0,0)):
        self.color = color
        self.playerID = playerID

        self.bulletNP = NodePath("Bullet-%d" % id(self))
        self.bulletAN = ActorNode("bullet-physics-%d" % id(self))
        # set the mass of the ball to 3.3g = average weight of a paintball
        self.bulletAN.getPhysicsObject().setMass(0.033)
        self.bulletANP = self.bulletNP.attachNewNode(self.bulletAN)
        base.physicsMgr.attachPhysicalNode(self.bulletAN)
        self.bullet = loader.loadModel("Bullet")
        self.bullet.setScale(2)
        self.bullet.setColorScale(
            self.color.getX(),
            self.color.getY(),
            self.color.getZ(),
            1.0)
        self.bullet.reparentTo(self.bulletANP)

        # setup the collision detection
        # 17.3 mm (0.0173) = size of a .68cal paintball
        self.bulletColName = "bulletCollision-%02d" % id(self)
        self.bulletSphere = CollisionSphere(0, 0, 0, 0.0173*2)
        self.bulletCollision = self.bulletANP.attachNewNode(CollisionNode(self.bulletColName))
        self.bulletCollision.node().addSolid(self.bulletSphere)
        #self.bulletCollision.show()
        base.physicpusher.addCollider(self.bulletCollision, self.bulletANP)
        base.cTrav.addCollider(self.bulletCollision, base.physicpusher)

    def shoot(self, pos, shootVec=None):
        if shootVec != None:
            v = shootVec
            v *= 214.0
        else:
            # Get from/to points from mouse click
            pMouse = base.mouseWatcherNode.getMouse()
            pFrom = Point3()
            pTo = Point3()
            base.camLens.extrude(pMouse, pFrom, pTo)

            pFrom = render.getRelativePoint(base.cam, pFrom)
            pTo = render.getRelativePoint(base.cam, pTo)

            # Calculate initial velocity
            v = pTo - pFrom
            v.normalize()
            v *= 214.0

        self.bulletNP.setPos(pos)
        self.bulletNP.reparentTo(render)
        self.bulletFN = ForceNode("Bullet-force-%d" % id(self))
        self.bulletFNP = self.bulletNP.attachNewNode(self.bulletFN)
        # speed of a paintball when he leafes the muzzle: 214 fps
        self.lvf = LinearVectorForce(v)
        self.lvf.setMassDependent(1)
        self.bulletFN.addForce(self.lvf)
        self.bulletAN.getPhysical(0).addLinearForce(self.lvf)

        self.accept("bulletCollision-%d-hit" % id(self), self.bulletHit)
        taskMgr.doMethodLater(
            2,
            self.doRemove,
            'doRemove-%d' % id(self),
            appendTask=True)

    def doRemove(self, task):
        if self is None: return task.done
        self.ignoreAll()
        self.bulletNP.removeNode()
        self.bulletAN.getPhysical(0).removeLinearForce(self.lvf)
        return task.done

    def bulletHit(self, entry):
        hitName = entry.getIntoNode().getName()
        if str(self.playerID) not in hitName and \
            self.bulletColName not in hitName:
            base.messenger.send("Bulet-hit-%s" % hitName, [entry, self.color])
            self.bulletNP.removeNode()
            self.bulletAN.getPhysical(0).removeLinearForce(self.lvf)
    def __init__(self):
        ShowBase.__init__(self)
        self.scene = self.loader.loadModel(models_dir + "hallway.bam")  # Load the environment model
        self.scene.reparentTo(self.render)
        self.scene.setScale(1, 1, 1)
        self.scene.setPos(0, 0, 1)
        self.scene.setHpr(90, 0, 0)

        # Add an ambient light and set sky color
        sky_col = VBase3(135 / 255.0, 206 / 255.0, 235 / 255.0)
        self.set_background_color(sky_col)
        alight = AmbientLight("sky")
        alight.set_color(VBase4(sky_col * 0.04, 1))
        alight_path = self.render.attachNewNode(alight)
        self.render.set_light(alight_path)

        # # 4 perpendicular lights (flood light)
        for light_no in range(4):
            d_light = DirectionalLight('directionalLight')
            d_light.setColor(Vec4(*([0.3] * 4)))
            d_light_NP = self.render.attachNewNode(d_light)
            d_light_NP.setHpr(-90 * light_no, 0, 0)
            self.render.setLight(d_light_NP)

        # # 1 directional light (Sun)
        sun_light = DirectionalLight('directionalLight')
        sun_light.setColor(Vec4(*([0.7] * 4)))  # directional light is dim green
        sun_light.getLens().setFilmSize(Vec2(0.8, 0.8))
        sun_light.getLens().setNearFar(-0.3, 12)
        sun_light.setShadowCaster(True, 2 ** 7, 2 ** 7)
        self.dlightNP = self.render.attachNewNode(sun_light)
        self.dlightNP.setHpr(0, -65, 0)

        # Turning shader and lights on
        self.render.setLight(self.dlightNP)

        # Load and transform the quadrotor actor.
        self.quad_model = self.loader.loadModel(models_dir + f'{quad_model_filename}.egg')
        self.prop_models = []

        for prop_no in range(4):
            prop = self.loader.loadModel(models_dir + 'propeller.egg')
            x = 0 if prop_no % 2 == 1 else (-0.26 if prop_no == 0 else 0.26)
            y = 0 if prop_no % 2 == 0 else (-0.26 if prop_no == 3 else 0.26)
            prop.setPos(x, y, 0)
            prop.reparentTo(self.quad_model)
            self.prop_models.append(prop)

        self.prop_models = tuple(self.prop_models)
        # self.quad_model.reparentTo(self.scene)
        self.quad_model.setPos(0, 0, 2)
        self.quad_neutral_hpr = (90, 0, 0)
        self.quad_model.setHpr(*self.quad_neutral_hpr)

        # env cam
        self.cam_neutral_pos = (0, -4, 3)
        self.cam.reparentTo(self.scene)
        # self.cam_neutral_pos = (-4, 0, 1)
        # self.cam.reparentTo(self.quad_model)

        self.cam.setPos(*self.cam_neutral_pos)
        self.cam.lookAt(self.quad_model)

        self.enableParticles()
        node = NodePath("PhysicsNode")
        node.reparentTo(self.scene)
        self.actor_node = ActorNode("quadrotor-physics")
        # self.actor_node.getPhysicsObject().setMass(1)
        self.actor_node_physics = node.attachNewNode(self.actor_node)
        self.physicsMgr.attachPhysicalNode(self.actor_node)
        self.quad_model.reparentTo(self.actor_node_physics)

        # add gravity
        # gravity_force_node = ForceNode('world-forces')
        # gravityForce = LinearVectorForce(0, 0, -0.1)  # gravity acceleration
        # gravity_force_node.addForce(gravityForce)
        # self.physicsMgr.addLinearForce(gravityForce)

        self.time = datetime.datetime.today().strftime('%Y-%m-%d-%H.%M.%S')
        self.simulation_folder = "\sims\\" + self.time + '\\'
        self.simulation_folder_path = ROOT_DIR + self.simulation_folder
        os.makedirs(self.simulation_folder_path)
        self.movements = ''

        self.taskMgr.add(self.camera_move, 'Camera Movement')
        self.taskMgr.add(self.quad_move, 'Quad Movement')
        self.taskMgr.add(self.rotate_propellers, 'Propellers Rotation')
        self.taskMgr.add(self.save_image, 'Screenshot Capture')

        # self.buffer: GraphicsBuffer = self.win.makeTextureBuffer(name='buffer', x_size=84, y_size=84, tex=None, to_ram=True)
        # self.buffer.setActive(1)
        self.images = []
        self.image_index = 1
예제 #24
0
 def __init__(self, parent, model, name):
     ModelNode.__init__(self, parent, model, name)
     actorNode = ActorNode(name + "_actor_node")
     self.actor = self.attachNewNode(actorNode)
     self.model.reparentTo(self.actor)