def __doThrow(self, alreadyThrown):
     self.weapon.setScale(1)
     pathNP = NodePath('throwPath')
     if not alreadyThrown:
         pathNP.reparentTo(self.suit)
     else:
         pathNP.reparentTo(self.weapon)
     pathNP.setScale(render, 1.0)
     pathNP.setPos(0, 30, -100)
     pathNP.setHpr(90, -90, 90)
     print pathNP.getPos(base.render)
     if self.throwTrajectory:
         self.throwTrajectory.pause()
         self.throwTrajectory = None
     if alreadyThrown:
         startPos = self.weapon.getPos(base.render)
         gravity = 0.7
     else:
         gravity = 0.7
         startPos = self.suit.find('**/joint_Rhold').getPos(base.render)
     self.throwTrajectory = ProjectileInterval(self.weapon, startPos=startPos, endPos=pathNP.getPos(base.render), gravityMult=gravity, duration=3.0)
     self.throwTrajectory.start()
     self.weapon.setScale(10)
     self.weapon.reparentTo(render)
     self.weapon.setHpr(pathNP.getHpr(render))
     self.weapon_state = 'released'
     self.acceptOnce(self.wsnp.node().getName() + '-into', self.__handleHitFloor)
     return
Esempio n. 2
0
	def throwObject(self, task):
		self.playWeaponSound()
		
		self.weaponNP = NodePath("weaponNP")
		self.weaponNP.setScale(render, 1)
		try: self.weaponNP.reparentTo(self.find('**/joint_nameTag'))
		except: return task.done
		self.weaponNP.setPos(0, 50, 0)
		self.weaponNP.setHpr(0, 0, 0)
		
		if self.weapon:
			self.weapon.setScale(self.weapon.getScale(render))
		try: self.weapon.reparentTo(render)
		except: return task.done
		
		self.weapon.setPos(0,0,0)
		self.weapon.setHpr(0,0,0)
		
		if self.attack == "glowerpower":
			self.weapon.setH(self.weaponNP.getH(render))
			self.wtrajectory = self.weapon.posInterval(0.5,
										Point3(self.weaponNP.getPos(render)),
										startPos=(self.getX(render), self.getY(render) + 3, self.find('**/joint_head').getZ(render)))
			self.wtrajectory.start()
		else:
			self.wtrajectory = ProjectileInterval(self.weapon,
										startPos = (self.suit.find('**/joint_Rhold').getPos(render)),
										endPos = self.weaponNP.getPos(render),
										gravityMult = 0.7, duration = 1)
			self.wtrajectory.start()
		if self.attack == "glowerpower":
			taskMgr.doMethodLater(0.5, self.delWeapon, "delWeapon")
		else:
			taskMgr.doMethodLater(1, self.delWeapon, "delWeapon")
		self.weapon_state = 'released'
Esempio n. 3
0
 def shoot(self, rangeVector):
     if not self.gag:
         return
     rangeNode = NodePath('Shoot Range')
     rangeNode.reparentTo(self.turret.getCannon())
     rangeNode.setScale(render, 1)
     rangeNode.setPos(rangeVector)
     rangeNode.setHpr(90, -90, 90)
     self.gag.setScale(self.gag.getScale(render))
     self.gag.setScale(self.gag.getScale(render))
     self.gag.setPos(self.gag.getPos(render))
     self.gag.reparentTo(render)
     self.gag.setHpr(rangeNode.getHpr(render))
     base.audio3d.attachSoundToObject(self.gagClass.woosh, self.gag)
     self.gagClass.woosh.play()
     self.track = ProjectileInterval(self.gag,
                                     startPos=self.gag.getPos(render),
                                     endPos=rangeNode.getPos(render),
                                     gravityMult=self.gravityMult,
                                     duration=self.duration,
                                     name=self.trackName)
     self.track.setDoneEvent(self.track.getName())
     self.acceptOnce(self.track.getDoneEvent(), self.cleanup)
     self.track.start()
     fireSfx = base.audio3d.loadSfx(
         'phase_4/audio/sfx/MG_cannon_fire_alt.ogg')
     base.audio3d.attachSoundToObject(fireSfx, self.turret.getCannon())
     fireSfx.play()
     if self.turret.isLocal():
         self.buildCollisions()
         self.acceptOnce(self.eventName, self.handleCollision)
Esempio n. 4
0
 def shoot(self, rangeVector):
     if not self.gag:
         return
     rangeNode = NodePath('Shoot Range')
     rangeNode.reparentTo(self.turret.getCannon())
     rangeNode.setScale(render, 1)
     rangeNode.setPos(rangeVector)
     rangeNode.setHpr(90, -90, 90)
     self.gag.setScale(self.gag.getScale(render))
     self.gag.setScale(self.gag.getScale(render))
     self.gag.setPos(self.gag.getPos(render))
     self.gag.reparentTo(render)
     self.gag.setHpr(rangeNode.getHpr(render))
     base.audio3d.attachSoundToObject(self.gagClass.woosh, self.gag)
     self.gagClass.woosh.play()
     self.track = ProjectileInterval(self.gag, startPos=self.gag.getPos(render), endPos=rangeNode.getPos(render), gravityMult=self.gravityMult, duration=self.duration, name=self.trackName)
     self.track.setDoneEvent(self.track.getName())
     self.acceptOnce(self.track.getDoneEvent(), self.cleanup)
     self.track.start()
     fireSfx = base.audio3d.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.mp3')
     base.audio3d.attachSoundToObject(fireSfx, self.turret.getCannon())
     fireSfx.play()
     if self.turret.isLocal():
         self.buildCollisions()
         self.acceptOnce(self.eventName, self.handleCollision)
 def throwObject(self, projectile=True):
     if not self.weapon:
         return
     self.acceptOnce('enter' + self.wsnp.node().getName(), self.handleWeaponCollision)
     self.playWeaponSound()
     if self.weapon:
         self.weapon.wrtReparentTo(render)
         self.weapon.setHpr(Vec3(0, 0, 0))
     if self.attack not in ('glowerpower', ):
         parent = self.suit.find('**/joint_Rhold')
     else:
         parent = self.suit.find('**/joint_head')
     startNP = parent.attachNewNode('startNp')
     startNP.lookAt(render, self.targetX, self.targetY, self.targetZ)
     pathNP = NodePath('throwPath')
     pathNP.reparentTo(startNP)
     pathNP.setScale(render, 1.0)
     pathNP.setPos(0, 50, 0)
     if self.attack in ('clipontie', 'powertie', 'halfwindsor'):
         self.weapon.setHpr(pathNP.getHpr(render))
     if projectile == True:
         self.throwTrajectory = ProjectileInterval(self.weapon, startPos=self.suit.find('**/joint_Rhold').getPos(render), endPos=pathNP.getPos(render), gravityMult=0.7, duration=1.0)
     else:
         self.weapon.setH(pathNP.getH(render))
         self.throwTrajectory = LerpPosInterval(self.weapon, duration=0.5, pos=pathNP.getPos(render), startPos=startNP.getPos(render) + (0,
                                                                                                                                         3,
                                                                                                                                         0))
     self.throwTrajectory.start()
     self.weapon_state = 'released'
     startNP.removeNode()
     del startNP
     pathNP.removeNode()
     del pathNP
    def getTossPieInterval(self, toon, x, y, z, h, p, r, power, beginFlyIval = Sequence()):
        ToontownBattleGlobals = ToontownBattleGlobals
        import toontown.toonbase
        BattleProps = BattleProps
        import toontown.battle
        pie = toon.getPieModel()
        pie.setScale(0.5)
        flyPie = pie.copyTo(NodePath('a'))
        pieName = ToontownBattleGlobals.pieNames[toon.pieType]
        pieType = BattleProps.globalPropPool.getPropType(pieName)
        animPie = Sequence()
        if pieType == 'actor':
            animPie = ActorInterval(pie, pieName, startFrame = 48)
        
        sound = loader.loadSfx('phase_3.5/audio/sfx/AA_pie_throw_only.mp3')
        t = power / 100.0
        dist = lerp(PartyGlobals.CogActivityPieMinDist, PartyGlobals.CogActivityPieMaxDist, t)
        time = lerp(1.0, 1.5, t)
        proj = ProjectileInterval(None, startPos = Point3(0, 0, 0), endPos = Point3(0, dist, 0), duration = time)
        relVel = proj.startVel
        
        def getVelocity(toon = toon, relVel = relVel):
            return render.getRelativeVector(toon, relVel) * 0.59999999999999998

        
        def _PartyCogActivity__safeSetAnimState(toon = toon, state = 'Happy'):
            if toon and hasattr(toon, 'animFSM'):
                toon.setAnimState('Happy')
            else:
                self.notify.warning('The toon is being destroyed. No attribute animState.')

        toss = Track((0, Sequence(Func(toon.setPosHpr, x, y, z, h, p, r), Func(pie.reparentTo, toon.rightHand), Func(pie.setPosHpr, 0, 0, 0, 0, 0, 0), animPie, Parallel(ActorInterval(toon, 'throw', startFrame = 48, playRate = 1.5, partName = 'torso'), animPie), Func(_PartyCogActivity__safeSetAnimState, toon, 'Happy'))), (16.0 / 24.0, Func(pie.detachNode)))
        fly = Track((14.0 / 24.0, SoundInterval(sound, node = toon, cutOff = PartyGlobals.PARTY_COG_CUTOFF)), (16.0 / 24.0, Sequence(Func(flyPie.reparentTo, render), Func(flyPie.setPosHpr, toon, 0.52000000000000002, 0.96999999999999997, 2.2400000000000002, 0, -45, 0), beginFlyIval, ProjectileInterval(flyPie, startVel = getVelocity, duration = 6), Func(flyPie.detachNode))))
        return (toss, fly, flyPie)
Esempio n. 7
0
 def __doThrow(self, alreadyThrown):
     self.weapon.setScale(1)
     pathNP = NodePath('throwPath')
     if not alreadyThrown:
         pathNP.reparentTo(self.suit)
     else:
         pathNP.reparentTo(self.weapon)
     pathNP.setScale(render, 1.0)
     pathNP.setPos(0, 30, -100)
     pathNP.setHpr(90, -90, 90)
     print pathNP.getPos(base.render)
     if self.throwTrajectory:
         self.throwTrajectory.pause()
         self.throwTrajectory = None
     if alreadyThrown:
         startPos = self.weapon.getPos(base.render)
         gravity = 0.7
     else:
         gravity = 0.7
         startPos = self.suit.find('**/joint_Rhold').getPos(base.render)
     self.throwTrajectory = ProjectileInterval(self.weapon, startPos=startPos, endPos=pathNP.getPos(base.render), gravityMult=gravity, duration=3.0)
     self.throwTrajectory.start()
     self.weapon.setScale(10)
     self.weapon.reparentTo(render)
     self.weapon.setHpr(pathNP.getHpr(render))
     self.weapon_state = 'released'
     self.acceptOnce(self.wsnp.node().getName() + '-into', self.__handleHitFloor)
     return
Esempio n. 8
0
 def shootBullet(self, task):
     self.ball = self.loader.loadModel("models/bullet")
     self.ball.reparentTo(self.render)
     self.ball.setScale(0.02, 0.02, 0.02)
     self.ball.setPos(0, 0, 0)
     self.bullets.append(self.ball)
     self.bt = ProjectileInterval(self.ball,
                                  startPos=Point3(0, 0, -5),
                                  endPos=Point3(self.heading * -2, 100,
                                                self.pitch * 2),
                                  duration=0.3,
                                  gravityMult=-2)
     self.bt.start()
     self.taskMgr.doMethodLater(0.3, self.removeBullet, 'removeBullet')
     self.hit_flight()
     if (self.m1down):
         self.taskMgr.doMethodLater(0.2, self.shootBullet, 'shootbullet')
 def release(self):
     Gag.release(self)
     base.audio3d.attachSoundToObject(self.woosh, self.gag)
     base.playSfx(self.woosh, node=self.gag)
     throwPath = NodePath('ThrowPath')
     throwPath.reparentTo(self.avatar)
     throwPath.setScale(render, 1)
     throwPath.setPos(0, self.power, -90)
     throwPath.setHpr(90, -90, 90)
     entity = self.gag
     if not entity:
         entity = self.build()
     entity.wrtReparentTo(render)
     entity.setHpr(throwPath.getHpr(render))
     self.gag = None
     if not self.handJoint:
         self.handJoint = self.avatar.find('**/def_joint_right_hold')
     track = ProjectileInterval(entity, startPos=self.handJoint.getPos(render), endPos=throwPath.getPos(render), gravityMult=0.9, duration=3)
     event = self.avatar.uniqueName('throwIvalDone') + '-' + str(hash(entity))
     track.setDoneEvent(event)
     base.acceptOnce(event, self.__handlePieIvalDone, [entity])
     track.start()
     self.entities.append([entity, track])
     if self.isLocal():
         self.buildCollisions(entity)
         base.localAvatar.sendUpdate('usedGag', [self.id])
     self.reset()
     return
