def update(self):
        toonPos = self.toon.getPos()
        newOffset = Vec3(self.player.instantaneousVelocity.getX() * 0.1,
                         self.player.instantaneousVelocity.getY() * 2.0,
                         self.player.velocity.getZ())
        targetPos = toonPos + self.camOffset + Vec3(0, 0,
                                                    -newOffset.getZ() * 0.3)
        targetLookAt = toonPos + Vec3(0, 35, 0) + newOffset

        if self.player.instantaneousVelocity.getY() < 0.0 or (
                self.player.instantaneousVelocity.getY() <= 0.0
                and self.player.instantaneousVelocity.getZ() < 0.0):
            targetPos = targetPos + Vec3(
                0, +2.0, abs(self.player.instantaneousVelocity.getZ() * 0.4))
            targetLookAt = targetLookAt + Vec3(
                0, 0, -abs(self.player.instantaneousVelocity.getZ() * 0.2))
            targetLookAt[1] = toonPos[1]

        p = 0.90
        targetPos[0] = clamp(targetPos[0], self.player.game.leftLimit * p,
                             self.player.game.rightLimit * p)
        targetLookAt[0] = clamp(targetLookAt[0],
                                self.player.game.leftLimit * p,
                                self.player.game.rightLimit * p)

        #targetPos[2] = clamp(targetPos[2], self.player.game.downLimit*p, self.player.game.upLimit*p)
        p = 0.95
        targetLookAt[2] = clamp(targetLookAt[2],
                                self.player.game.downLimit * p,
                                self.player.game.upLimit * p)

        self.cameraManager.setTargetPos(targetPos)
        self.cameraManager.setTargetLookAtPos(targetLookAt)
Esempio n. 2
0
 def hourChange(self, currentHour):
     currentHour = currentHour % 12
     if currentHour == 0:
         currentHour = 12
     self.hourSoundInterval = Parallel()
     # Make a sequence with all the clock sounds
     seq1 = Sequence()
     for i in range(currentHour):
         seq1.append(SoundInterval(self.clockSounds[i]))
         seq1.append(Wait(0.2))
     # Now make a sequence that will deform the clock face
     timeForEachDeformation = seq1.getDuration() / currentHour
     seq2 = Sequence()
     for i in range(currentHour):
         seq2.append(
             self.clockFlat.scaleInterval(timeForEachDeformation / 2.0,
                                          Vec3(0.9, 1.0, 1.2),
                                          blendType='easeInOut'))
         seq2.append(
             self.clockFlat.scaleInterval(timeForEachDeformation / 2.0,
                                          Vec3(1.2, 1.0, 0.9),
                                          blendType='easeInOut'))
     seq2.append(
         self.clockFlat.scaleInterval(timeForEachDeformation / 2.0,
                                      Vec3(1.0, 1.0, 1.0),
                                      blendType='easeInOut'))
     # Now parallel the two together
     self.hourSoundInterval.append(seq1)
     self.hourSoundInterval.append(seq2)
     self.hourSoundInterval.start()