Esempio n. 10
0
 def shootBullet(self,task):
     self.ball = self.loader.loadModel("models/bullet")
     self.ball.reparentTo(self.render)
     self.ball.setScale(0.02,0.02,0.02)
     self.ball.setPos(0,0,0) 
     self.bullets.append(self.ball)
     self.bt = ProjectileInterval(self.ball,
                                  startPos = Point3(0,0,-5),
                                  endPos = Point3(self.heading * -2 , 100 , self.pitch*2), duration = 0.3 ,
                                  gravityMult = -2 )    
     self.bt.start()
     self.taskMgr.doMethodLater(0.3, self.removeBullet, 'removeBullet')
     self.hit_flight()
     if(self.m1down):
         self.taskMgr.doMethodLater(0.2, self.shootBullet, 'shootbullet')
Esempio n. 11
0
 def release(self):
     Gag.release(self)
     base.audio3d.attachSoundToObject(self.woosh, self.gag)
     self.woosh.play()
     throwPath = NodePath('ThrowPath')
     throwPath.reparentTo(self.avatar)
     throwPath.setScale(render, 1)
     throwPath.setPos(0, 160, -90)
     throwPath.setHpr(90, -90, 90)
     entity = self.gag
     if not entity:
         entity = self.build()
     entity.wrtReparentTo(render)
     entity.setHpr(throwPath.getHpr(render))
     self.gag = None
     if not self.handJoint:
         self.handJoint = self.avatar.find('**/def_joint_right_hold')
     track = ProjectileInterval(entity, startPos=self.handJoint.getPos(render), endPos=throwPath.getPos(render), gravityMult=0.9, duration=3)
     track.start()
     self.entities.append([entity, track])
     if self.isLocal():
         self.buildCollisions(entity)
     self.reset()
     return
Esempio n. 12
0
 def jump(self, extraArg):
     intoName = extraArg.getIntoNode().getName().lower()
     if not "floor" in intoName and not "plate" in intoName:
         return
     # setup the projectile interval
     startPos = self.player.getPos()
     self.jumpstartFloater.setPos(self.player, 0, 0.5, 0)
     tempFloater = NodePath(PandaNode("tempJumpFloater"))
     tempFloater.setPos(self.player, 0, -3.2, 0.1)
     endPos = tempFloater.getPos()
     tempFloater.removeNode()
     self.jumpInterval = ProjectileInterval(
         self.player, startPos=startPos, endPos=endPos, duration=1.5, gravityMult=0.25
     )
     self.request("Jump")
     self.jumpInterval.start()
Esempio n. 13
0
 def flyToNewSpot(self, spot):
     if not hasattr(self, 'suit') or not self.suit or self.suit.isEmpty():
         self.exit()
         return
     self.isAirborne = True
     endPos = CIGlobals.SuitSpawnPoints[self.suit.getHood()][spot]
     self.suit.headsUp(endPos)
     startPos = self.suit.getPos(render)
     duration = 5.0
     self.suit.d_startProjInterval(startPos, endPos, duration, 0.25)
     self.flyIval = Parallel(
         ProjectileInterval(self.suit,
                            startPos=startPos,
                            endPos=endPos,
                            gravityMult=0.25,
                            duration=duration),
         Sequence(Wait(9.0), Func(self.exit)))
     self.flyIval.start()
Esempio n. 14
0
    def fire(self):
        endx = self.actor.getX() + 200 * cos(radians(self.actor.getH() - 90))
        endy = self.actor.getY() + 200 * sin(radians(self.actor.getH() - 90))
        self.interval = ProjectileInterval(self.proj,
                                           startPos=self.proj.getPos(),
                                           endPos=(endx, endy,
                                                   self.actor.getZ()),
                                           duration=0.1)
        self.sequence = None

        def start():
            if self.character.fired or self.character.fireOnCooldown:
                self.sequence = Sequence(Func(self.kill))
            else:
                self.character.fired = True
                self.character.fireOnCooldown = True
                self.character.fireCooldown = 3
                self.character.fireCooldown = self.base.clock.get_long_time()
                self.sequence = Sequence(self.interval, Func(self.kill))

        start()
        self.sequence.start()
Esempio n. 15
0
class TurretGag(DirectObject):

    def __init__(self, turret, collideEventName, gagName):
        DirectObject.__init__(self)
        self.turret = turret
        self.collideEventName = collideEventName
        self.eventName = 'turretGagSensor' + str(id(self)) + '-into'
        self.trackName = 'turretGagTrack' + str(id(self))
        self.track = None
        self.gravityMult = 0.9
        self.duration = 2.5
        self.setClass(gagName)
        return

    def setClass(self, gagName):
        gagMgr = GagManager()
        self.gagClass = gagMgr.getGagByName(gagName)
        self.gag = None
        return

    def build(self):
        self.gagClass.build()
        self.gag = self.gagClass.getGag()
        self.gag.reparentTo(self.turret.getCannon())
        self.gag.setY(5.2)
        self.gag.setHpr(90, -90, 90)
        if isinstance(self.gag, Actor):
            self.gag.loop('chan')

    def shoot(self, rangeVector):
        if not self.gag:
            return
        rangeNode = NodePath('Shoot Range')
        rangeNode.reparentTo(self.turret.getCannon())
        rangeNode.setScale(render, 1)
        rangeNode.setPos(rangeVector)
        rangeNode.setHpr(90, -90, 90)
        self.gag.setScale(self.gag.getScale(render))
        self.gag.setScale(self.gag.getScale(render))
        self.gag.setPos(self.gag.getPos(render))
        self.gag.reparentTo(render)
        self.gag.setHpr(rangeNode.getHpr(render))
        base.audio3d.attachSoundToObject(self.gagClass.woosh, self.gag)
        self.gagClass.woosh.play()
        self.track = ProjectileInterval(self.gag, startPos=self.gag.getPos(render), endPos=rangeNode.getPos(render), gravityMult=self.gravityMult, duration=self.duration, name=self.trackName)
        self.track.setDoneEvent(self.track.getName())
        self.acceptOnce(self.track.getDoneEvent(), self.cleanup)
        self.track.start()
        fireSfx = base.audio3d.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.mp3')
        base.audio3d.attachSoundToObject(fireSfx, self.turret.getCannon())
        fireSfx.play()
        if self.turret.isLocal():
            self.buildCollisions()
            self.acceptOnce(self.eventName, self.handleCollision)

    def getGag(self):
        return self.gag

    def buildCollisions(self):
        pieSphere = CollisionSphere(0, 0, 0, 1)
        pieSensor = CollisionNode('turretGagSensor' + str(id(self)))
        pieSensor.addSolid(pieSphere)
        pieNP = self.gag.attachNewNode(pieSensor)
        pieNP.setCollideMask(BitMask32(0))
        pieNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
        event = CollisionHandlerEvent()
        event.set_in_pattern('%fn-into')
        event.set_out_pattern('%fn-out')
        base.cTrav.addCollider(pieNP, event)

    def handleCollision(self, entry):
        messenger.send(self.collideEventName, [entry, self])

    def getID(self):
        return self.gagClass.getID()

    def getCollideEventName(self):
        return self.collideEventName

    def cleanup(self):
        if hasattr(self, 'collideEventName'):
            del self.collideEventName
        if self.track:
            self.track.finish()
            self.track = None
        if self.turret:
            if self.turret.entities and self in self.turret.entities:
                self.turret.entities.remove(self)
            self.turret = None
        self.ignore(self.eventName)
        self.duration = None
        self.gravityMult = None
        self.eventName = None
        self.trackName = None
        if self.gagClass:
            self.gagClass.cleanupGag()
            self.gagClass = None
        if self.gag:
            if isinstance(self.gag, Actor):
                self.gag.cleanup()
            self.gag.removeNode()
            self.gag = None
        return
Esempio n. 16
0
class BounceCheckAttack(ThrowAttack):
    notify = directNotify.newCategory('BounceCheckAttack')
    MaxBounces = 3
    WeaponHitDistance = 0.5

    def __init__(self, attacksClass, suit):
        ThrowAttack.__init__(self, attacksClass, suit)
        self.attack = 'bouncecheck'
        self.bounceSound = None
        self.numBounces = 0
        return

    def __pollCheckDistance(self, task):
        if base.localAvatar.getDistance(self.weapon) <= self.WeaponHitDistance:
            self.handleWeaponCollision(None)
            return Task.done
        else:
            return Task.cont
            return

    def loadAttack(self):
        self.weapon = loader.loadModel('phase_5/models/props/bounced-check.bam')
        self.weapon.setScale(10)
        self.weapon.setTwoSided(1)
        self.bounceSound = base.audio3d.loadSfx('phase_5/audio/sfx/SA_bounce_check_bounce.mp3')
        base.audio3d.attachSoundToObject(self.bounceSound, self.suit)
        cSphere = CollisionSphere(0, 0, 0, 0.1)
        cSphere.setTangible(0)
        if hasattr(self, 'uniqueName'):
            name = self.uniqueName('bounced_check_collision')
        else:
            name = 'bounced_check_collision'
        cNode = CollisionNode(name)
        cNode.addSolid(cSphere)
        cNode.setFromCollideMask(CIGlobals.FloorBitmask)
        cNP = self.weapon.attachNewNode(cNode)
        cNP.setCollideMask(BitMask32(0))
        self.event = CollisionHandlerEvent()
        self.event.setInPattern('%fn-into')
        self.event.setOutPattern('%fn-out')
        base.cTrav.addCollider(cNP, self.event)
        self.wsnp = cNP
        self.wsnp.show()

    def doAttack(self, ts = 0):
        ThrowAttack.doAttack(self, ts)
        self.loadAttack()
        if hasattr(self, 'uniqueName'):
            name = self.uniqueName('doBounceCheckAttack')
        else:
            name = 'doBounceCheckAttack'
        self.suitTrack = Sequence(name=name)
        self.weapon.reparentTo(self.suit.find('**/joint_Rhold'))
        if self.suit.type == 'C':
            self.suitTrack.append(Wait(2.3))
        else:
            self.suitTrack.append(Wait(3))
        self.suit.play('throw-paper')
        self.suitTrack.append(Func(self.throwObject))
        self.suitTrack.start(ts)

    def throwObject(self):
        ThrowAttack.throwObject(self)
        taskMgr.add(self.__pollCheckDistance, 'pollCheckDistance')
        self.__doThrow(0)

    def __doThrow(self, alreadyThrown):
        self.weapon.setScale(1)
        pathNP = NodePath('throwPath')
        if not alreadyThrown:
            pathNP.reparentTo(self.suit)
        else:
            pathNP.reparentTo(self.weapon)
        pathNP.setScale(render, 1.0)
        pathNP.setPos(0, 30, -100)
        pathNP.setHpr(90, -90, 90)
        print pathNP.getPos(base.render)
        if self.throwTrajectory:
            self.throwTrajectory.pause()
            self.throwTrajectory = None
        if alreadyThrown:
            startPos = self.weapon.getPos(base.render)
            gravity = 0.7
        else:
            gravity = 0.7
            startPos = self.suit.find('**/joint_Rhold').getPos(base.render)
        self.throwTrajectory = ProjectileInterval(self.weapon, startPos=startPos, endPos=pathNP.getPos(base.render), gravityMult=gravity, duration=3.0)
        self.throwTrajectory.start()
        self.weapon.setScale(10)
        self.weapon.reparentTo(render)
        self.weapon.setHpr(pathNP.getHpr(render))
        self.weapon_state = 'released'
        self.acceptOnce(self.wsnp.node().getName() + '-into', self.__handleHitFloor)
        return

    def __handleHitFloor(self, entry):
        self.numBounces += 1
        if self.numBounces >= self.MaxBounces:
            self.cleanup()
            return
        base.playSfx(self.bounceSound)
        self.__doThrow(1)

    def cleanup(self):
        taskMgr.remove('pollCheckDistance')
        self.ignore(self.wsnp.node().getName() + '-into')
        self.bounceSound = None
        ThrowAttack.cleanup(self)
        return
class TurretGag(DirectObject):
    def __init__(self, turret, collideEventName, gagName):
        DirectObject.__init__(self)
        self.turret = turret
        self.collideEventName = collideEventName
        self.eventName = 'turretGagSensor' + str(id(self)) + '-into'
        self.trackName = 'turretGagTrack' + str(id(self))
        self.track = None
        self.gravityMult = 0.9
        self.duration = 2.5
        self.setClass(gagName)

    def setClass(self, gagName):
        gagMgr = GagManager()
        self.gagClass = gagMgr.getGagByName(gagName)
        self.gag = None

    def build(self):
        self.gagClass.build()
        self.gag = self.gagClass.getGag()
        self.gag.reparentTo(self.turret.getCannon())
        self.gag.setY(5.2)
        self.gag.setHpr(90, -90, 90)

        if isinstance(self.gag, Actor):
            self.gag.loop('chan')

    def shoot(self, rangeVector):
        if not self.gag:
            return

        rangeNode = NodePath('Shoot Range')
        rangeNode.reparentTo(self.turret.getCannon())
        rangeNode.setScale(render, 1)
        rangeNode.setPos(rangeVector)
        rangeNode.setHpr(90, -90, 90)

        self.gag.setScale(self.gag.getScale(render))
        self.gag.setScale(self.gag.getScale(render))
        self.gag.setPos(self.gag.getPos(render))
        self.gag.reparentTo(render)
        self.gag.setHpr(rangeNode.getHpr(render))

        base.audio3d.attachSoundToObject(self.gagClass.woosh, self.gag)
        self.gagClass.woosh.play()

        self.track = ProjectileInterval(self.gag,
                                        startPos=self.gag.getPos(render),
                                        endPos=rangeNode.getPos(render),
                                        gravityMult=self.gravityMult,
                                        duration=self.duration,
                                        name=self.trackName)
        self.track.setDoneEvent(self.track.getName())
        self.acceptOnce(self.track.getDoneEvent(), self.cleanup)
        self.track.start()

        fireSfx = base.audio3d.loadSfx(
            'phase_4/audio/sfx/MG_cannon_fire_alt.ogg')
        base.audio3d.attachSoundToObject(fireSfx, self.turret.getCannon())
        fireSfx.play()

        if self.turret.isLocal():
            self.buildCollisions()
            self.acceptOnce(self.eventName, self.handleCollision)

    def getGag(self):
        return self.gag

    def buildCollisions(self):
        pieSphere = CollisionSphere(0, 0, 0, 1)
        pieSensor = CollisionNode('turretGagSensor' + str(id(self)))
        pieSensor.addSolid(pieSphere)
        pieNP = self.gag.attachNewNode(pieSensor)
        pieNP.setCollideMask(BitMask32(0))
        pieNP.node().setFromCollideMask(CIGlobals.WallBitmask
                                        | CIGlobals.FloorBitmask)

        event = CollisionHandlerEvent()
        event.set_in_pattern("%fn-into")
        event.set_out_pattern("%fn-out")
        base.cTrav.addCollider(pieNP, event)

    def handleCollision(self, entry):
        messenger.send(self.collideEventName, [entry, self])

    def getID(self):
        return self.gagClass.getID()

    def getCollideEventName(self):
        return self.collideEventName

    def cleanup(self):
        if hasattr(self, 'collideEventName'):
            del self.collideEventName
        if self.track:
            self.track.finish()
            self.track = None
        if self.turret:
            if self.turret.entities and self in self.turret.entities:
                self.turret.entities.remove(self)
            self.turret = None
        self.ignore(self.eventName)
        self.duration = None
        self.gravityMult = None
        self.eventName = None
        self.trackName = None
        if self.gagClass:
            self.gagClass.cleanupGag()
            self.gagClass = None
        if self.gag:
            if isinstance(self.gag, Actor):
                self.gag.cleanup()
            self.gag.removeNode()
            self.gag = None
Esempio n. 18
0
 def do_jump(self):
     map = self.manager.map
     pred = lambda pos: 'jump' in map[pos]['actions']
     field = deque(map.get_jump_field(self.pos))
     if not field:
         return
     pointer = loader.loadModel(S.model('plane'))
     texture = loader.loadTexture(
                 S.texture(S.player['pointer_texture']))
     pointer.setTexture(texture)
     pointer.setTransparency(True)
     pointer.setHpr(0, -90, 0)
     pointer.reparentTo(self.manager.main_node)
     while True:
         pos = field[0]
         pointer.setPos(pos[0], pos[1], 0.1)
         finish_event = S.control_keys['jump'] + '-up'
         left_key = S.control_keys['move_left']
         right_key = S.control_keys['move_right']
         val = yield events(left_key, left_key + '-repeat',
                            right_key, right_key + '-repeat',
                            finish_event, self.must_die_event)
         if val in (self.must_die_event, finish_event):
             break
         elif val in (left_key, left_key + '-repeat'):
             field.rotate(1)
         elif val in (right_key, right_key + '-repeat'):
             field.rotate(-1)
         else:
             raise Exception('Unknown event "{}"'.format(val))
     self.set_move_handlers()
     pointer.removeNode()
     if self.must_die:
         return
     actor = self.actor
     sp = float(self.speed)
     v = pos[0] - self.pos[0], pos[1] - self.pos[1]
     dist = float(hypot(v[0], v[1]))
     angle = (degrees(atan2(v[1], v[0])) + 90) % 360
     anim = actor.getAnimControl('anim')
     anim.setPlayRate(sp / 2)
     wr = S.ch_anim['walk_range']
     anim.loop(True, wr[0], wr[1])
     yield self._rotate_to(angle=angle)
     if not self.walk_pred(pos):
         actor.pose('anim', self.idle_frame)
         return
     map.block(pos)
     wr = S.pl_anim['pre_jump_range']
     interval = actor.actorInterval(
         'anim',
         playRate=S.pl_anim['pre_jump_speed'],
         startFrame=wr[0], endFrame=wr[1]
     )
     yield interval
     interval = ProjectileInterval(actor, (0, 0, 0),
                 (0, 0, 0), 1, gravityMult=S.player['jump_height'])
     interval.start()
     mid_pos = (float(self.pos[0] + pos[0]) / 2,
                float(self.pos[1] + pos[1]) / 2)
     interval = LerpPosInterval(self.node, 0.5, mid_pos + (0,))
     yield interval
     self.pos = pos
     map.unblock(self.pos)
     interval = LerpPosInterval(self.node, 0.5, pos + (0,))
     yield interval
     wr = S.pl_anim['post_jump_range']
     interval = actor.actorInterval(
         'anim',
         playRate=S.pl_anim['post_jump_speed'],
         startFrame=wr[0], endFrame=wr[1]
     )
     yield interval
     yield wait(0.1)
     actor.pose('anim', self.idle_frame)
Esempio n. 19
0
class Myapp(ShowBase):
    
    def __init__(self):
        ShowBase.__init__(self)
        self.accept("escape",sys.exit)
        self.accept("mouse1", self.startShoot)
        self.accept("mouse1-up", self.endShoot)
        
        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        self.heading = 0
        self.pitch = 0
        self.mousex = 0
        self.mousey = 0
        self.flight = []
        self.cs_flight = []
        self.explosion = []
        self.score = 0
        self.life = 20
        self.m1down = 1
         
        self.environ = self.loader.loadModel("models/terrain")
        self.environ.reparentTo(self.render)
        self.environ.setScale(0.8, 0.8, 0.8)
        self.environ.setPos(0,0,-10)
        self.environ.setHpr(-90,0,0)
        
        for k in range(0,5):
            self.flight.append(self.loader.loadModel("models/spitfire"))
            self.flight[k].reparentTo(self.render)
            self.flight[k].setScale(0.1, 0.1, 0.1)
            self.flight[k].setPos(randint(-40,20), randint(300,400),randint(10,20))
            self.cs_flight.append( self.flight[k].attachNewNode(CollisionNode(str(k))))
            self.cs_flight[k].node().addSolid(CollisionSphere(0,0,5,30))
            #self.cs_flight[k].show()
            self.flight[k].setCollideMask(BitMask32.bit(1))
        
        self.bullets = [] 
        
        self.crosshair = OnscreenImage(image = 'models/crosshair.png', pos = (0,0,0))
        self.crosshair.setScale(0.03,0.03,0.03)
        self.crosshair.setTransparency(TransparencyAttrib.MAlpha) 
        self.title = OnscreenText(" ",
                              style=1, fg=(1,1,1,1),
                              pos=(0,0), scale = .07)
        
        self.taskMgr.add(self.mouse_control, "mouse_control")
        self.taskMgr.add(self.update_flight, "update_flight")

        self.picker = CollisionTraverser()
        self.pq = CollisionHandlerQueue() 

        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(BitMask32.bit(1))

        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.picker.addCollider(self.pickerNP,self.pq)   
        
        self.gun = OnscreenImage(image = 'models/gun.png', pos = (0.24, 0, -0.54)) 
        self.gun.setScale(1,0.6,0.6)
        self.gun.setTransparency(TransparencyAttrib.MAlpha)
        
        self.sound = base.loader.loadSfx("models/sound.ogg")
    
        base.setFrameRateMeter(True)
           
    def mouse_control(self,task):
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        if base.win.movePointer(0, 100, 100):
            self.heading = self.heading - (x - 100) * 0.1
            self.pitch = self.pitch - (y - 100) * 0.1
        if (self.pitch < -10): self.pitch = -10
        if (self.pitch >  20): self.pitch =  20
        if (self.heading < -40): self.heading = -40
        if (self.heading >  30): self.heading =  30
        base.camera.setHpr(self.heading,self.pitch,0)

        return Task.cont

    def update_flight(self,task):
        i = 0
        while(i<len(self.flight)):
            x = self.flight[i].getY()
            if x<-3:
                self.flight[i].setPos(randint(-40,20), randint(200,300),randint(10,20))
                if(self.life ==0):
                    self.game_end()
                else:
                    self.life -= 1
            else:
                x -= 0.7
                self.flight[i].setPos(self.flight[i].getX(), x, self.flight[i].getZ())
            i+=1
        self.title.destroy()
        self.title = OnscreenText(text='Life: ' + str(self.life)+' Score: '+str(self.score),
                              style=1, fg=(1,1,1,1),
                              pos=(-1.5,0.9), scale = .07)
        return Task.cont
               
    def removeBullet(self,task):
        if len(self.bullets) < 1: return
        self.bulletNP = self.bullets.pop(0)
        self.bulletNP.removeNode()
        return task.done
             
    def shootBullet(self,task):
        self.ball = self.loader.loadModel("models/bullet")
        self.ball.reparentTo(self.render)
        self.ball.setScale(0.02,0.02,0.02)
        self.ball.setPos(0,0,0) 
        self.bullets.append(self.ball)
        self.bt = ProjectileInterval(self.ball,
                                     startPos = Point3(0,0,-5),
                                     endPos = Point3(self.heading * -2 , 100 , self.pitch*2), duration = 0.3 ,
                                     gravityMult = -2 )    
        self.bt.start()
        self.taskMgr.doMethodLater(0.3, self.removeBullet, 'removeBullet')
        self.hit_flight()
        if(self.m1down):
            self.taskMgr.doMethodLater(0.2, self.shootBullet, 'shootbullet')

    def hit_flight(self):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
            self.pickerRay.setFromLens(base.camNode,0,0)
            self.picker.traverse(render)
            if self.pq.getNumEntries() > 0:
                self.pq.sortEntries()
                pickedObj = self.pq.getEntry(0).getIntoNodePath()
                if pickedObj.getName() != 'CINEMA4D_Mesh' :
                    k = int(pickedObj.getName())
                    self.score += 1
                    self.explode(self.flight[k].getX(),self.flight[k].getY(),self.flight[k].getZ())
                    self.flight[k].setPos(randint(-40,20), randint(200,300),randint(10,20))
    
    def game_end(self):
        self.crosshair.remove()
        self.gov = OnscreenText("Game Over",
                              style=1, fg=(1,1,1,1),
                              pos=(0,0), scale = 0.07)
        self.taskMgr.remove("mouse_control")
        self.taskMgr.remove("update_flight")
        #self.explode(20,20,20)
        p = open('score.txt','r')
        score = p.readline()
        p.close()
        if(self.score > int(score)):
            p = open('score.txt','w')
            p.write(str(self.score))
            p.close()


    def explode(self,x,y,z):
        k = len(self.explosion) 
        self.explosion.append(loader.loadModel('explosion/flip.egg'))
        self.explosion[k].reparentTo(self.render)
        self.explosion[k].setPos(x,y,z)
        self.explosion[k].setScale(5,5,5)
        self.taskMgr.doMethodLater(0.6, self.removeExplosion, 'removeExp')  
        
    def removeExplosion(self,task):
        if len(self.explosion) < 1: return
        self.explosion[0].removeNode()
        del self.explosion[0]
        return task.done

    def endShoot(self):
        self.m1down = 0
        self.sound.stop()
     
    def startShoot(self):
        self.sound.play()
        self.m1down = 1
        self.taskMgr.doMethodLater(0.1, self.shootBullet, 'shootbullet')