Esempio n. 3
0
 def initIntervals(self):
     dur = Globals.LegalEagle.LiftOffTime
     nestPos = self.nest.getPos(render)
     airPos = nestPos + Vec3(0.0, 0.0, Globals.LegalEagle.LiftOffHeight)
     self.takeOffSeq = Sequence(Parallel(Sequence(Wait(dur * 0.6), LerpPosInterval(self.suit, dur * 0.4, startPos=nestPos, pos=airPos, blendType='easeInOut'))), Wait(1.5), Func(self.request, 'next'), name='%s.takeOffSeq-%i' % (self.__class__.__name__, self.index))
     self.landOnNestPosLerp = LerpPosInterval(self.suit, 1.0, startPos=airPos, pos=nestPos, blendType='easeInOut')
     self.landingSeq = Sequence(Func(self.updateLandOnNestPosLerp), Parallel(self.landOnNestPosLerp), Func(self.request, 'next'), name='%s.landingSeq-%i' % (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.ChargeUpTime
     self.chargeUpPosLerp = LerpFunc(self.moveAlongChargeUpMopathFunc, fromData=0.0, toData=self.chargeUpMotionPath.getMaxT(), duration=dur, blendType='easeInOut')
     self.chargeUpAttackSeq = Sequence(Func(self.updateChargeUpPosLerp), self.chargeUpPosLerp, Func(self.request, 'next'), name='%s.chargeUpAttackSeq-%i' % (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.RetreatToNestTime
     self.retreatToNestPosLerp = LerpPosInterval(self.suit, dur, startPos=Vec3(0, 0, 0), pos=airPos, blendType='easeInOut')
     self.retreatToNestSeq = Sequence(Func(self.updateRetreatToNestPosLerp), self.retreatToNestPosLerp, Func(self.request, 'next'), name='%s.retreatToNestSeq-%i' % (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.RetreatToSkyTime
     self.retreatToSkyPosLerp = LerpFunc(self.moveAlongRetreatMopathFunc, fromData=0.0, toData=self.retreatToSkyMotionPath.getMaxT(), duration=dur, blendType='easeOut')
     self.retreatToSkySeq = Sequence(Func(self.updateRetreatToSkyPosLerp), self.retreatToSkyPosLerp, Func(self.request, 'next'), name='%s.retreatToSkySeq-%i' % (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.PreAttackTime
     self.preAttackLerpXY = LerpFunc(self.updateAttackXY, fromData=0.0, toData=1.0, duration=dur)
     self.preAttackLerpZ = LerpFunc(self.updateAttackZ, fromData=0.0, toData=1.0, duration=dur, blendType='easeOut')
     dur = Globals.LegalEagle.PostAttackTime
     self.postAttackPosLerp = LerpPosInterval(self.suit, dur, startPos=Vec3(0, 0, 0), pos=Vec3(0, 0, 0))
     self.attackSeq = Sequence(Parallel(self.preAttackLerpXY, self.preAttackLerpZ), Func(self.updatePostAttackPosLerp), self.postAttackPosLerp, Func(self.request, 'next'), name='%s.attackSeq-%i' % (self.__class__.__name__, self.index))
     dur = Globals.LegalEagle.CooldownTime
     self.cooldownSeq = Sequence(Wait(dur), Func(self.request, 'next'), name='%s.cooldownSeq-%i' % (self.__class__.__name__, self.index))
     self.propTrack = Sequence(ActorInterval(self.prop, 'propeller', startFrame=0, endFrame=14))
     self.hoverOverNestSeq = Sequence(ActorInterval(self.suit, 'landing', startFrame=10, endFrame=20, playRate=0.5), ActorInterval(self.suit, 'landing', startFrame=20, endFrame=10, playRate=0.5))
Esempio n. 4
0
    def thinkAboutCatchingToon(self):
        if not self.game:
            return

        av = self.game.getAvatar(self.goalId)
        if av:
            if not self.lastThinkTime:
                self.lastThinkTime = globalClock.getFrameTime()
            diffTime = globalClock.getFrameTime() - self.lastThinkTime
            avPos = av.getPos()
            myPos = self.suit.getPos()

            if not self.doneAdjust:
                myPos = self.lastPosFromAI
                self.notify.debug(
                    'thinkAboutCatchingToon not doneAdjust setting pos %s' %
                    myPos)
                self.doneAdjust = True

            self.suit.setPos(myPos)

            if self.game.isToonPlayingHitTrack(self.goalId):
                # do nothing, just look at toon
                self.suit.headsUp(av)
                self.velocity = Vec3(0, 0, 0)
                self.oldVelocity = Vec3(0, 0, 0)
                self.acceleration = Vec3(0, 0, 0)
            else:
                self.commonMove()

            newPos = self.suit.getPos()
            self.adjustPlayRate(newPos, myPos, diffTime)

        self.lastThinkTime = globalClock.getFrameTime()
Esempio n. 5
0
    def load(self):
        """
        Load the necessary assets
        """
        DistributedPartyFireworksActivity.notify.debug("load")
        DistributedPartyActivity.load(self)

        self.eventId = PartyGlobals.FireworkShows.Summer

        # load the rocket platform and place it in party space
        self.launchPadModel = loader.loadModel(
            'phase_13/models/parties/launchPad')
        # Compensate for pivot of fireworks model and center it in 2x4 space
        self.launchPadModel.setH(90.0)
        self.launchPadModel.setPos(0.0, -18.0, 0.0)
        # reparent to root
        self.launchPadModel.reparentTo(self.root)
        # special case the depth testing on the railings to prevent
        # transparency oddness
        railingsCollection = self.launchPadModel.findAllMatches(
            "**/launchPad_mesh/*railing*")
        for i in range(railingsCollection.getNumPaths()):
            railingsCollection[i].setAttrib(
                AlphaTestAttrib.make(RenderAttrib.MGreater, 0.75))

        # place the lever on the platform
        leverLocator = self.launchPadModel.find("**/RocketLever_locator")
        self.lever.setPosHpr(Vec3.zero(), Vec3.zero())
        self.lever.reparentTo(leverLocator)
        self.toonPullingLeverInterval = None

        # place the activity sign
        self.sign.reparentTo(
            self.launchPadModel.find("**/launchPad_sign_locator"))

        # load the rocket with animation and place it on the platform
        self.rocketActor = Actor(
            'phase_13/models/parties/rocket_model',
            {'launch': 'phase_13/models/parties/rocket_launch'},
        )

        rocketLocator = self.launchPadModel.find("**/rocket_locator")
        self.rocketActor.reparentTo(rocketLocator)
        # ensure the rocket is never culled
        self.rocketActor.node().setBound(OmniBoundingVolume())
        self.rocketActor.node().setFinal(True)

        effectsLocator = self.rocketActor.find("**/joint1")
        self.rocketExplosionEffect = RocketExplosion(effectsLocator,
                                                     rocketLocator)

        self.rocketParticleSeq = None

        self.launchSound = base.loader.loadSfx(
            "phase_13/audio/sfx/rocket_launch.mp3")

        # create state machine and set initial state
        self.activityFSM = FireworksActivityFSM(self)
        self.activityFSM.request("Idle")
Esempio n. 6
0
    def __init__(self, cogIndex, suitType, game, cogSpeed):
        self.cogIndex = cogIndex
        self.suitType = suitType
        self.game = game
        self.cogSpeed = cogSpeed
        suit = Suit.Suit()
        d = SuitDNA.SuitDNA()
        d.newSuit(suitType)
        suit.setDNA(d)
        # cache the walk anim
        suit.pose('walk', 0)
        self.suit = suit
        self.goal = CTGG.NoGoal
        self.goalId = CTGG.InvalidGoalId
        self.lastLocalTimeStampFromAI = 0
        self.lastPosFromAI = Point3(0, 0, 0)
        self.lastThinkTime = 0
        self.doneAdjust = False
        self.barrel = CTGG.NoBarrelCarried
        self.signalledAtReturnPos = False
        self.defaultPlayRate = 1.0
        self.netTimeSentToStartByHit = 0

        # steering loosely based on boid code game programming gems #1
        # "Portions Copyright (C) Steven Woodcock, 2000"
        self.velocity = Vec3(0, 0, 0)
        self.oldVelocity = Vec3(0, 0, 0)
        self.acceleration = Vec3(0, 0, 0)
        self.bodyLength = self.CollisionRadius * 2
        # Desired distance from closest neighbor when flying.
        self.cruiseDistance = 2 * self.bodyLength
        self.maxVelocity = self.cogSpeed
        # Maximum magnitude of acceleration as a fraction of maxSpeed.
        self.maxAcceleration = 5.0
        self.perceptionRange = 6
        self.notify.debug('cogSpeed=%s' % self.cogSpeed)

        self.kaboomSound = loader.loadSfx(
            "phase_4/audio/sfx/MG_cannon_fire_alt.mp3")
        self.kaboom = loader.loadModel(
            'phase_4/models/minigames/ice_game_kaboom')
        self.kaboom.setScale(2.0)
        self.kaboom.setBillboardPointEye()
        self.kaboom.hide()
        self.kaboomTrack = None

        splatName = 'splat-creampie'
        self.splat = globalPropPool.getProp(splatName)
        self.splat.setBillboardPointEye()
        self.splatType = globalPropPool.getPropType(splatName)

        self.pieHitSound = globalBattleSoundCache.getSound(
            'AA_wholepie_only.mp3')
Esempio n. 7
0
 def exitCooldown(self):
     self.notify.debug("exit%s: '%s' -> '%s'" % (self.oldState, self.oldState, self.newState))
     self.suit.unstash()
     self.cooldownSeq.clearToInitial()
     if self.newState != 'Off':
         heightOffNest = Globals.LegalEagle.PostCooldownHeightOffNest
         nestPos = self.nest.getPos(render)
         if self.newState in ['LandOnNest']:
             self.suit.setPos(nestPos + Vec3(0, 0, heightOffNest))
         else:
             targetPos = self.target.getPos(render)
             attackPos = Vec3(targetPos)
             attackPos[1] = nestPos[1]
             attackPos[2] = nestPos[2] + heightOffNest
             self.suit.setPos(attackPos)
Esempio n. 8
0
def calcVelocity(rotation, angle, initialVelocity=1.0):
    horizVel = initialVelocity * math.cos(angle)
    xVel = horizVel * -math.sin(rotation)
    yVel = horizVel * math.cos(rotation)
    zVel = initialVelocity * math.sin(angle)

    return Vec3(xVel, yVel, zVel)
Esempio n. 9
0
 def fillActivityList(self, activityIds):
     self.activityList.removeAndDestroyAllItems()
     sortedList = activityIds[:]
     sortedList.sort()
     lastActivityId = -1
     for activityId in sortedList:
         if activityId == lastActivityId:
             continue
         lastActivityId = activityId
         number = sortedList.count(activityId)
         text = TTLocalizer.PartyActivityNameDict[activityId]["generic"]
         if number > 1:
             text += " X %d" % number
         item = DirectLabel(
             relief=None,
             text=text,
             text_align=TextNode.ACenter,
             text_scale=0.05,
             text_pos=(0.0, -0.15),
             geom_scale=0.3,
             geom_pos=Vec3(0.0, 0.0, 0.07),
             geom=PartyUtils.getPartyActivityIcon(
                 self.activityIconsModel,
                 PartyGlobals.ActivityIds.getString(activityId)))
         self.activityList.addItem(item)
Esempio n. 10
0
    def keepDistance(self):
        """Generates a vector for a flock boid to maintain his
        desired separation distance from the nearest flockmate he sees.
        """
        ratio = self.distToNearestFlockmate / self.SeparationDistance
        nearestThief = self.game.getCogThief(self.nearestFlockmate)
        change = nearestThief.suit.getPos() - self.suit.getPos()

        if ratio < self.MinUrgency:
            ratio = self.MinUrgency
        if ratio > self.MaxUrgency:
            ratio = self.MaxUrgency

        # test:  are we too close to our nearest flockmate?
        if self.distToNearestFlockmate < self.SeparationDistance:
            #self.notify.debug('%d is too close to %d' % (self.cogIndex, self.nearestFlockmate))

            # too close...move away from our neighbor
            change.normalize()
            change *= -(1 - ratio
                        )  # the close we are the more we are pushed away
        elif self.distToNearestFlockmate > self.SeparationDistance:
            # too far away move towards our neighbor
            change.normalize()
            change *= ratio
        else:
            # in the UNLIKELY event we're exactly the right distance away, do nothing
            change = Vec3(0, 0, 0)

        return change
    def createBattleCheerInterval(self):
        """Create a looping interval that the prop plays when buffing battles."""
        result = Sequence()
        for i in range(self.numFightAnims):
            animKey = "fight%d" % i
            animAndSoundIval = self.createAnimAndSoundIval(animKey)
            origAnimName = self.node.getAnimFilename(animKey).split('/')[-1]
            if self.hasOverrideIval(origAnimName):
                result.append(self.getOverrideIval(origAnimName))
            elif self.hasSpecialIval(origAnimName):
                result.append(
                    Parallel(animAndSoundIval,
                             self.getSpecialIval(origAnimName)))
            else:
                result.append(animAndSoundIval)

        self.createBattleCheerText()
        battleCheerTextIval = Sequence(
            Func(self.hpText.show),
            self.hpText.posInterval(duration=4.0,
                                    pos=Vec3(0, 0, 7),
                                    startPos=(0, 0, 3)),
            Func(self.hpText.hide),
        )

        ivalWithText = Parallel(battleCheerTextIval, result)
        return ivalWithText
Esempio n. 12
0
 def checkTargets(self, task=None):
     """
     Do a distance check against all the targets in the pond.
     If we hit one of the targets, send an update to the AI and return 1
     Otherwise just return 0
     """
     self.notify.debug("checkTargets")
     if self.localToonSpot != None:
         for target in list(self.targets.values()):
             targetPos = target.getPos(render)
             distVec = Vec3(targetPos - self.localToonBobPos)
             dist = distVec.length()
             if dist < target.getRadius():
                 self.notify.debug("checkTargets: hit target: %s" %
                                   (target.getDoId()))
                 self.d_hitTarget(target)
                 return Task.done
         # Check again later
         taskMgr.doMethodLater(self.pollInterval, self.checkTargets,
                               self.taskName("checkTargets"))
     else:
         # Not sure why this is happening.
         self.notify.warning(
             'localToonSpot became None while checking targets')
     return Task.done
 def rateInterpolate(self, currentPos, targetPos):
     dt = globalClock.getDt()
     vec = currentPos - targetPos
     return Vec3(
         targetPos[0] + vec[0] * (inverse_e**(dt * self.vecRate[0])),
         targetPos[1] + vec[1] * (inverse_e**(dt * self.vecRate[1])),
         targetPos[2] + vec[2] * (inverse_e**(dt * self.vecRate[2])))
Esempio n. 14
0
    def getDropIval(self):
        shadow = self.shadow
        drop = self.drop
        id = self.id
        hangTime = Globals.ShadowTime
        dropTime = Globals.DropTime
        dropHeight = Globals.DropHeight
        targetShadowScale = 0.5
        targetShadowAlpha = 0.4
        shadowScaleIval = LerpScaleInterval(shadow, dropTime, targetShadowScale, startScale=0)
        shadowAlphaIval = LerpColorScaleInterval(shadow, hangTime, Point4(1, 1, 1, targetShadowAlpha), startColorScale=Point4(1, 1, 1, 0))
        shadowIval = Parallel(shadowScaleIval, shadowAlphaIval)
        startPos = Point3(0, 0, dropHeight)
        drop.setPos(startPos)
        dropIval = LerpPosInterval(drop, dropTime, Point3(0, 0, 0), startPos=startPos, blendType='easeIn')
        dropSoundIval = self._dropSfx
        dropSoundIval.node = self
        self.drop.setTransparency(1)

        def _setRandScale(t):
            self.drop.setScale(self, 1 - random.random() / 16, 1 - random.random() / 16, 1 - random.random() / 4)

        scaleChange = 0.4 + random.random() / 4
        dropShakeSeq = Sequence(LerpScaleInterval(self.drop, 0.25, Vec3(1.0 + scaleChange, 1.0 + scaleChange / 2, 1.0 - scaleChange), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.25, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), Func(self.disableCollisionDamage), LerpScaleInterval(self.drop, 0.2, Vec3(1.0 + scaleChange / 8, 1.0 + scaleChange / 8, 1.0 - scaleChange / 8), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.2, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.15, Vec3(1.0 + scaleChange / 16, 1.0 + scaleChange / 16, 1.0 - scaleChange / 16), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.15, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.1, Vec3(1.0 + scaleChange / 16, 1.0 + scaleChange / 8, 1.0 - scaleChange / 16), blendType='easeInOut'), LerpColorScaleInterval(self.drop, Globals.DropFadeTime, Vec4(1.0, 1.0, 1.0, 0.0)))
        ival = Sequence(Func(self.reparentTo, render), Parallel(Sequence(WaitInterval(hangTime), dropIval), shadowIval), Parallel(Func(self.game.dropHit, self, id), dropSoundIval, dropShakeSeq), Func(self.game.cleanupDrop, id), name='drop%s' % id)
        self.ival = ival
        return ival
Esempio n. 15
0
 def _initCollisions(self):
     self.collPlane = CollisionPlane(
         Plane(Vec3(0, 0, 1.0), Point3(0, 0, 10)))
     self.collPlane.setTangible(0)
     self.collNode = CollisionNode('fogPlane')
     self.collNode.setIntoCollideMask(OTPGlobals.FloorBitmask)
     self.collNode.addSolid(self.collPlane)
     self.collNodePath = self.root.attachNewNode(self.collNode)
     self.collNodePath.hide()
Esempio n. 16
0
    def updateGoal(self, timestamp, inResponseClientStamp, goalType, goalId,
                   pos):
        """Update our goal and position."""
        assert self.notify.debugStateCall(self)
        self.notify.debug('self.netTimeSentToStartByHit =%s' %
                          self.netTimeSentToStartByHit)
        if not self.game:
            self.notify.debug('updateGoal self.game is None, just returning')
            return
        if not self.suit:
            self.notify.debug('updateGoal self.suit is None, just returning')
            return
        if self.goal == CTGG.NoGoal:
            self.startWalkAnim()

        if goalType == CTGG.NoGoal:
            self.notify.debug('updateGoal setting position to %s' % pos)
            self.suit.setPos(pos)

        self.lastThinkTime = 0
        self.velocity = Vec3(0, 0, 0)
        self.oldVelocity = Vec3(0, 0, 0)
        self.acceleration = Vec3(0, 0, 0)

        if goalType == CTGG.RunAwayGoal:
            #import pdb; pdb.set_trace()
            pass

        if inResponseClientStamp < self.netTimeSentToStartByHit and \
           self.goal == CTGG.NoGoal and \
           goalType == CTGG.RunAwayGoal:
            #import pdb; pdb.set_trace()
            self.notify.warning(
                'ignoring newGoal %s as cog %d was recently hit responsetime=%s hitTime=%s'
                % (CTGG.GoalStr[goalType], self.cogIndex,
                   inResponseClientStamp, self.netTimeSentToStartByHit))
        else:
            self.lastLocalTimeStampFromAI = globalClockDelta.networkToLocalTime(
                timestamp, bits=32)
            self.goal = goalType
            self.goalId = goalId
            self.lastPosFromAI = pos
            self.doneAdjust = False
        self.signalledAtReturnPos = False
    def __init__(self, player, cam, root):
        self.player = player
        self.toon = player.toon
        self.camera = cam
        self.root = root

        self.camOffset = VBase3(0, -12, 5)
        self.cameraManager = FlyingCamera(self.camera)
        self.cameraManager.vecRate = Vec3(3.0, 2.0, 1.8)
        self.cameraManager.otherNP = self.root
Esempio n. 18
0
 def doModelSetup(self):
     if self.typeIndex == GardenGlobals.BOX_THREE:
         self.defaultModel = "phase_5.5/models/estate/planterA"
     elif self.typeIndex == GardenGlobals.BOX_TWO:
         self.defaultModel = "phase_5.5/models/estate/planterC"
     else:
         self.defaultModel = "phase_5.5/models/estate/planterD"
         self.collSphereOffset = 0.0
         self.collSphereRadius = self.collSphereRadius * 1.41
         self.plotScale = Vec3(1.0, 1.0, 1.0)
Esempio n. 19
0
 def startRotate(self):
     self.stopRotate()
     try:
         ivalDur = 360. / self.degreesPerSec
     except ZeroDivisionError:
         pass
     else:
         hOffset = 360.
         if ivalDur < 0.:
             ivalDur = -ivalDur
             hOffset = -hOffset
         self.rotateIval = LerpHprInterval(self.model,
                                           ivalDur,
                                           Vec3(hOffset, 0, 0),
                                           startHpr=Vec3(0, 0, 0),
                                           name='gearRot-%s' % self.entId)
         self.rotateIval.loop()
         self.rotateIval.setT((globalClock.getFrameTime() -
                               self.level.startTime) +
                              (ivalDur * self.phaseShift))
    def __init__(self, game, toon):
        CogdoFlyingPlayer.__init__(self, toon)
        self.velocity = Vec3(0.0, 0.0, 0.0)
        self.lastVelocity = Vec3(0.0, 0.0, 0.0)
        self.instantaneousVelocity = Vec3(0.0, 0.0, 0.0)
        self.oldPos = Vec3(0.0, 0.0, 0.0)
        self.game = game
        self.inputMgr = CogdoFlyingInputManager()
        self.cameraMgr = CogdoFlyingCameraManager(self, camera, render)
        self.guiMgr = CogdoFlyingGuiManager(self)

        self.checkpointPlatform = None

        self.fuel = 0.0
        self.props = {}

        self.initModels()
        self.initIntervals()

        self.propSound = base.loadSfx('phase_4/audio/sfx/TB_propeller.wav')
def getWalkDistance(fromNode, toNode, velocity, paths):
    posPoints = getPointsFromTo(fromNode, toNode, paths)

    retval = 0
    for pointIndex in range(len(posPoints) - 1):
        startPoint = posPoints[pointIndex]
        endPoint = posPoints[pointIndex + 1]

        # Calculate the amount of time it will take to walk
        distance = Vec3(endPoint - startPoint).length()
        retval += distance

    return retval
Esempio n. 22
0
    def createMeterInterval(self, icon, meter, time):
        """Create and return the meter interval."""
        ivalDarkness = LerpScaleInterval(meter,
                                         time,
                                         scale=Vec3(1, 1, 1),
                                         startScale=Vec3(1, 0.001, 0.001))
        flashingTrack = Sequence()
        flashDuration = 10
        if time > flashDuration:
            flashingTrack.append(Wait(time - flashDuration))
            for i in range(10):
                flashingTrack.append(
                    Parallel(
                        LerpColorScaleInterval(icon, 0.5, VBase4(1, 0, 0, 1)),
                        icon.scaleInterval(0.5, 1.25)))
                flashingTrack.append(
                    Parallel(
                        LerpColorScaleInterval(icon, 0.5, VBase4(1, 1, 1, 1)),
                        icon.scaleInterval(0.5, 1)))

        retIval = Parallel(ivalDarkness, flashingTrack)
        return retIval
Esempio n. 23
0
 def updateLockOnTask(self):
     dt = globalClock.getDt()
     targetPos = self.target.getPos(render)
     suitPos = self.suit.getPos(render)
     nestPos = self.nest.getPos(render)
     attackPos = Vec3(targetPos)
     attackPos[1] = nestPos[1] + Globals.LegalEagle.LockOnDistanceFromNest
     attackPos[2] += Globals.LegalEagle.VerticalOffset
     if attackPos[2] < nestPos[2]:
         attackPos[2] = nestPos[2]
     attackChangeVec = (attackPos - suitPos) * Globals.LegalEagle.LockOnSpeed
     self.suit.setPos(suitPos + attackChangeVec * dt)
     return Task.cont
Esempio n. 24
0
 def getJumpDest(av = av, node = self.golfKart):
     dest = Point3(0,0,0)
     if hasattr(self, 'golfKart') and self.golfKart:
         dest = Vec3(self.golfKart.getPos(av.getParent()))
         seatNode = self.golfKart.find("**/seat" + str(seatIndex + 1))
         dest += seatNode.getPos(self.golfKart)
         dna = av.getStyle()
         dest -= hipOffset
         if(seatIndex < 2):
             dest.setY( dest.getY() + 2 * hipOffset.getY())
         dest.setZ(dest.getZ() + 0.1)
     else:
         self.notify.warning('getJumpDestinvalid golfKart, returning (0,0,0)')
     return dest
Esempio n. 25
0
    def turnDown(self, doInterval = DoIntervalDefault):
        """Turn up the card.

        doInterval -- if true do a sound and flip up animation

        """
        self.faceUp = 0
        if doInterval:
            self.clearFlipIval()
            self.flipIval = Parallel(
                LerpHprInterval(self, self.FlipTime, Vec3(0,0,180)),
                SoundInterval(self.turnDownSound, node = self,
                              listenerNode = base.localAvatar,
                              cutOff = 240)
                )
            self.flipIval.start()
        else:
            self.setR(180)
Esempio n. 26
0
 def isToonInView(self, toon):
     distanceThreshold = self.getInterestConeLength()
     angleThreshold = Globals.LegalEagle.InterestConeAngle
     toonPos = toon.getPos(render)
     nestPos = self.nest.getPos(render)
     distance = toon.getDistance(self.interestConeOrigin)
     if distance > distanceThreshold:
         return False
     if toonPos[1] > nestPos[1]:
         return False
     a = toon.getPos(render) - self.interestConeOrigin.getPos(render)
     a.normalize()
     b = Vec3(0, -1, 0)
     dotProduct = a.dot(b)
     angle = math.degrees(math.acos(dotProduct))
     if angle <= angleThreshold / 2.0:
         return True
     else:
         return False
Esempio n. 27
0
 def __init__(self, nest, index, suitDnaName = 'le'):
     FSM.__init__(self, 'CogdoFlyingLegalEagle')
     self.defaultTransitions = {'Off' : ['Roost'],
                                'Roost' : ['TakeOff', 'Off'],
                                'TakeOff' : ['LockOnToon', 'LandOnNest', 'Off'],
                                'LockOnToon' : ['RetreatToNest', 'ChargeUpAttack', 'Off'],
                                'ChargeUpAttack' : ['RetreatToNest', 'Attack', 'Off'],
                                'Attack' : ['RetreatToSky', 'Off'],
                                'RetreatToSky' : ['Cooldown', 'Off'],
                                'Cooldown' : ['LockOnToon', 'LandOnNest', 'Off'],
                                'RetreatToNest' : ['LandOnNest', 'Off'],
                                'LandOnNest' : ['Roost', 'Off'],
                               }
     self.index = index
     self.nest = nest
     self.target = None
     self.isEagleInterested = False
     self.collSphere = None
     self.suit = Suit.Suit()
     d = SuitDNA.SuitDNA()
     d.newSuit(suitDnaName)
     self.suit.setDNA(d)
     self.suit.reparentTo(render)
     swapAvatarShadowPlacer(self.suit, 'legalEagle-%sShadowPlacer' % index)
     self.suit.setPos(self.nest.getPos(render))
     self.suit.setHpr(-180, 0, 0)
     self.suit.stash()
     self.prop = None
     self.attachPropeller()
     head = self.suit.find('**/joint_head')
     self.interestConeOrigin = self.nest.attachNewNode('fakeHeadNodePath')
     self.interestConeOrigin.setPos(render, head.getPos(render) + Vec3(0, Globals.LegalEagle.InterestConeOffset, 0))
     self.attackTargetPos = None
     self.startOfRetreatToSkyPos = None
     pathModel = CogdoUtil.loadFlyingModel('legalEaglePaths')
     self.chargeUpMotionPath = Mopath.Mopath(name='chargeUpMotionPath-%i' % self.index)
     self.chargeUpMotionPath.loadNodePath(pathModel.find('**/charge_path'))
     self.retreatToSkyMotionPath = Mopath.Mopath(name='retreatToSkyMotionPath-%i' % self.index)
     self.retreatToSkyMotionPath.loadNodePath(pathModel.find('**/retreat_path'))
     audioMgr = base.cogdoGameAudioMgr
     self._screamSfx = audioMgr.createSfx('legalEagleScream', self.suit)
     self.initIntervals()
     return
Esempio n. 28
0
    def turnUp(self, doInterval = DoIntervalDefault):
        """Turn up the card.

        doInterval -- if true do a sound and flip up animation

        """
        assert self.value != PlayingCardGlobals.Unknown
        self.faceUp = 1
        if doInterval:
            self.clearFlipIval()
            self.flipIval = Parallel(
                LerpHprInterval(self, self.FlipTime, Vec3(0,0,0)),
                SoundInterval(self.turnUpSound, node = self,
                              listenerNode = base.localAvatar,
                              cutOff=240)
                )
            self.flipIval.start()
        else:
            self.setR(0)
Esempio n. 29
0
 def _initCollisions(self):
     self._camCollRay = CollisionRay()
     camCollNode = CollisionNode('CameraToonRay')
     camCollNode.addSolid(self._camCollRay)
     camCollNode.setFromCollideMask(OTPGlobals.WallBitmask
                                    | OTPGlobals.CameraBitmask
                                    | ToontownGlobals.FloorEventBitmask
                                    | ToontownGlobals.CeilingBitmask)
     camCollNode.setIntoCollideMask(0)
     self._camCollNP = self._camera.attachNewNode(camCollNode)
     self._camCollNP.show()
     self._collOffset = Vec3(0, 0, 0.5)
     self._collHandler = CollisionHandlerQueue()
     self._collTrav = CollisionTraverser()
     self._collTrav.addCollider(self._camCollNP, self._collHandler)
     self._betweenCamAndToon = {}
     self._transNP = NodePath('trans')
     self._transNP.reparentTo(render)
     self._transNP.setTransparency(True)
     self._transNP.setAlphaScale(Globals.Camera.AlphaBetweenToon)
     self._transNP.setBin('fixed', 10000)
Esempio n. 30
0
    def _updateCollisions(self):
        pos = self._toon.getPos(self._camera) + self._collOffset
        self._camCollRay.setOrigin(pos)
        direction = -Vec3(pos)
        direction.normalize()
        self._camCollRay.setDirection(direction)
        self._collTrav.traverse(render)
        nodesInBetween = {}
        if self._collHandler.getNumEntries() > 0:
            self._collHandler.sortEntries()
            for entry in self._collHandler.getEntries():
                name = entry.getIntoNode().getName()
                if name.find('col_') >= 0:
                    np = entry.getIntoNodePath().getParent()
                    if np not in nodesInBetween:
                        nodesInBetween[np] = np.getParent()

        for np in list(nodesInBetween.keys()):
            if np in self._betweenCamAndToon:
                del self._betweenCamAndToon[np]
            else:
                np.setTransparency(True)
                np.wrtReparentTo(self._transNP)
                if np.getName().find('lightFixture') >= 0:
                    np.find('**/*floor_mesh').hide()
                elif np.getName().find('platform') >= 0:
                    np.find('**/*Floor').hide()

        for np, parent in list(self._betweenCamAndToon.items()):
            np.wrtReparentTo(parent)
            np.setTransparency(False)
            if np.getName().find('lightFixture') >= 0:
                np.find('**/*floor_mesh').show()
            elif np.getName().find('platform') >= 0:
                np.find('**/*Floor').show()

        self._betweenCamAndToon = nodesInBetween