Esempio n. 20
0
class Suit(Avatar.Avatar):
	healthColors = (Vec4(0, 1, 0, 1),
		Vec4(1, 1, 0, 1),
		Vec4(1, 0.5, 0, 1),
		Vec4(1, 0, 0, 1),
		Vec4(0.3, 0.3, 0.3, 1))
	healthGlowColors = (Vec4(0.25, 1, 0.25, 0.5),
		Vec4(1, 1, 0.25, 0.5),
		Vec4(1, 0.5, 0.25, 0.5),
		Vec4(1, 0.25, 0.25, 0.5),
		Vec4(0.3, 0.3, 0.3, 0))
	medallionColors = {'c': Vec4(0.863, 0.776, 0.769, 1.0),
		's': Vec4(0.843, 0.745, 0.745, 1.0),
		'l': Vec4(0.749, 0.776, 0.824, 1.0),
		'm': Vec4(0.749, 0.769, 0.749, 1.0)}
	health2DmgMultiplier = 2.5
	
	def __init__(self):
		try:
			self.Suit_initialized
			return
		except:
			self.Suit_initialized = 1
		
		Avatar.Avatar.__init__(self)
		self.avatarType = CIGlobals.Suit
		self.name = ''
		self.chat = ''
		self.suit = None
		self.suitHeads = None
		self.suitHead = None
		self.loserSuit = None
		self.healthMeterGlow = None
		self.healthMeter = None
		self.weapon = None
		self.weapon_sfx = None
		self.anim = None
		self.suit_dial = None
		self.shadow = None
		self.balloon_sfx = None
		self.add_sfx = None
		self.explosion = None
		self.largeExp = None
		self.smallExp = None
		self.death_sfx = None
		self.attack = None
		self.wtrajectory = None
		self.throwObjectId = None
		self.hasSpawned = False
		self.condition = 0
		self.type = ""
		self.head = ""
		self.team = ""
		self.isSkele = 0
		self.animFSM = ClassicFSM('Suit', [State('off', self.enterOff, self.exitOff),
								State('neutral', self.enterNeutral, self.exitNeutral),
								State('walk', self.enterWalk, self.exitWalk),
								State('die', self.enterDie, self.exitDie),
								State('attack', self.enterAttack, self.exitAttack),
								State('flydown', self.enterFlyDown, self.exitFlyDown),
								State('pie', self.enterPie, self.exitPie),
								State('win', self.enterWin, self.exitWin),
								State('flyaway', self.enterFlyAway, self.exitFlyAway),
								State('rollodex', self.enterRollodex, self.exitRollodex)], 'off', 'off')
		animStateList = self.animFSM.getStates()
		self.animFSM.enterInitialState()
		
		self.initializeBodyCollisions()
		
	def delete(self):
		try:
			self.Suit_deleted
		except:
			self.Suit_deleted = 1
			if self.suit:
				self.cleanupSuit()
			if self.loserSuit:
				self.cleanupLoserSuit()
			if self.suitHeads:
				self.suitHeads.remove()
				self.suitHeads = None
			if self.suitHead:
				self.suitHead.remove()
				self.suitHead = None
			if self.healthMeterGlow:
				self.healthMeterGlow.remove()
				self.healthMeterGlow = None
			if self.healthMeter:
				self.healthMeter.remove()
				self.healthMeter = None
			if self.shadow:
				self.shadow.remove()
				self.shadow = None
			self.weapon = None
			self.weapon_sfx = None
			self.suit_dial = None
			del self.shadowPlacer
			
	def generateSuit(self, suitType, suitHead, suitTeam, suitHealth, skeleton):
		self.health = suitHealth
		self.maxHealth = suitHealth
		self.generateBody(suitType, suitTeam, suitHead, skeleton)
		self.generateHealthMeter()
		self.generateHead(suitType, suitHead)
		self.setupNameTag()
		Avatar.Avatar.initShadow(self)
		
	def generateBody(self, suitType, suitTeam, suitHead, skeleton):
		if self.suit:
			self.cleanupSuit()
			
		self.team = suitTeam
		self.type = suitType
		self.head = suitHead
		self.isSkele = skeleton
		
		if suitType == "A":
			if skeleton:
				self.suit = Actor("phase_5/models/char/cogA_robot-zero.bam")
			else:
				self.suit = Actor("phase_3.5/models/char/suitA-mod.bam")
			self.suit.loadAnims({"neutral": "phase_4/models/char/suitA-neutral.bam",
							"walk": "phase_4/models/char/suitA-walk.bam",
							"pie": "phase_4/models/char/suitA-pie-small.bam",
							"land": "phase_5/models/char/suitA-landing.bam",
							"throw-object": "phase_5/models/char/suitA-throw-object.bam",
							"throw-paper": "phase_5/models/char/suitA-throw-paper.bam",
							"glower": "phase_5/models/char/suitA-glower.bam",
							"win": "phase_4/models/char/suitA-victory.bam",
							"rollodex": "phase_5/models/char/suitA-roll-o-dex.bam"})
		if suitType == "B":
			if skeleton:
				self.suit = Actor("phase_5/models/char/cogB_robot-zero.bam")
			else:
				self.suit = Actor("phase_3.5/models/char/suitB-mod.bam")
			self.suit.loadAnims({"neutral": "phase_4/models/char/suitB-neutral.bam",
							"walk": "phase_4/models/char/suitB-walk.bam",
							"pie": "phase_4/models/char/suitB-pie-small.bam",
							"land": "phase_5/models/char/suitB-landing.bam",
							"throw-object": "phase_5/models/char/suitB-throw-object.bam",
							"throw-paper": "phase_5/models/char/suitB-throw-paper.bam",
							"glower": "phase_5/models/char/suitB-magic1.bam",
							"win": "phase_4/models/char/suitB-victory.bam",
							"rollodex": "phase_5/models/char/suitB-roll-o-dex.bam"})
		if suitType == "C":
			if skeleton:
				self.suit = Actor("phase_5/models/char/cogC_robot-zero.bam")
			else:
				self.suit = Actor("phase_3.5/models/char/suitC-mod.bam")
			self.suit.loadAnims({"neutral": "phase_3.5/models/char/suitC-neutral.bam",
						"walk": "phase_3.5/models/char/suitC-walk.bam",
						"pie": "phase_3.5/models/char/suitC-pie-small.bam",
						"land": "phase_5/models/char/suitC-landing.bam",
						"throw-object": "phase_3.5/models/char/suitC-throw-paper.bam",
						"throw-paper": "phase_3.5/models/char/suitC-throw-paper.bam",
						"glower": "phase_5/models/char/suitC-glower.bam",
						"win": "phase_4/models/char/suitC-victory.bam"})
		if skeleton:
			self.suit.setTwoSided(1)
		self.suit.getGeomNode().setScale(CIGlobals.SuitScales[suitHead] / CIGlobals.SuitScaleFactors[suitType])
		
		if skeleton:
			if suitTeam == "s":
				self.suit_tie = loader.loadTexture("phase_5/maps/cog_robot_tie_sales.jpg")
			elif suitTeam == "m":
				self.suit_tie = loader.loadTexture("phase_5/maps/cog_robot_tie_money.jpg")
			elif suitTeam == "l":
				self.suit_tie = loader.loadTexture("phase_5/maps/cog_robot_tie_legal.jpg")
			elif suitTeam == "c":
				self.suit_tie = loader.loadTexture("phase_5/maps/cog_robot_tie_boss.jpg")
			self.suit.find('**/tie').setTexture(self.suit_tie, 1)
		else:
			self.suit_blazer = loader.loadTexture("phase_3.5/maps/" + suitTeam + "_blazer.jpg")
			self.suit_leg = loader.loadTexture("phase_3.5/maps/" + suitTeam + "_leg.jpg")
			self.suit_sleeve = loader.loadTexture("phase_3.5/maps/" + suitTeam + "_sleeve.jpg")
			
			self.suit.find('**/legs').setTexture(self.suit_leg, 1)
			self.suit.find('**/arms').setTexture(self.suit_sleeve, 1)
			self.suit.find('**/torso').setTexture(self.suit_blazer, 1)
		
			if suitHead == "coldcaller":
				self.suit.find('**/hands').setColor(0.55, 0.65, 1.0, 1.0)
			elif suitHead == "corporateraider":
				self.suit.find('**/hands').setColor(0.85, 0.55, 0.55, 1.0)
			elif suitHead == "bigcheese":
				self.suit.find('**/hands').setColor(0.75, 0.95, 0.75, 1.0)
			elif suitHead == "bloodsucker":
				self.suit.find('**/hands').setColor(0.95, 0.95, 1.0, 1.0)
			elif suitHead == "spindoctor":
				self.suit.find('**/hands').setColor(0.5, 0.8, 0.75, 1.0)
			elif suitHead == "legaleagle":
				self.suit.find('**/hands').setColor(0.25, 0.25, 0.5, 1.0)
			elif suitHead == "pennypincher":
				self.suit.find('**/hands').setColor(1.0, 0.5, 0.6, 1.0)
			elif suitHead == "loanshark":
				self.suit.find('**/hands').setColor(0.5, 0.85, 0.75, 1.0)
			else:
				self.suit.find('**/hands').setColor(CIGlobals.SuitHandColors[suitTeam])
		
		self.suit.reparentTo(self)
		
	def generateHead(self, suitType, suitHead):
		if self.suitHead:
			self.cleanupSuitHead()
			
		self.type = suitType
		self.head = suitHead
		
		if suitHead == "vp":
			self.suitHead = Actor("phase_9/models/char/sellbotBoss-head-zero.bam",
								{"neutral": "phase_9/models/char/bossCog-head-Ff_neutral.bam"})
			self.suitHead.setTwoSided(True)
			self.suitHead.loop("neutral")
			self.suitHead.setScale(0.35)
			self.suitHead.setHpr(270, 0, 270)
			self.suitHead.setZ(-0.10)
		else:
			if suitType == "A" or suitType == "B":
				self.suitHeads = loader.loadModel("phase_4/models/char/suit" + suitType + "-heads.bam")
			else:
				self.suitHeads = loader.loadModel("phase_3.5/models/char/suit" + suitType + "-heads.bam")
			self.suitHead = self.suitHeads.find('**/' + CIGlobals.SuitHeads[suitHead])
			if suitHead == "flunky":
				glasses = self.suitHeads.find('**/glasses')
				glasses.reparentTo(self.suitHead)
				glasses.setTwoSided(True)
			if suitHead in CIGlobals.SuitSharedHeads:
				if suitHead == "coldcaller":
					self.suitHead.setColor(0.25, 0.35, 1.0, 1.0)
				else:
					headTexture = loader.loadTexture("phase_3.5/maps/" + suitHead + ".jpg")
					self.suitHead.setTexture(headTexture, 1)
		if not self.isSkele:
			self.suitHead.reparentTo(self.suit.find('**/joint_head'))
			
	def cleanupSuit(self):
		if self.shadow:
			self.shadow.remove()
			self.shadow = None
		self.removeHealthBar()
		self.suit.cleanup()
		self.suit = None
		
	def cleanupSuitHead(self):
		if self.suitHeads:
			self.suitHeads.remove()
			self.suitHeads = None
		if self.suitHead:
			self.suitHead.remove()
			self.suitHead = None
		
	def cleanupLoserSuit(self):
		if self.explosion:
			self.explosion.remove()
			self.explosion = None
		if self.smallExp:
			self.smallExp = None
		if self.largeExp:
			self.largeExp.cleanup()
			self.largeExp = None
		if self.loserSuit:
			self.loserSuit.cleanup()
			self.loserSuit = None
		
	def setName(self, nameString, charName):
		Avatar.Avatar.setName(self, nameString, avatarType=self.avatarType, charName=charName)
		
	def setChat(self, chatString):
		self.chat = chatString
		if self.isSkele:
			if "?" in chatString:
				self.suit_dial = audio3d.loadSfx("phase_5/audio/sfx/Skel_COG_VO_question.ogg")
			elif "!" in chatString:
				self.suit_dial = audio3d.loadSfx("phase_5/audio/sfx/Skel_COG_VO_grunt.ogg")
			else:
				self.suit_dial = audio3d.loadSfx("phase_5/audio/sfx/Skel_COG_VO_statement.ogg")
		elif self.head == "vp":
			if "?" in chatString:
				self.suit_dial = audio3d.loadSfx("phase_9/audio/sfx/Boss_COG_VO_question.ogg")
			elif "!" in chatString:
				self.suit_dial = audio3d.loadSfx("phase_9/audio/sfx/Boss_COG_VO_grunt.ogg")
			else:
				self.suit_dial = audio3d.loadSfx("phase_9/audio/sfx/Boss_COG_VO_statement.ogg")
		else:
			if "?" in chatString:
				self.suit_dial = audio3d.loadSfx("phase_3.5/audio/dial/COG_VO_question.ogg")
			elif "!" in chatString:
				self.suit_dial = audio3d.loadSfx("phase_3.5/audio/dial/COG_VO_grunt.ogg")
			else:
				self.suit_dial = audio3d.loadSfx("phase_3.5/audio/dial/COG_VO_statement.ogg")
		if self.isSkele:
			audio3d.attachSoundToObject(self.suit_dial, self.suit)
		else:
			audio3d.attachSoundToObject(self.suit_dial, self.suitHead)
		self.suit_dial.play()
		Avatar.Avatar.setChat(self, chatString)
		
	def generateHealthMeter(self):
		self.removeHealthBar()
		model = loader.loadModel("phase_3.5/models/gui/matching_game_gui.bam")
		button = model.find('**/minnieCircle')
		button.setScale(3.0)
		button.setH(180)
		button.setColor(self.healthColors[0])
		chestNull = self.suit.find('**/def_joint_attachMeter')
		if chestNull.isEmpty():
			chestNull = self.suit.find('**/joint_attachMeter')
		button.reparentTo(chestNull)
		self.healthBar = button
		glow = loader.loadModel("phase_3.5/models/props/glow.bam")
		glow.reparentTo(self.healthBar)
		glow.setScale(0.28)
		glow.setPos(-0.005, 0.01, 0.015)
		glow.setColor(self.healthGlowColors[0])
		button.flattenLight()
		self.healthBarGlow = glow
		self.condition = 0
		
	def updateHealthBar(self, hp):
		if hp > self.hp:
			self.hp = hp
		self.hp -= hp
		health = float(self.health) / float(self.maxHP)
		if health > 0.95:
			condition = 0
		elif health > 0.7:
			condition = 1
		elif health > 0.3:
			condition = 2
		elif health > 0.05:
			condition = 3
		elif health > 0.0:
			condition = 4
		else:
			condition = 5
			
		if self.condition != condition:
			if condition == 4:
				blinkTask = Task.loop(Task(self.__blinkRed), Task.pause(0.75), Task(self.__blinkGray), Task.pause(0.1))
				taskMgr.add(blinkTask, self.taskName('blink-task'))
			elif condition == 5:
				if self.condition == 4:
					taskMgr.remove(self.taskName('blink-task'))
				blinkTask = Task.loop(Task(self.__blinkRed), Task.pause(0.25), Task(self.__blinkGray), Task.pause(0.1))
				taskMgr.add(blinkTask, self.taskName('blink-task'))
			else:
				self.healthBar.setColor(self.healthColors[condition], 1)
				self.healthBarGlow.setColor(self.healthGlowColors[condition], 1)
			self.condition = condition
			
	def __blinkRed(self, task):
		self.healthBar.setColor(self.healthColors[3], 1)
		self.healthBarGlow.setColor(self.healthGlowColors[3], 1)
		if self.condition == 5:
			self.healthBar.setScale(1.17)
		return Task.done
		
	def __blinkGray(self, task):
		if not self.healthBar:
			return
		self.healthBar.setColor(self.healthColors[4], 1)
		self.healthBarGlow.setColor(self.healthGlowColors[4], 1)
		if self.condition == 5:
			self.healthBar.setScale(1.0)
		return Task.done
		
	def removeHealthBar(self):
		if self.healthMeter:
			self.healthBar.removeNode()
			self.healthBar = None
		if self.condition == 4 or self.condition == 5:
			taskMgr.remove(self.taskName('blink-task'))
		self.healthCondition = 0
		return
			
	def enterOff(self):
		self.anim = None
		return
		
	def exitOff(self):
		pass
		
	def exitGeneral(self):
		self.suit.stop()
		
	def enterNeutral(self):
		self.suit.loop("neutral")
		
	def exitNeutral(self):
		self.exitGeneral()
		
	def enterRollodex(self):
		self.suit.play("rollodex")
		
	def exitRollodex(self):
		self.exitGeneral()
		
	def enterWalk(self):
		self.suit.loop("walk")
		
	def exitWalk(self):
		self.exitGeneral()
		
	def generateLoserSuit(self):
		self.cleanupLoserSuit()
		if self.type == "A":
			if self.isSkele:
				self.loserSuit = Actor("phase_5/models/char/cogA_robot-lose-mod.bam")
			else:
				self.loserSuit = Actor("phase_4/models/char/suitA-lose-mod.bam")
			self.loserSuit.loadAnims({"lose": "phase_4/models/char/suitA-lose.bam"})
		if self.type == "B":
			if self.isSkele:
				self.loserSuit = Actor("phase_5/models/char/cogB_robot-lose-mod.bam")
			else:
				self.loserSuit = Actor("phase_4/models/char/suitB-lose-mod.bam")
			self.loserSuit.loadAnims({"lose": "phase_4/models/char/suitB-lose.bam"})
		if self.type == "C":
			if self.isSkele:
				self.loserSuit = Actor("phase_5/models/char/cogC_robot-lose-mod.bam")
			else:
				self.loserSuit = Actor("phase_3.5/models/char/suitC-lose-mod.bam")
			self.loserSuit.loadAnims({"lose": "phase_3.5/models/char/suitC-lose.bam"})
		if self.isSkele:
			self.loserSuit.find('**/tie').setTexture(self.suit_tie, 1)
			self.loserSuit.setTwoSided(1)
		else:
			self.loserSuit.find('**/hands').setColor(self.suit.find('**/hands').getColor())
			self.loserSuit.find('**/legs').setTexture(self.suit_leg, 1)
			self.loserSuit.find('**/arms').setTexture(self.suit_sleeve, 1)
			self.loserSuit.find('**/torso').setTexture(self.suit_blazer, 1)
		self.loserSuit.getGeomNode().setScale(self.suit.getScale())
		self.loserSuit.reparentTo(self)
		if not self.isSkele:
			self.suitHead.reparentTo(self.loserSuit.find('**/joint_head'))
		self.loserSuit.setPos(self.suit.getPos(render))
		self.loserSuit.setHpr(self.suit.getHpr(render))
		self.cleanupSuit()
		Avatar.Avatar.initShadow(self, self.avatarType)
		self.loserSuit.reparentTo(render)
		
	def enterDie(self):
		self.generateLoserSuit()
		self.state = "dead"
		self.loserSuit.play("lose")
		spinningSound = base.loadSfx("phase_3.5/audio/sfx/Cog_Death.ogg")
		deathSound = base.loadSfx("phase_3.5/audio/sfx/ENC_cogfall_apart.ogg")
		#audio3d.attachSoundToObject(spinningSound, self.loserSuit)
		#audio3d.attachSoundToObject(deathSound, self.loserSuit)
		Sequence(Wait(0.8), SoundInterval(spinningSound, duration=1.2, startTime=1.5, volume=0.4, node=self.loserSuit),
			SoundInterval(spinningSound, duration=3.0, startTime=0.6, volume=2.0, node=self.loserSuit),
			SoundInterval(deathSound, volume=0.32, node=self.loserSuit)).start()
		Sequence(Wait(0.8), Func(self.smallDeathParticles), Wait(4.2), Func(self.suitExplode),
				Wait(1.0), Func(self.delSuit)).start()
		
	def smallDeathParticles(self):
		self.smallExp = ParticleLoader.loadParticleEffect("phase_3.5/etc/gearExplosionSmall.ptf")
		self.smallExp.start(self.loserSuit)
		
	def suitExplode(self):
		self.smallExp.cleanup()
		self.largeExp = ParticleLoader.loadParticleEffect("phase_3.5/etc/gearExplosion.ptf")
		self.largeExp.start(self.loserSuit)
		self.explosion = loader.loadModel("phase_3.5/models/props/explosion.bam")
		self.explosion.setScale(0.5)
		self.explosion.reparentTo(render)
		self.explosion.setBillboardPointEye()
		if self.isSkele:
			self.explosion.setPos(self.loserSuit.find('**/joint_head').getPos(render) + (0, 0, 2))
		else:
			self.explosion.setPos(self.suitHead.getPos(render) + (0,0,2))
		
	def delSuit(self):
		self.cleanupLoserSuit()
		self.disableBodyCollisions()
		
	def exitDie(self):
		pass
		
	def enterFlyDown(self):
		self.fd_sfx = audio3d.loadSfx("phase_5/audio/sfx/ENC_propeller_in.ogg")
		self.prop = Actor("phase_4/models/props/propeller-mod.bam",
						{"chan": "phase_4/models/props/propeller-chan.bam"})
		audio3d.attachSoundToObject(self.fd_sfx, self.prop)
		self.fd_sfx.play()
		self.prop.reparentTo(self.suit.find('**/joint_head'))
		propTrack = Sequence(Func(self.prop.loop, 'chan', fromFrame=0, toFrame=3),
							Wait(1.75),
							Func(self.prop.play, 'chan', fromFrame=3))
		propTrack.start()
		if not self.hasSpawned:
			showSuit = Task.sequence(Task(self.hideSuit), Task.pause(0.3), Task(self.showSuit))
			taskMgr.add(showSuit, "showsuit")
			self.hasSpawned = True
		dur = self.suit.getDuration('land')
		suitTrack = Sequence(Func(self.suit.pose, 'land', 0),
							Wait(1.9),
							ActorInterval(self.suit, 'land', duration=dur))
		suitTrack.start()
		
	def hideSuit(self, task):
		self.hide()
		return Task.done
	
	def showSuit(self, task):
		self.show()
		fadeIn = Sequence(Func(self.setTransparency, 1), self.colorScaleInterval(0.6, colorScale=Vec4(1,1,1,1), startColorScale=Vec4(1,1,1,0)), Func(self.clearColorScale), Func(self.clearTransparency), Func(self.reparentTo, render))
		fadeIn.start()
		return Task.done
		
	def initializeLocalCollisions(self, name):
		Avatar.Avatar.initializeLocalCollisions(self, 1, 3, name)
		
	def initializeBodyCollisions(self):
		Avatar.Avatar.initializeBodyCollisions(self, self.avatarType, 2.25, 1, 4, 2)
		self.initializeRay(self.avatarType)
		self.collTube.setTangible(0)
		
	def deleteBean(self):
		if self.bean:
			self.bean.remove_node()
			self.bean = None
			
	def createJellyBean(self):
		self.deleteBean()
		money = int(self.maxHP / CIGlobals.SuitAttackDamageFactors['clipontie'])
		if money == 1:
			self.bean = loader.loadModel("phase_5.5/models/estate/jellyBean.bam")
			self.bean.set_two_sided(True)
			random_r = random.uniform(0, 1)
			random_g = random.uniform(0, 1)
			random_b = random.uniform(0, 1)
			self.bean.set_color(random_r, random_g, random_b, 1)
		else:
			self.bean = loader.loadModel("phase_5.5/models/estate/jellybeanJar.bam")
		self.bean.reparent_to(render)
		self.bean.set_pos(self.get_pos(render) + (0, 0, 1))
		bean_int = self.bean.hprInterval(1,
										Point3(360, 0, 0),
										startHpr=(0, 0, 0))
		bean_int.loop()
		
	def exitFlyDown(self):
		audio3d.detachSound(self.fd_sfx)
		self.prop.cleanup()
		self.prop = None
		
	def enterFlyAway(self):
		self.fa_sfx = audio3d.loadSfx("phase_5/audio/sfx/ENC_propeller_out.ogg")
		self.prop = Actor("phase_4/models/props/propeller-mod.bam",
						{"chan": "phase_4/models/props/propeller-chan.bam"})
		audio3d.attachSoundToObject(self.fa_sfx, self.prop)
		self.fa_sfx.play()
		self.prop.reparentTo(self.suit.find('**/joint_head'))
		self.prop.setPlayRate(-1.0, "chan")
		propTrack = Sequence(Func(self.prop.play, 'chan', fromFrame=3),
							Wait(1.75),
							Func(self.prop.play, 'chan', fromFrame=0, toFrame=3))
		propTrack.start()
		self.suit.setPlayRate(-1.0, 'land')
		self.suit.play('land')
		
	def exitFlyAway(self):
		audio3d.detachSound(self.fa_sfx)
		self.prop.cleanup()
		self.prop = None
		
	def enterAttack(self, attack):
		self.attack = attack
		
		self.weapon_state = 'start'
		
		if attack == "canned":
			self.weapon = loader.loadModel("phase_5/models/props/can.bam")
			self.weapon.setScale(15)
			self.weapon.setR(180)
			self.wss = CollisionSphere(0,0,0,0.05)
		elif attack == "clipontie":
			self.weapon = loader.loadModel("phase_5/models/props/power-tie.bam")
			self.weapon.setScale(4)
			self.weapon.setR(180)
			self.wss = CollisionSphere(0,0,0,0.2)
		elif attack == "sacked":
			self.weapon = loader.loadModel("phase_5/models/props/sandbag-mod.bam")
			self.weapon.setScale(2)
			self.weapon.setR(180)
			self.weapon.setP(90)
			self.weapon.setY(-2.8)
			self.weapon.setZ(-0.3)
			self.wss = CollisionSphere(0,0,0,1)
		elif attack == "playhardball":
			self.weapon = loader.loadModel("phase_5/models/props/baseball.bam")
			self.weapon.setScale(10)
			self.wss = CollisionSphere(0,0,0,0.1)
			self.weapon.setZ(-0.5)
		elif attack == "marketcrash":
			self.weapon = loader.loadModel("phase_5/models/props/newspaper.bam")
			self.weapon.setScale(3)
			self.weapon.setPos(0.41, -0.06, -0.06)
			self.weapon.setHpr(90, 0, 270)
			self.wss = CollisionSphere(0,0,0,0.35)
		elif attack == "glowerpower":
			self.weapon = loader.loadModel("phase_5/models/props/dagger.bam")
			self.wss = CollisionSphere(0,0,0,1)
		else:
			notify.warning("unknown attack!")
			
		self.throwObjectId = random.uniform(0, 101010101010)
		
		if attack == "canned" or attack == "playhardball":
			self.weapon.reparentTo(self.suit.find('**/joint_Rhold'))
			if self.type == "C":
				taskMgr.doMethodLater(2.2, self.throwObject, "throwObject" + str(self.throwObjectId))
			else:
				taskMgr.doMethodLater(3, self.throwObject, "throwObject" + str(self.throwObjectId))
			self.suit.play("throw-object")
		elif attack == "clipontie" or attack == "marketcrash" or attack == "sacked":
			self.weapon.reparentTo(self.suit.find('**/joint_Rhold'))
			if self.type == "C":
				taskMgr.doMethodLater(2.2, self.throwObject, "throwObject" + str(self.throwObjectId))
			else:
				taskMgr.doMethodLater(3, self.throwObject, "throwObject" + str(self.throwObjectId))
			self.suit.play("throw-paper")
		elif attack == "glowerpower":
			taskMgr.doMethodLater(1, self.throwObject, "throwObject" + str(self.throwObjectId))
			self.suit.play("glower")
		self.weaponSensorId = random.uniform(0, 1010101010101001)
		wsnode = CollisionNode('weaponSensor' + str(self.weaponSensorId))
		wsnode.addSolid(self.wss)
		self.wsnp = self.weapon.attachNewNode(wsnode)
		if attack == "sacked":
			self.wsnp.setZ(1)
		elif attack == "marketcrash":
			self.wsnp.setPos(-0.25, 0.3, 0)
			
	def delWeapon(self, task):
		if self.weapon:
			self.weapon.removeNode()
			self.weapon = None
		return task.done
		
	def interruptAttack(self):
		if self.wtrajectory:
			if self.wtrajectory.isStopped():
				if self.weapon:
					self.weapon.removeNode()
					self.weapon = None
		if self.throwObjectId:
			taskMgr.remove("throwObject" + str(self.throwObjectId))
		
	def handleWeaponTouch(self):
		if not self.attack == "glowerpower" or not self.attack == "clipontie":
			if self.weapon_sfx:
				self.weapon_sfx.stop()
		try: self.wtrajectory.pause()
		except: pass
		if self.weapon:
			self.weapon.removeNode()
			self.weapon = None
		
	def weaponCollisions(self):
		self.wsnp.setCollideMask(BitMask32(0))
		self.wsnp.node().setFromCollideMask(CIGlobals.EventBitmask)
			
		event = CollisionHandlerEvent()
		event.setInPattern("%fn-into")
		event.setOutPattern("%fn-out")
		base.cTrav.addCollider(self.wsnp, event)
		
	def throwObject(self, task):
		self.playWeaponSound()
		
		self.weaponNP = NodePath("weaponNP")
		self.weaponNP.setScale(render, 1)
		try: self.weaponNP.reparentTo(self.find('**/joint_nameTag'))
		except: return task.done
		self.weaponNP.setPos(0, 50, 0)
		self.weaponNP.setHpr(0, 0, 0)
		
		if self.weapon:
			self.weapon.setScale(self.weapon.getScale(render))
		try: self.weapon.reparentTo(render)
		except: return task.done
		
		self.weapon.setPos(0,0,0)
		self.weapon.setHpr(0,0,0)
		
		if self.attack == "glowerpower":
			self.weapon.setH(self.weaponNP.getH(render))
			self.wtrajectory = self.weapon.posInterval(0.5,
										Point3(self.weaponNP.getPos(render)),
										startPos=(self.getX(render), self.getY(render) + 3, self.find('**/joint_head').getZ(render)))
			self.wtrajectory.start()
		else:
			self.wtrajectory = ProjectileInterval(self.weapon,
										startPos = (self.suit.find('**/joint_Rhold').getPos(render)),
										endPos = self.weaponNP.getPos(render),
										gravityMult = 0.7, duration = 1)
			self.wtrajectory.start()
		if self.attack == "glowerpower":
			taskMgr.doMethodLater(0.5, self.delWeapon, "delWeapon")
		else:
			taskMgr.doMethodLater(1, self.delWeapon, "delWeapon")
		self.weapon_state = 'released'
		
	def playWeaponSound(self):
		if self.attack == "glowerpower":
			self.weapon_sfx = audio3d.loadSfx("phase_5/audio/sfx/SA_glower_power.ogg")
		elif self.attack == "canned":
			self.weapon_sfx = audio3d.loadSfx("phase_5/audio/sfx/SA_canned_tossup_only.ogg")
		elif self.attack == "clipontie":
			self.weapon_sfx = audio3d.loadSfx("phase_5/audio/sfx/SA_powertie_throw.ogg")
		elif self.attack == "sacked":
			self.weapon_sfx = audio3d.loadSfx("phase_5/audio/sfx/SA_canned_tossup_only.ogg")
		elif self.attack == "playhardball":
			self.weapon_sfx = audio3d.loadSfx("phase_5/audio/sfx/SA_canned_tossup_only.ogg")
		elif self.attack == "marketcrash":
			self.weapon_sfx = audio3d.loadSfx("phase_5/audio/sfx/SA_canned_tossup_only.ogg")
		if self.weapon:
			audio3d.attachSoundToObject(self.weapon_sfx, self.weapon)
			self.weapon_sfx.play()
			
	def exitAttack(self):
		pass
		
	def enterPie(self):
		self.suit.play("pie")
		
	def exitPie(self):
		self.exitGeneral()
		
	def enterWin(self):
		self.suit.play("win")
		
	def exitWin(self):
		self.exitGeneral()
Esempio n. 21
0
    def getTossPieInterval(self,
                           toon,
                           x,
                           y,
                           z,
                           h,
                           p,
                           r,
                           power,
                           beginFlyIval=Sequence()):
        """Adapted from toon.py to suit our needs.
        Returns (toss, pie, flyPie), where toss is an interval to
        animate the toon tossing a pie, pie is the interval to
        animate the pie flying through the air, and pieModel is the
        model that flies.  This is used in the final BossBattle
        sequence of CogHQ when we all throw pies directly at the
        boss cog.
        """

        from toontown.toonbase import ToontownBattleGlobals
        from toontown.battle import BattleProps

        pie = toon.getPieModel()
        pie.setScale(0.5)
        flyPie = pie.copyTo(NodePath('a'))
        pieName = ToontownBattleGlobals.pieNames[toon.pieType]
        pieType = BattleProps.globalPropPool.getPropType(pieName)
        animPie = Sequence()
        if pieType == 'actor':
            animPie = ActorInterval(pie, pieName, startFrame=48)

        sound = loader.loadSfx('phase_3.5/audio/sfx/AA_pie_throw_only.mp3')

        # First, create a ProjectileInterval to compute the relative
        # velocity.

        assert 0 <= power <= 100, "invalid pie throw power %s" % power

        t = power / 100.0

        # Distance ranges from CogActivityPieMinDist to CogActivityPieMaxDist ft, time ranges from 1 to 1.5 s.
        dist = lerp(PartyGlobals.CogActivityPieMinDist,
                    PartyGlobals.CogActivityPieMaxDist, t)
        time = lerp(1.0, 1.5, t)

        proj = ProjectileInterval(None,
                                  startPos=Point3(0, 0, 0),
                                  endPos=Point3(0, dist, 0),
                                  duration=time)
        relVel = proj.startVel

        def getVelocity(toon=toon, relVel=relVel):
            return render.getRelativeVector(toon, relVel) * 0.6

        toss = Track(
            (
                0,
                Sequence(
                    Func(toon.setPosHpr, x, y, z, h, p, r),
                    Func(pie.reparentTo, toon.rightHand),
                    Func(pie.setPosHpr, 0, 0, 0, 0, 0, 0),
                    animPie,
                    Parallel(
                        ActorInterval(
                            toon,
                            'throw',
                            startFrame=48,
                            #duration=0.25, #self.throwPieLimitTime,
                            playRate=1.5,
                            partName='torso'),
                        animPie),
                    Func(toon.setAnimState, 'Happy'),
                )),
            (16. / 24., Func(pie.detachNode)))

        fly = Track(
            (14. / 24.,
             SoundInterval(
                 sound, node=toon, cutOff=PartyGlobals.PARTY_COG_CUTOFF)),
            (
                16. / 24.,
                Sequence(
                    Func(flyPie.reparentTo, render),
                    Func(flyPie.setPosHpr, toon, 0.52, 0.97, 2.24, 0, -45, 0),
                    beginFlyIval,
                    ProjectileInterval(
                        flyPie, startVel=getVelocity, duration=6),
                    #LerpPosInterval(flyPie, duration = 3, Point3(0.52,50,2.24)),
                    Func(flyPie.detachNode),
                )),
        )
        return (toss, fly, flyPie)
Esempio n. 22
0
class Myapp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.accept("escape", sys.exit)
        self.accept("mouse1", self.startShoot)
        self.accept("mouse1-up", self.endShoot)

        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        self.heading = 0
        self.pitch = 0
        self.mousex = 0
        self.mousey = 0
        self.flight = []
        self.cs_flight = []
        self.explosion = []
        self.score = 0
        self.life = 20
        self.m1down = 1

        self.environ = self.loader.loadModel("models/terrain")
        self.environ.reparentTo(self.render)
        self.environ.setScale(0.8, 0.8, 0.8)
        self.environ.setPos(0, 0, -10)
        self.environ.setHpr(-90, 0, 0)

        for k in range(0, 5):
            self.flight.append(self.loader.loadModel("models/spitfire"))
            self.flight[k].reparentTo(self.render)
            self.flight[k].setScale(0.1, 0.1, 0.1)
            self.flight[k].setPos(randint(-40, 20), randint(300, 400),
                                  randint(10, 20))
            self.cs_flight.append(self.flight[k].attachNewNode(
                CollisionNode(str(k))))
            self.cs_flight[k].node().addSolid(CollisionSphere(0, 0, 5, 30))
            #self.cs_flight[k].show()
            self.flight[k].setCollideMask(BitMask32.bit(1))

        self.bullets = []

        self.crosshair = OnscreenImage(image='models/crosshair.png',
                                       pos=(0, 0, 0))
        self.crosshair.setScale(0.03, 0.03, 0.03)
        self.crosshair.setTransparency(TransparencyAttrib.MAlpha)
        self.title = OnscreenText(" ",
                                  style=1,
                                  fg=(1, 1, 1, 1),
                                  pos=(0, 0),
                                  scale=.07)

        self.taskMgr.add(self.mouse_control, "mouse_control")
        self.taskMgr.add(self.update_flight, "update_flight")

        self.picker = CollisionTraverser()
        self.pq = CollisionHandlerQueue()

        self.pickerNode = CollisionNode('mouseRay')
        self.pickerNP = camera.attachNewNode(self.pickerNode)
        self.pickerNode.setFromCollideMask(BitMask32.bit(1))

        self.pickerRay = CollisionRay()
        self.pickerNode.addSolid(self.pickerRay)
        self.picker.addCollider(self.pickerNP, self.pq)

        self.gun = OnscreenImage(image='models/gun.png', pos=(0.24, 0, -0.54))
        self.gun.setScale(1, 0.6, 0.6)
        self.gun.setTransparency(TransparencyAttrib.MAlpha)

        self.sound = base.loader.loadSfx("models/sound.ogg")

        base.setFrameRateMeter(True)

    def mouse_control(self, task):
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        if base.win.movePointer(0, 100, 100):
            self.heading = self.heading - (x - 100) * 0.1
            self.pitch = self.pitch - (y - 100) * 0.1
        if (self.pitch < -10): self.pitch = -10
        if (self.pitch > 20): self.pitch = 20
        if (self.heading < -40): self.heading = -40
        if (self.heading > 30): self.heading = 30
        base.camera.setHpr(self.heading, self.pitch, 0)

        return Task.cont

    def update_flight(self, task):
        i = 0
        while (i < len(self.flight)):
            x = self.flight[i].getY()
            if x < -3:
                self.flight[i].setPos(randint(-40, 20), randint(200, 300),
                                      randint(10, 20))
                if (self.life == 0):
                    self.game_end()
                else:
                    self.life -= 1
            else:
                x -= 0.7
                self.flight[i].setPos(self.flight[i].getX(), x,
                                      self.flight[i].getZ())
            i += 1
        self.title.destroy()
        self.title = OnscreenText(text='Life: ' + str(self.life) + ' Score: ' +
                                  str(self.score),
                                  style=1,
                                  fg=(1, 1, 1, 1),
                                  pos=(-1.5, 0.9),
                                  scale=.07)
        return Task.cont

    def removeBullet(self, task):
        if len(self.bullets) < 1: return
        self.bulletNP = self.bullets.pop(0)
        self.bulletNP.removeNode()
        return task.done

    def shootBullet(self, task):
        self.ball = self.loader.loadModel("models/bullet")
        self.ball.reparentTo(self.render)
        self.ball.setScale(0.02, 0.02, 0.02)
        self.ball.setPos(0, 0, 0)
        self.bullets.append(self.ball)
        self.bt = ProjectileInterval(self.ball,
                                     startPos=Point3(0, 0, -5),
                                     endPos=Point3(self.heading * -2, 100,
                                                   self.pitch * 2),
                                     duration=0.3,
                                     gravityMult=-2)
        self.bt.start()
        self.taskMgr.doMethodLater(0.3, self.removeBullet, 'removeBullet')
        self.hit_flight()
        if (self.m1down):
            self.taskMgr.doMethodLater(0.2, self.shootBullet, 'shootbullet')

    def hit_flight(self):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
            self.pickerRay.setFromLens(base.camNode, 0, 0)
            self.picker.traverse(render)
            if self.pq.getNumEntries() > 0:
                self.pq.sortEntries()
                pickedObj = self.pq.getEntry(0).getIntoNodePath()
                if pickedObj.getName() != 'CINEMA4D_Mesh':
                    k = int(pickedObj.getName())
                    self.score += 1
                    self.explode(self.flight[k].getX(), self.flight[k].getY(),
                                 self.flight[k].getZ())
                    self.flight[k].setPos(randint(-40, 20), randint(200, 300),
                                          randint(10, 20))

    def game_end(self):
        self.crosshair.remove()
        self.gov = OnscreenText("Game Over",
                                style=1,
                                fg=(1, 1, 1, 1),
                                pos=(0, 0),
                                scale=0.07)
        self.taskMgr.remove("mouse_control")
        self.taskMgr.remove("update_flight")
        #self.explode(20,20,20)
        p = open('score.txt', 'r')
        score = p.readline()
        p.close()
        if (self.score > int(score)):
            p = open('score.txt', 'w')
            p.write(str(self.score))
            p.close()

    def explode(self, x, y, z):
        k = len(self.explosion)
        self.explosion.append(loader.loadModel('explosion/flip.egg'))
        self.explosion[k].reparentTo(self.render)
        self.explosion[k].setPos(x, y, z)
        self.explosion[k].setScale(5, 5, 5)
        self.taskMgr.doMethodLater(0.6, self.removeExplosion, 'removeExp')

    def removeExplosion(self, task):
        if len(self.explosion) < 1: return
        self.explosion[0].removeNode()
        del self.explosion[0]
        return task.done

    def endShoot(self):
        self.m1down = 0
        self.sound.stop()

    def startShoot(self):
        self.sound.play()
        self.m1down = 1
        self.taskMgr.doMethodLater(0.1, self.shootBullet, 'shootbullet')
class BounceCheckAttack(ThrowAttack):
    notify = directNotify.newCategory('BounceCheckAttack')
    MaxBounces = 3
    WeaponHitDistance = 0.5

    def __init__(self, attacksClass, suit):
        ThrowAttack.__init__(self, attacksClass, suit)
        self.attack = 'bouncecheck'
        self.bounceSound = None
        self.numBounces = 0
        return

    def __pollCheckDistance(self, task):
        if base.localAvatar.getDistance(self.weapon) <= self.WeaponHitDistance:
            self.handleWeaponCollision(None)
            return Task.done
        return Task.cont
        return

    def loadAttack(self):
        self.weapon = loader.loadModel('phase_5/models/props/bounced-check.bam')
        self.weapon.setScale(10)
        self.weapon.setTwoSided(1)
        self.bounceSound = base.audio3d.loadSfx('phase_5/audio/sfx/SA_bounce_check_bounce.ogg')
        base.audio3d.attachSoundToObject(self.bounceSound, self.suit)
        cSphere = CollisionSphere(0, 0, 0, 0.1)
        cSphere.setTangible(0)
        if hasattr(self, 'uniqueName'):
            name = self.uniqueName('bounced_check_collision')
        else:
            name = 'bounced_check_collision'
        cNode = CollisionNode(name)
        cNode.addSolid(cSphere)
        cNode.setFromCollideMask(CIGlobals.FloorBitmask)
        cNP = self.weapon.attachNewNode(cNode)
        cNP.setCollideMask(BitMask32(0))
        self.event = CollisionHandlerEvent()
        self.event.setInPattern('%fn-into')
        self.event.setOutPattern('%fn-out')
        base.cTrav.addCollider(cNP, self.event)
        self.wsnp = cNP
        self.wsnp.show()

    def doAttack(self, ts=0):
        ThrowAttack.doAttack(self, ts)
        self.loadAttack()
        if hasattr(self, 'uniqueName'):
            name = self.uniqueName('doBounceCheckAttack')
        else:
            name = 'doBounceCheckAttack'
        self.suitTrack = Sequence(name=name)
        self.weapon.reparentTo(self.suit.find('**/joint_Rhold'))
        if self.suit.type == 'C':
            self.suitTrack.append(Wait(2.3))
        else:
            self.suitTrack.append(Wait(3))
        self.suit.play('throw-paper')
        self.suitTrack.append(Func(self.throwObject))
        self.suitTrack.start(ts)

    def throwObject(self):
        ThrowAttack.throwObject(self)
        taskMgr.add(self.__pollCheckDistance, 'pollCheckDistance')
        self.__doThrow(0)

    def __doThrow(self, alreadyThrown):
        self.weapon.setScale(1)
        pathNP = NodePath('throwPath')
        if not alreadyThrown:
            pathNP.reparentTo(self.suit)
        else:
            pathNP.reparentTo(self.weapon)
        pathNP.setScale(render, 1.0)
        pathNP.setPos(0, 30, -100)
        pathNP.setHpr(90, -90, 90)
        print pathNP.getPos(base.render)
        if self.throwTrajectory:
            self.throwTrajectory.pause()
            self.throwTrajectory = None
        if alreadyThrown:
            startPos = self.weapon.getPos(base.render)
            gravity = 0.7
        else:
            gravity = 0.7
            startPos = self.suit.find('**/joint_Rhold').getPos(base.render)
        self.throwTrajectory = ProjectileInterval(self.weapon, startPos=startPos, endPos=pathNP.getPos(base.render), gravityMult=gravity, duration=3.0)
        self.throwTrajectory.start()
        self.weapon.setScale(10)
        self.weapon.reparentTo(render)
        self.weapon.setHpr(pathNP.getHpr(render))
        self.weapon_state = 'released'
        self.acceptOnce(self.wsnp.node().getName() + '-into', self.__handleHitFloor)
        return

    def __handleHitFloor(self, entry):
        self.numBounces += 1
        if self.numBounces >= self.MaxBounces:
            self.cleanup()
            return
        base.playSfx(self.bounceSound)
        self.__doThrow(1)

    def cleanup(self):
        taskMgr.remove('pollCheckDistance')
        self.ignore(self.wsnp.node().getName() + '-into')
        self.bounceSound = None
        ThrowAttack.cleanup(self)
        return
Esempio n. 24
0
class Player(FSM, DirectObject):
    NormalMode = "Normal"
    FightMode = "Fight"

    GAMEPADMODE = "Gamepad"
    MOUSEANDKEYBOARD = "MouseAndKeyboard"

    def __init__(self):
        FSM.__init__(self, "FSM-Player")
        random.seed()

        #
        # PLAYER CONTROLS AND CAMERA
        #
        self.player = Actor(
            "Character",
            {
                "Idle": "Character-Idle",
                "Run": "Character-Run",
                "Activate": "Character-Activate",
                "Death": "Character-Death",
                "Jump": "Character-Jump",
                "Hit": "Character-Hit",
                "Fight_Attack": "Character-FightAttack",
                "Fight_Idle": "Character-FightIdle",
                "Fight_Left": "Character-FightLeft",
                "Fight_Right": "Character-FightRight",
            },
        )
        self.player.setBlend(frameBlend=True)
        # the initial cam distance
        self.fightCamDistance = 3.0
        # the next two vars will set the min and max distance the cam can have
        # to the node it is attached to
        self.maxCamDistance = 4.0
        self.minCamDistance = 1.2
        # the initial cam distance
        self.camDistance = (self.maxCamDistance - self.minCamDistance) / 2.0 + self.minCamDistance
        # the next two vars set the min and max distance on the Z-Axis to the
        # node the cam is attached to
        self.maxCamHeightDist = 3.0
        self.minCamHeightDist = 1.5
        # the average camera height
        self.camHeightAvg = (self.maxCamHeightDist - self.minCamHeightDist) / 2.0 + self.minCamHeightDist
        # an invisible object which will fly above the player and will be used to
        # track the camera on it
        self.camFloater = NodePath(PandaNode("playerCamFloater"))
        self.camFloater.setPos(0, 0, 1.5)
        self.camFloater.reparentTo(self.player)
        # screen sizes
        self.winXhalf = base.win.getXSize() / 2
        self.winYhalf = base.win.getYSize() / 2
        # Interval for the jump animation
        self.jumpInterval = None
        self.jumpstartFloater = NodePath(PandaNode("jumpstartFloater"))
        self.jumpstartFloater.reparentTo(render)
        self.deathComplete = None
        # Joystick/Gamepad support
        self.hasJoystick = False
        if gamepadSupport:
            # initialize controls
            joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
            if len(joysticks) > 0:
                self.mainJoystick = joysticks[0]
                self.mainJoystick.init()
                self.hasJoystick = True

        #
        # WEAPONS AND ACCESSORIES
        #
        self.RightHandAttach = self.player.exposeJoint(None, "modelRoot", "HandAttach_R")
        self.spear = loader.loadModel("Spear")
        self.spear.setP(90)
        self.spear.setR(180)
        self.spear.reparentTo(self.RightHandAttach)
        self.LeftHandAttach = self.player.exposeJoint(None, "modelRoot", "HandAttach_L")
        self.shield = loader.loadModel("Shield")
        self.shield.setZ(0.05)
        self.shield.setH(-90)
        self.shield.reparentTo(self.LeftHandAttach)

        #
        # PLAYER COLLISION DETECTION AND PHYSICS
        #
        self.playerSphere = CollisionSphere(0, 0, 0.8, 0.7)
        self.playerCollision = self.player.attachNewNode(CollisionNode("playerCollision"))
        self.playerCollision.node().addSolid(self.playerSphere)
        base.pusher.addCollider(self.playerCollision, self.player)
        base.cTrav.addCollider(self.playerCollision, base.pusher)
        # The foot collision checks
        self.footRay = CollisionRay(0, 0, 0, 0, 0, -1)
        self.playerFootRay = self.player.attachNewNode(CollisionNode("playerFootCollision"))
        self.playerFootRay.node().addSolid(self.footRay)
        self.playerFootRay.node().setIntoCollideMask(0)
        self.lifter = CollisionHandlerFloor()
        self.lifter.addCollider(self.playerFootRay, self.player)
        self.lifter.setMaxVelocity(5)
        base.cTrav.addCollider(self.playerFootRay, self.lifter)
        # a collision segment slightly in front of the player to check for jump ledges
        self.jumpCheckSegment = CollisionSegment(0, -0.2, 0.5, 0, -0.2, -2)
        self.playerJumpRay = self.player.attachNewNode(CollisionNode("playerJumpCollision"))
        self.playerJumpRay.node().addSolid(self.jumpCheckSegment)
        self.playerJumpRay.node().setIntoCollideMask(0)
        self.jumper = CollisionHandlerEvent()
        self.jumper.addOutPattern("%fn-out")
        base.cTrav.addCollider(self.playerJumpRay, self.jumper)
        # a collision segment to check attacks
        self.attackCheckSegment = CollisionSegment(0, 0, 1, 0, -1.3, 1)
        self.playerAttackRay = self.player.attachNewNode(CollisionNode("playerAttackCollision"))
        self.playerAttackRay.node().addSolid(self.attackCheckSegment)
        self.playerAttackRay.node().setIntoCollideMask(0)
        self.attackqueue = CollisionHandlerQueue()
        base.cTrav.addCollider(self.playerAttackRay, self.attackqueue)

        #
        # SOUNDEFFECTS
        #
        self.footstep = loader.loadSfx("Footstep.ogg")
        self.footstep.setLoop(True)
        self.footstep.setPlayRate(1.5)
        self.footstep.setVolume(0.5)
        self.spearAttackSfx = loader.loadSfx("SpearAttack.ogg")
        self.spearAttackSfx.setVolume(0.5)

    #
    # START/STOP
    #
    def start(self, startPoint):
        self.player.setPos(startPoint.getPos())
        self.player.setHpr(startPoint.getHpr())
        self.player.reparentTo(render)
        self.jumpstartFloater.setPos(self.player.getPos())

        self.keyMap = {"horizontal": 0, "vertical": 0}

        self.health = 3
        self.trackedEnemy = None
        # this mode will be used to determine in which move mode the player currently is
        self.mode = Player.NormalMode
        # the initial cam height
        self.camHeight = self.camHeightAvg
        # a time to keep the cam zoom at a specific speed independent of
        # current framerate
        self.camElapsed = 0.0
        self.mouseSpeedX = 15.0 * base.mouseSensitivity
        self.mouseSpeedY = 0.2 * base.mouseSensitivity
        self.speed = 1.0

        self.camCenterEvents = ["centerCam", "home", "q"]
        self.camZoomInEvents = ["zoomIn", "+", "wheel_up"]
        self.camZoomOutEvents = ["zoomOut", "-", "wheel_down"]
        self.actionEvents = ["doAction", "enter", "e"]

        self.accept("arrow_left", self.setKey, ["horizontal", 1])
        self.accept("arrow_right", self.setKey, ["horizontal", -1])
        self.accept("arrow_up", self.setKey, ["vertical", -1])
        self.accept("arrow_down", self.setKey, ["vertical", 1])
        self.accept("arrow_left-up", self.setKey, ["horizontal", 0])
        self.accept("arrow_right-up", self.setKey, ["horizontal", 0])
        self.accept("arrow_up-up", self.setKey, ["vertical", 0])
        self.accept("arrow_down-up", self.setKey, ["vertical", 0])
        self.accept("a", self.setKey, ["horizontal", 1])
        self.accept("d", self.setKey, ["horizontal", -1])
        self.accept("w", self.setKey, ["vertical", -1])
        self.accept("s", self.setKey, ["vertical", 1])
        self.accept("a-up", self.setKey, ["horizontal", 0])
        self.accept("d-up", self.setKey, ["horizontal", 0])
        self.accept("w-up", self.setKey, ["vertical", 0])
        self.accept("s-up", self.setKey, ["vertical", 0])
        for event in self.camCenterEvents:
            self.acceptOnce(event, self.center)
        for event in self.camZoomInEvents:
            self.acceptOnce(event, self.zoom, [True])
        for event in self.camZoomOutEvents:
            self.acceptOnce(event, self.zoom, [False])
        for event in self.actionEvents:
            self.acceptOnce(event, self.request, ["Action"])
        self.accept("ActionDone", self.request, ["Idle"])

        self.accept("playerJumpCollision-out", self.jump)

        taskMgr.add(self.move, "task_movement", priority=-10)
        taskMgr.add(self.updateCam, "task_camActualisation", priority=-4)

        if self.hasJoystick:
            taskMgr.add(self.gamepadLoop, "task_gamepad_loop", priority=-5)

        camera.setPos(self.player, 0, self.camDistance, self.camHeightAvg)

        self.hasJumped = False
        self.isActionmove = False

        self.request("Idle")

    def stop(self):
        taskMgr.remove("task_movement")
        taskMgr.remove("task_camActualisation")
        taskMgr.remove("task_gamepad_loop")
        self.ignoreAll()
        self.player.hide()

    def cleanup(self):
        self.stop()
        if self.deathComplete is not None:
            self.deathComplete.finish()
        if self.jumpInterval is not None:
            self.jumpInterval.finish()
        self.spear.removeNode()
        self.shield.removeNode()
        self.player.cleanup()
        self.player.removeNode()
        self.jumpstartFloater.removeNode()
        self.camFloater.removeNode()

    #
    # BASIC FUNCTIONS
    #
    def die(self):
        self.health -= 1
        base.messenger.send("setHealth", [self.health])
        self.request("Death")

    def heal(self):
        if self.health >= 3:
            return
        self.health += 1
        base.messenger.send("setHealth", [self.health])

    def hit(self):
        self.health -= 1
        base.messenger.send("setHealth", [self.health])
        if self.health == 0:
            self.request("Death")
        else:
            self.request("Hit")

    def resetPlayerPos(self):
        self.player.setPos(self.jumpstartFloater.getPos())
        self.jumper.clear()
        self.request("Idle")

    def gameOver(self):
        base.messenger.send("GameOver", ["loose"])

    def enterFightMode(self, trackedEnemy):
        self.trackedEnemy = trackedEnemy
        self.mode = Player.FightMode
        base.messenger.send("EnterFightMode")

    def exitFightMode(self):
        self.trackedEnemy = None
        self.mode = Player.NormalMode
        base.messenger.send("ExitFightMode")

    def gamepadLoop(self, task):
        joymap = {0: "doAction", 5: "centerCam", 6: "zoomIn", 4: "zoomOut", 9: "escape"}
        for event in pygame.event.get():
            for button in range(self.mainJoystick.get_numbuttons()):
                if button in joymap and self.mainJoystick.get_button(button):
                    base.messenger.send(joymap[button])
            if event.type == pygame.JOYAXISMOTION:
                for axis in range(self.mainJoystick.get_numaxes()):
                    axisChange = 0.0
                    axisChange = self.mainJoystick.get_axis(axis)
                    if axis == 0:
                        self.setKey("horizontal", -axisChange)
                    if axis == 1:
                        self.setKey("vertical", axisChange)
        return task.cont

    def setAnimationSpeed(self, requestedState):
        if requestedState == "Run":
            self.player.setPlayRate(3 * self.speed, "Run")
        elif requestedState == "RunReverse":
            self.player.setPlayRate(-3 * self.speed, "Run")
        elif requestedState == "FightLeft":
            self.player.setPlayRate(2 * self.speed, "Fight_Left")
        elif requestedState == "FightRight":
            self.player.setPlayRate(2 * self.speed, "Fight_Right")

    #
    # MOVE FUNCTIONS
    #
    def setKey(self, key, value):
        self.keyMap[key] = value

    def move(self, task):
        dt = globalClock.getDt()
        resetMouse = False

        def resetMouse():
            if base.controlType == Player.MOUSEANDKEYBOARD:
                base.win.movePointer(0, self.winXhalf, self.winYhalf)

        if self.player.getAnimControl("Hit").isPlaying() or self.player.getAnimControl("Death").isPlaying():
            resetMouse()
            return task.cont
        if self.deathComplete is not None:
            if self.deathComplete.isPlaying():
                resetMouse()
                return task.cont
        if self.jumpInterval is not None:
            if self.jumpInterval.isPlaying():
                resetMouse()
                return task.cont
        if self.isActionmove:
            resetMouse()
            return task.cont

        if self.mode == Player.NormalMode:
            self.__normalMove(dt)
        else:
            self.__fightMove(dt)
        return task.cont

    def __normalMove(self, dt):
        requestState = "Idle"
        move = False
        if self.keyMap["horizontal"] != 0:
            requestState = "Run"
            move = True
        if self.keyMap["vertical"] != 0:
            requestState = "Run"
            move = True
        if move and base.controlType == Player.GAMEPADMODE:
            movementVec = Vec3(self.keyMap["horizontal"], self.keyMap["vertical"], 0)
            self.speed = max(abs(self.keyMap["horizontal"]), abs(self.keyMap["vertical"]))
            angle = math.atan2(-movementVec.getX(), movementVec.getY())
            rotation = angle * (180.0 / math.pi)
            self.player.setH(camera, rotation)
            self.player.setP(0)
            self.player.setR(0)
            self.player.setPos(self.player, (0, -2 * self.speed * dt, 0))
        elif base.controlType == Player.MOUSEANDKEYBOARD:
            if not base.mouseWatcherNode.hasMouse():
                return
            self.pointer = base.win.getPointer(0)
            mouseX = self.pointer.getX()
            mouseY = self.pointer.getY()

            if base.win.movePointer(0, self.winXhalf, self.winYhalf):
                z = camera.getZ() + (mouseY - self.winYhalf) * self.mouseSpeedY * dt
                camera.setZ(z)

                h = self.player.getH() - (mouseX - self.winXhalf) * self.mouseSpeedX * dt
                if h < -360:
                    h = 360
                elif h > 360:
                    h = -360
                self.player.setH(h)
                if move:
                    self.player.setPos(
                        self.player, (2 * dt * self.keyMap["horizontal"], 2 * dt * self.keyMap["vertical"], 0)
                    )
                self.center()
        if self.state != requestState:
            self.request(requestState)
        self.setAnimationSpeed(requestState)

    def __fightMove(self, dt):
        if self.trackedEnemy == None:
            return
        requestState = "Idle"
        self.player.lookAt(self.trackedEnemy)
        self.player.setH(self.player, 180)
        if self.keyMap["horizontal"] > 0:
            self.player.setX(self.player, 2 * self.speed * dt)
            requestState = "FightLeft"
        elif self.keyMap["horizontal"] < 0:
            self.player.setX(self.player, -2 * self.speed * dt)
            requestState = "FightRight"
        elif self.keyMap["vertical"] < 0:
            self.player.setY(self.player, -2 * self.speed * dt)
            requestState = "Run"
        elif self.keyMap["vertical"] > 0:
            self.player.setY(self.player, 2 * self.speed * dt)
            requestState = "RunReverse"
        if self.state != requestState:
            self.request(requestState)
        self.setAnimationSpeed(requestState)

    def jump(self, extraArg):
        intoName = extraArg.getIntoNode().getName().lower()
        if not "floor" in intoName and not "plate" in intoName:
            return
        # setup the projectile interval
        startPos = self.player.getPos()
        self.jumpstartFloater.setPos(self.player, 0, 0.5, 0)
        tempFloater = NodePath(PandaNode("tempJumpFloater"))
        tempFloater.setPos(self.player, 0, -3.2, 0.1)
        endPos = tempFloater.getPos()
        tempFloater.removeNode()
        self.jumpInterval = ProjectileInterval(
            self.player, startPos=startPos, endPos=endPos, duration=1.5, gravityMult=0.25
        )
        self.request("Jump")
        self.jumpInterval.start()

    #
    # CAMERA FUNCTIONS
    #
    def updateCam(self, task):
        if self.mode == Player.NormalMode:
            self.__normalCam()
        else:
            self.__fightCam()
        return task.cont

    def zoom(self, zoomIn):

        # Camera Movement Updates
        camvec = self.player.getPos() - camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()

        zoom = 0
        if zoomIn:
            if camdist > self.minCamDistance + 0.5:
                zoom = 0.5
            for event in self.camZoomInEvents:
                self.acceptOnce(event, self.zoom, [True])
        else:
            if camdist < self.maxCamDistance - 0.5:
                zoom = -0.5
            for event in self.camZoomOutEvents:
                self.acceptOnce(event, self.zoom, [False])
        camera.setPos(camera, 0, zoom, 0)

    def center(self):
        # Camera Movement Updates
        camvec = self.player.getPos() - camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()
        # get the cameras current offset to the player model on the z-axis
        offsetZ = camera.getZ() - self.player.getZ()
        camera.setPos(self.player, 0, camdist, offsetZ)
        for event in self.camCenterEvents:
            self.acceptOnce(event, self.center)

    def __normalCam(self):
        """This function will check the min and max distance of the camera to
        the defined model and will correct the position if the cam is to close
        or to far away"""

        # Camera Movement Updates
        camvec = self.player.getPos() - camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()
        camvec.normalize()

        # If far from player start following
        if camdist > self.maxCamDistance:
            camera.setPos(camera.getPos() + camvec * (camdist - self.maxCamDistance))
            camdist = self.maxCamDistance

        # If player to close move cam backwards
        if camdist < self.minCamDistance:
            camera.setPos(camera.getPos() - camvec * (self.minCamDistance - camdist))
            camdist = self.minCamDistance

        # get the cameras current offset to the player model on the z-axis
        offsetZ = camera.getZ() - self.player.getZ()
        # check if the camera is within the min and max z-axis offset
        if offsetZ < self.minCamHeightDist:
            camera.setZ(self.player.getZ() + self.minCamHeightDist)
            offsetZ = self.minCamHeightDist
        elif offsetZ > self.maxCamHeightDist:
            camera.setZ(self.player.getZ() + self.maxCamHeightDist)
            offsetZ = self.maxCamHeightDist

        if offsetZ != self.camHeightAvg and not base.controlType == Player.MOUSEANDKEYBOARD:
            # if we are not moving up or down, set the cam to an average position
            if offsetZ != self.camHeightAvg:
                if offsetZ > self.camHeightAvg:
                    # the cam is higher then the average cam height above the player
                    # so move it slowly down
                    camera.setZ(camera.getZ() - 5 * globalClock.getDt())
                    newOffsetZ = camera.getZ() - self.player.getZ()
                    # check if the cam has reached the desired offset
                    if newOffsetZ < self.camHeightAvg:
                        # set the cam z position to exactly the desired offset
                        camera.setZ(self.player.getZ() + self.camHeightAvg)
                else:
                    # the cam is lower then the average cam height above the player
                    # so move it slowly up
                    camera.setZ(camera.getZ() + 5 * globalClock.getDt())
                    newOffsetZ = camera.getZ() - self.player.getZ()
                    # check if the cam has reached the desired offset
                    if newOffsetZ > self.camHeightAvg:
                        # set the cam z position to exactly the desired offset
                        camera.setZ(self.player.getZ() + self.camHeightAvg)

        camera.lookAt(self.camFloater)

    def __fightCam(self):
        """This function will check the min and max distance of the camera to
        the defined model and will correct the position if the cam is to close
        or to far away"""
        camera.setX(self.player, 0)
        camera.setY(self.player, self.fightCamDistance)
        camera.setZ(0.5)

        camera.lookAt(self.camFloater)

    #
    # FSM FUNCTIONS
    #
    def enterIdle(self):
        if self.mode == Player.NormalMode:
            self.player.loop("Idle")
            self.footstep.stop()
        elif self.mode == Player.FightMode:
            self.player.loop("Fight_Idle")
            self.footstep.stop()

    def enterRun(self):
        self.player.loop("Run")
        self.footstep.play()

    def enterRunReverse(self):
        self.player.loop("Run")
        self.footstep.play()

    def enterAction(self):
        if self.player.getAnimControl("Hit").isPlaying() or self.player.getAnimControl("Death").isPlaying():
            self.__exitAction()
            return
        self.isActionmove = True
        if self.mode == Player.NormalMode:
            self.__enterActivate()
        elif self.mode == Player.FightMode:
            self.__enterFightAttack()
        self.accept("ActionDone", self.__exitAction)

    def __exitAction(self):
        self.isActionmove = False
        for event in self.actionEvents:
            self.acceptOnce(event, self.request, ["Action"])

    def __enterActivate(self):
        activateAnim = self.player.actorInterval("Activate", playRate=3)
        activateAnim.setDoneEvent("ActionDone")
        activateAnim.start()
        base.messenger.send("Player_Activate")
        self.footstep.stop()

    def enterDeath(self):
        self.footstep.stop()
        deathAnim = self.player.actorInterval("Death")
        deathComplete = None
        if self.health == 0:
            self.deathComplete = Sequence(deathAnim, Wait(2), Func(self.gameOver))
        else:
            self.deathComplete = Sequence(deathAnim, Wait(2), Func(self.resetPlayerPos))
        self.deathComplete.start()

    def enterJump(self):
        self.player.play("Jump")
        self.footstep.stop()

    def enterHit(self):
        self.player.setPlayRate(4, "Hit")
        self.player.play("Hit")
        self.footstep.stop()

    def __enterFightAttack(self):
        attackAnim = self.player.actorInterval("Fight_Attack", playRate=3)
        attackAnim.setDoneEvent("ActionDone")
        attackAnim.start()
        self.spearAttackSfx.play()
        for i in range(self.attackqueue.getNumEntries()):
            entry = self.attackqueue.getEntry(i)
            into = entry.getIntoNode()
            if "golemHitField" in into.getName():
                if random.random() > 0.15:
                    base.messenger.send("HitEnemy")
        self.footstep.stop()

    def enterFightLeft(self):
        self.player.loop("Fight_Left")
        self.footstep.play()

    def enterFightRight(self):
        self.player.loop("Fight_Right")
        self.footstep.play()