def clearDownAnim(self, animSpanId): if self.actor and self.animSpanId == animSpanId and self.getDownAnimName(): self.actor.setControlEffect(self.getDownAnimName(), 0.0, self.partName) Actor.stop(self.actor, self.getDownAnimName(), self.partName) self.setDownAnimName(None, animSpanId) self.setDownAnimWeight(0.0, animSpanId)
class ModelNode(NodePath): """A base class for nodes that have a 3d model. Class hierarchy: NodePath --> ModelNode """ ANIMATIONS = [] def __init__(self, parent, model, name=""): NodePath.__init__(self, name) self.name = name if not self.ANIMATIONS: # Load static model self.model = loader.loadModel("models/%s.bam" % (model,)) else: # Load animated model animations = dict((name, "models/%s-%s.bam" % (model, name)) for name in self.ANIMATIONS) self.model = Actor("models/%s.bam" % (model,), animations) self.model.reparentTo(self) self.reparentTo(parent) def setup(self): """Reset object to default configuration""" raise NotImplementedError
def play(self, newAnim, fromFrame = None, toFrame = None, blendInT = 0, blendOutT = 0, blendInto = None): ival = self._ReducedAnimationMixer__getPlayIval(newAnim, fromFrame, toFrame) if ival: Actor.play(self.actor, newAnim, fromFrame = fromFrame, toFrame = toFrame) ival.start() ival.setT(0.01) self.addIvalToOwnedList(ival)
class Character(): def __init__(self): print "character started" # create the main character, the Fish def createFish(self): print "fish created" # create the bubble, which position is defined by the player's hand position def createBubble(self): print "bubble created" # create the target object def createRandomObject(self): print "random object created" def createWorm(self): self.worm = Actor("model/worm",{"dance":"model/worm_anim"}) self.worm.reparentTo(render) self.worm.setPos(-200,-900,20) self.worm.setHpr(0,0,0) self.worm.setScale(2, 2, 2) self.worm.loop("dance") cm = CardMaker("sombraWorm") cm.setFrame(-5, 5, -5, 5) return self.worm
def __animateEnv(self): TTC = self.environ toonHall = TTC.find('**/sz13:toon_landmark_TT_toonhall_DNARoot') render.setPythonTag("ToonHall", ToonHall(toonHall, toonHall.find('**/door_double_round_ur'))) phase_4 = 'phase_4/models/props/' self.fish = TTC.find('**/animated_prop_PetShopFishAnimatedProp_DNARoot') self.fish.removeNode() self.fish = Actor(phase_4 + 'exteriorfish-zero.bam', {'anim' : phase_4 + 'exteriorfish-swim.bam'}) self.fish.reparentTo(TTC.find('**/sz22:toon_landmark_TT_pet_shop_DNARoot')) self.fish.loop('anim') self.periscope = Actor(TTC.find('**/animated_prop_HQPeriscopeAnimatedProp_DNARoot'), copy = 0) self.periscope.reparentTo(render) self.periscope.loadAnims({'anim': 'phase_3.5/models/props/HQ_periscope-chan.bam'}) self.periscope.pose('anim', 0) self.periscopeTrack = Sequence(Wait(2.0), self.periscope.actorInterval('anim', startFrame=0, endFrame=40), Wait(0.7), self.periscope.actorInterval('anim', startFrame=40, endFrame=90), Wait(0.7), self.periscope.actorInterval('anim', startFrame=91, endFrame=121), Wait(0.7), self.periscope.actorInterval('anim', startFrame=121, endFrame=91), Wait(0.7), self.periscope.actorInterval('anim', startFrame=90, endFrame=40), Wait(0.7), self.periscope.actorInterval('anim', startFrame=40, endFrame=90), Wait(0.7), self.periscope.actorInterval('anim', startFrame=91, endFrame=121), Wait(0.5), self.periscope.actorInterval('anim', startFrame=121, endFrame=148), Wait(3.0)) self.periscopeTrack.loop() self.telescope = Actor(TTC.find('**/animated_prop_HQTelescopeAnimatedProp_DNARoot'), copy = 0) self.telescope.reparentTo(render) self.telescope.loadAnims({'anim': 'phase_3.5/models/props/HQ_telescope-chan.bam'}) self.telescope.pose('anim', 0) self.telescopeTrack = Sequence(Wait(5.0), self.telescope.actorInterval('anim', startFrame=0, endFrame=32), Wait(0.5), self.telescope.actorInterval('anim', startFrame=32, endFrame=78), Wait(0.5), self.telescope.actorInterval('anim', startFrame=79, endFrame=112), Wait(0.5), self.telescope.actorInterval('anim', startFrame=112, endFrame=79), Wait(0.5), self.telescope.actorInterval('anim', startFrame=78, endFrame=32), Wait(0.5), self.telescope.actorInterval('anim', startFrame=32, endFrame=78), Wait(0.5), self.telescope.actorInterval('anim', startFrame=79, endFrame=112), Wait(0.5), self.telescope.actorInterval('anim', startFrame=112, endFrame=148), Wait(4.0)) self.telescopeTrack.loop() #base.taskMgr.add(self.__moveClouds, "Move Clouds") self.__fixTrashcans() self.environ.flattenStrong() self.scene.addModel(self.environ) render.find('**/TTC').setPythonTag('Class', self)
class BombWeapon(Weapon): def __init__(self, x, y, z, angle, bullets, id, projZ): Weapon.__init__(self, x, y, z, angle, bullets, id, projZ) self.cooldown = 5.0 self.penalty = 2.0 self.ammo = 3 self.range = 25 self.playerid = id self.deploySound = loader.loadSfx("Sound/FX/bomb_deploy.wav") #each individual method is going to need to load its own model #FLAG: needs image def LoadModel(self): self.form = Actor("animations/gentlemanBomb_idle", {"idle":"animations/gentlemanBomb_idle", "shoot":"animations/gentlemanBomb_trigger"}) #self.form.reparentTo(render) def fire(self): """drops a bomb""" #note: bombs don't inherit from projectile class self.deploySound.play() new_bomb = Bomb(self.xpos, self.ypos, -30, self.angle-180, self.playerid, players) self.bullets.append(new_bomb) self.cooldown = 5.0 self.ammo -= 1 if self.form.getCurrentAnim() == "idle": self.form.loop('shoot')
def disableMixing(self): if self._UsesAnimationMixer__mixer: self._UsesAnimationMixer__mixer.cleanup() self._UsesAnimationMixer__mixer = None Actor.disableBlend(self) Actor.stop(self)
def initExitGate(self): station = self.areaGeometry.find('**/station') exitGate = station.find('**/stationGate') ground = station.find('**/ground*') self.exitGate = Actor('models/exitGate') self.exitGateAnim = self.exitGate.getAnimNames() self.exitGate.setHpr(render, station.getHpr(render)) self.exitGate.setPos(render, station.getPos(render)) self.exitGate.reparentTo(self.areaNode) self.oII = Actor('models/oii') oIIAnim = self.oII.getAnimNames() # No animation added yet # print 'oII anim:', oIIAnim #self.oII.setPlayRate(0.5, oIIAnim) self.oII.loop(oIIAnim, fromFrame=0, toFrame=50) exitPos = self.areaGameObjects.find('**/exitPos').getPos(render) self.oII.setPos(exitPos) self.oII.setZ(self.oII, 0.1) self.oII.reparentTo(self.areaNode) taskMgr.doMethodLater(1, self.areaTransitionChecker, 'areaTransitionCheckerTask')
class GattlingGun(Weapon): def __init__(self, x, y, z, angle, bullets, id, projZ): Weapon.__init__(self, x, y, z, angle, bullets, id, projZ) self.coodown = 0.3 self.penalty = 0.3 self.ammo = 100 self.gatSound = loader.loadSfx("Sound/FX/gattling_singleshot.wav") #using revolver proxy for now def LoadModel(self): self.form = Actor("animations/gentlemanGattling_idle", {"idle":"animations/gentlemanGattling_idle", "shoot":"animations/gentlemanGattling_trigger"}) #self.form.setScale(300) self.form.setPos(self.xpos,self.ypos,self.zpos) #self.form.setH(90) #self.form.reparentTo(render) def fire(self): """pulls the trigger""" Weapon.fire(self) self.gatSound.play() #self.bullets[len(self.bullets)-1].penalty = 0.3 self.cooldown = 0.3 self.ammo -= 1 if self.form.getCurrentAnim() == "idle": self.form.loop('shoot')
class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) #standard GeoMipTerrain usage self.terrain = GeoMipTerrain("worldTerrain") self.terrain.setHeightfield("mapheight.png") self.terrain.setColorMap("maptexture.png") #self.terrain.setBruteforce(True) #set dynamically updated terrain self.terrain.setBlockSize(32) self.terrain.setNearFar(128, 256) #distance in terrain coordinates self.terrain.setMinLevel(0) #low means high quality self.terrain.setFocalPoint(base.camera) #a NodePath #get root root = self.terrain.getRoot() root.reparentTo(render) root.setSz(100) self.terrain.generate() taskMgr.add(self.updateTask, "update") self.camera.setPos(0, 0, 0) #add person self.player = Actor("girl4.x", {"girl03_03": "girl"}) print("girl loaded") self.player.setPos(0, 5, -1) self.player.reparentTo(self.render) print("girl reparented") def updateTask(self, task): self.terrain.update() return task.cont
def __init__(self, species, gender, head, features, torso_size, legs_size, path=""): """ Args: species (str): "cat", "dog", "duck", "mouse", "pig", "rabbit", "bear", "horse" or "monkey". gender (str): "m" (male) or "f" (female). head (str): "n" (normal) or "l" (long). features (str): "n" (normal) or "l" (long). torso_size (str): "s" (small), "m" (medium) or "l" (long). legs_size (str): "s" (small), "m" (medium) or "l" (long). path (str, optional): The file path to the Toontown phase files. Defaults to Panda3D's search path. """ global MODEL_PATH if path: self.path = pfile.fromOsSpecific("%s/" % path).getFullpath() else: self.path = pfile.fromOsSpecific("%s/" % MODEL_PATH).getFullpath() self.species = species self.gender = gender self.dimensions = torso_size, legs_size self.__make_actor( species, gender, head, features, torso_size, legs_size ) Actor.__init__(self, self.parts, self.animation) self.__initialize_actor()
def loadPlaceGeom(self, zoneId): self.notify.info('loadPlaceGeom: %s' % zoneId) zoneId = zoneId - zoneId % 100 self.notify.debug('zoneId = %d ToontownGlobals.BossbotHQ=%d' % (zoneId, ToontownGlobals.BossbotHQ)) if zoneId == ToontownGlobals.BossbotHQ: self.geom = loader.loadModel(self.cogHQExteriorModelPath) gzLinkTunnel = self.geom.find('**/LinkTunnel1') gzLinkTunnel.setName('linktunnel_gz_17000_DNARoot') self.makeSigns() top = self.geom.find('**/TunnelEntrance') origin = top.find('**/tunnel_origin') origin.setH(-33.33) self.extra = Actor("phase_12/models/bossbotHQ/ttr_m_bossbothq_sky") self.extra.reparentTo(self.geom) self.extra.setPos(0,0,0) self.extra.setScale(2.0) elif zoneId == ToontownGlobals.BossbotLobby: if base.config.GetBool('want-qa-regression', 0): self.notify.info('QA-REGRESSION: COGHQ: Visit BossbotLobby') self.notify.debug('cogHQLobbyModelPath = %s' % self.cogHQLobbyModelPath) self.geom = loader.loadModel(self.cogHQLobbyModelPath) self.extra = Actor("phase_12/models/bossbotHQ/ttr_m_bossbothq_sky") self.extra.reparentTo(self.geom) self.extra.setPos(0,0,0) self.extra.setScale(2.0) else: self.notify.warning('loadPlaceGeom: unclassified zone %s' % zoneId) CogHQLoader.CogHQLoader.loadPlaceGeom(self, zoneId)
class Walker(NodePath): def __init__(self, heightFunction, x=0, y=0): NodePath.__init__(self, "Creature") self.reparentTo(render) self.startPosition = Vec2(x,y) z = heightFunction(x, y) self.setPos(x, y, z) # movement self.acceleration = 25 self.velocity = Vec3(0,0,0) self.maxSpeed = 10 self.speed = 0 self.maxAngularVelocity = 360 self.turbo = 1 self.maxStoppingDistance = self.maxSpeed / self.acceleration * 0.5 self.body = Actor("models/ralph", {"run":"models/ralph-run", "walk":"models/ralph-walk"}) self.body.setScale(0.25) self.body.reparentTo(self) self.heightFunction = heightFunction def accelerate(self, desiredVelocity, elapsed): acceleration = self.acceleration * elapsed):
def startEntity(self, cog): if not cog: self.completeSquirt() return scaleUpPoint = Point3(1.5, 1.5, 1.5) rainDelay = 1 effectDelay = 0.3 cloudHold = 4.7 tContact = 2.4 if cog.isDead(): cloudHold = 1.7 cloud01, trickleFx, rainEffects, entity = self.buildEntity() cloud01.setZ(cog.suitPlan.getNametagZ() + 2) cloud01.reparentTo(cog) cloud02 = Actor(self.model, {'chan': GagGlobals.getProp(4, 'stormcloud-chan')}) cloud02.reparentTo(cloud01) def damageCog(): if self.isLocal(): self.avatar.sendUpdate('suitHitByPie', [cog.doId, self.getID()]) def __getCloudTrack(cloud, useEffect = 1): track = Sequence(Func(cloud.pose, 'chan', 0), LerpScaleInterval(cloud, 1.5, scaleUpPoint, startScale=GagGlobals.PNT3NEAR0), Wait(rainDelay)) if useEffect == 1: pTrack = Parallel() delay = trickleDuration = cloudHold * 0.25 trickleTrack = ParticleInterval(trickleFx, cloud, worldRelative=0, duration=trickleDuration, cleanup=True) track.append(trickleTrack) for i in range(0, 3): dur = cloudHold - 2 * trickleDuration pTrack.append(Sequence(Wait(delay), ParticleInterval(rainEffects[i], cloud, worldRelative=0, duration=dur, cleanup=True))) delay += effectDelay pTrack.append(Sequence(Wait(3 * effectDelay), ActorInterval(cloud, 'chan', startTime=1, duration=cloudHold))) damageTrack = Sequence() if cog.getHealth() - self.getDamage() <= 0: damageTrack.append(Func(cog.d_disableMovement, wantRay=True)) damageTrack.append(Func(damageCog)) else: damageTrack.append(Wait(tContact)) damageTrack.append(Func(damageCog)) pTrack.append(damageTrack) track.append(pTrack) else: track.append(ActorInterval(cloud, 'chan', startTime=1, duration=cloudHold)) track.append(LerpScaleInterval(cloud, 0.5, GagGlobals.PNT3NEAR0)) track.append(Func(GagUtils.destroyProp, cloud)) return track tracks = Parallel() soundTrack01 = self.getSoundTrack(1.3, self.avatar) soundTrack02 = self.getSoundTrack(3.4, self.avatar) tracks.append(soundTrack01) tracks.append(soundTrack02) cloud01Track = __getCloudTrack(cloud01) cloud02Track = __getCloudTrack(cloud02, useEffect=0) tracks.append(cloud01Track) tracks.append(cloud02Track) tracks.append(Func(self.destroyEntity, entity)) tracks.start()
class Akis(Enemy): def createCharacter(self): self.shape = BulletBoxShape(Vec3(0.4, 0.4, 0.85)) self.actor = BulletRigidBodyNode('Akis') self.actor.setMass(5.0) self.np = self.render.attachNewNode(self.actor) self.np.node().addShape(self.shape) self.np.setPos(self.x, self.y, self.z) self.np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(self.np.node()) self.actorModelNP = Actor('models/SecurityGuard/SecurityGuard.egg', { 'run': 'models/SecurityGuard/SecurityGuard-run.egg'}) self.actorModelNP.reparentTo(self.np) self.actorModelNP.setScale(0.3048) self.actorModelNP.setH(180) self.actorModelNP.setPos(0, 0, 0.27) self.actorModelNP.loop('run') def move(self, player): playerNP = player.getCharacterNP() self.np.lookAt(playerNP.getX(), playerNP.getY(), self.np.getZ()) vec = playerNP.getPos() - self.np.getPos() vec.setZ(0) dist = vec.length() vec.normalize() self.np.setPos(self.np.getPos() + vec * dist * 0.01)
def __init__(self): ShowBase.__init__(self) base.disableMouse()#mouse disabled #rocky terrain load self.environ=loader.loadModel("models/environment") self.environ.reparentTo(render) self.environ.setScale(0.15,0.15,0.15) self.environ.setPos(0,-10,0) #loading the sky background self.sky=loader.loadModel("models/farmsky") self.sky.reparentTo(render) self.sky.setScale(0.3,0.3,0.3) self.sky.setPos(0,350,0) #baby dinosaur model self.babyd = Actor("babyd", {"sit": "babydani"}) self.babyd.reparentTo(render) self.babyd.setPos(Vec3(25,-150, 3)) self.babyd.loop("sit") #big dinosaur model self.bigd = Actor("bigd", {"roar": "bigdani"}) self.bigd.reparentTo(render) self.bigd.setPos(Vec3(30, -110, 0)) self.bigd.loop("roar") #trex model self.trex = Actor("trex", {"run": "trex-eat"}) self.trex.reparentTo(render) self.trex.loop("run") self.trex.setHpr(270,0,0) self.cam.setPos(-20, -200, 22) #trex animation trexPosInterval1 = self.trex.posInterval(3, Point3(-60,-120, 0), startPos = Point3( -10,-120, 0)) trexPosInterval2 = self.trex.posInterval(3, Point3(-60,0, 0), startPos = Point3( -60,-120, 0)) trexPosInterval3 = self.trex.posInterval(3, Point3(-10,0, 0), startPos = Point3( -60,0, 0)) trexPosInterval4 = self.trex.posInterval(3, Point3(-10,-120, 0), startPos = Point3( -10,0, 0)) trexHprInterval1 = self.trex.hprInterval(0.5, Point3(180, 0, 0), startHpr = Point3(270, 0, 0)) trexHprInterval2 = self.trex.hprInterval(0.5, Point3(90, 0, 0), startHpr = Point3(180, 0, 0)) trexHprInterval3 = self.trex.hprInterval(0.5, Point3(0, 0, 0), startHpr = Point3(90, 0, 0)) trexHprInterval4 = self.trex.hprInterval(0.5, Point3(-90, 0, 0), startHpr = Point3(0, 0, 0)) # Create and play the sequence that coordinates the intervals. self.pandaPace = Sequence(trexPosInterval1, trexHprInterval1, trexPosInterval2, trexHprInterval2,trexPosInterval3,trexHprInterval3,trexPosInterval4,trexHprInterval4, name="pandaPace") self.pandaPace.loop()
def loadAnimation(filename, animations): global modelFileSuffix for anim in animations: animations[anim] += modelFileSuffix a = Actor(filename + modelFileSuffix, animations) a.setBlend(frameBlend = True) return a
class World(DirectObject): #------------------------------------------------------ # def __init__(self): # self.setup_scene() # self.showtime() #------------------------------------------------------ # def showtime(self): '''relevant code for the sample ''' self.actor = Actor("panda", {"walk":"panda-walk"}) self.actor.setScale(.5, .5, .5) terra=loader.loadModel( 'environment' ) terra.reparentTo( base.render ) terra.setScale(3) # floor = loader.loadModel( 'environment' ) floor.reparentTo( base.render ) floor.setScale(3) floor.hide() #** here is where the physics happens self.phy=terra_physics(self.actor, floor, None) self.accept("space", lambda x=50: self.phy.avatarNP.setZ(x)) base.mouseInterfaceNode.setPos(-150, 30, 5) base.taskMgr.add(self.localtask, 'localtask' ) #-------------------------------------------------------------- # def localtask(self, task): base.camera.lookAt(self.actor) return Task.cont #------------------------------------------------------ # def setup_scene(self): # *** Setup lighting lightLevel=0.8 lightPos=(0.0,-10.0,10.0) lightHpr=(0.0,-26.0,0.0) dlight = DirectionalLight('dlight') dlight.setColor(VBase4(lightLevel, lightLevel, lightLevel, 1)) dlnp = render.attachNewNode(dlight.upcastToPandaNode()) dlnp.setHpr(lightHpr[0],lightHpr[1],lightHpr[2]) dlnp.setPos(lightPos[0],lightPos[1],lightPos[2]) render.setLight(dlnp) alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) # *** Setup scene base.setBackgroundColor(0.0,0.1,0.7,1.0) base.mouseInterfaceNode.setPos(3.9, 37.26, 3.8) base.mouseInterfaceNode.setHpr(-4.5, 35.4, 0.97) base.setFrameRateMeter(True)
def delete(self): try: self.Avatar_deleted except: self.Avatar_deleted = 1 self.removeLoopTask() Actor.delete(self)
def __init__(self, defaultAnimation, hasShoes): try: Actor.__init__(self, {"head":"models/tt_a_chr_dgm_shorts_head_1000.bam", "torso":"models/tt_a_chr_dgm_shorts_torso_1000.bam", "legs":"models/tt_a_chr_dgm_shorts_legs_1000.bam"}, {"head":{"neutral":"models/anim/toonHead/tt_a_chr_dgm_shorts_head_neutral.bam", "run":"models/anim/toonHead/tt_a_chr_dgm_shorts_head_run.bam", "runjump":"models/anim/toonHead/tt_a_chr_dgm_shorts_head_leap_zhang.bam", "walk":"models/anim/toonHead/tt_a_chr_dgm_shorts_head_walk.bam", "jump":"models/anim/toonHead/tt_a_chr_dgm_shorts_head_jump-zhang.bam"}, "torso":{"neutral":"models/anim/toonTorso/tt_a_chr_dgm_shorts_torso_neutral.bam", "run":"models/anim/toonTorso/tt_a_chr_dgm_shorts_torso_run.bam", "runjump":"models/anim/toonTorso/tt_a_chr_dgm_shorts_torso_leap_zhang.bam", "walk":"models/anim/toonTorso/tt_a_chr_dgm_shorts_torso_walk.bam", "jump":"models/anim/toonTorso/tt_a_chr_dgm_shorts_torso_jump-zhang.bam"}, "legs":{"neutral":"models/anim/toonLegs/tt_a_chr_dgm_shorts_legs_neutral.bam", "run":"models/anim/toonLegs/tt_a_chr_dgm_shorts_legs_run.bam", "runjump":"models/anim/toonLegs/tt_a_chr_dgm_shorts_legs_leap_zhang.bam", "walk":"models/anim/toonLegs/tt_a_chr_dgm_shorts_legs_walk.bam", "jump":"models/anim/toonLegs/tt_a_chr_dgm_shorts_legs_jump-zhang.bam"}}) self.loop(defaultAnimation) self.attach("head", "torso", "def_head") self.attach("torso", "legs", "joint_hips") except IOError: Log.sendError("err") Actor.__init__(self, 'models/err.egg') if hasShoes is False: self.find("**/shoes").hide() self.find("**/boots_short").hide() self.find("**/boots_long").hide()
class Gorrila(DirectObject): def __init__(self): DirectObject.__init__(self) self.collisionSphere = CollisionSphere(0,0,0,1) self.collisionNode = CollisionNode('gorrila') self.collisionNode.setCollideMask(BitMask32.bit(1)) self.collisionNode.addSolid(self.collisionSphere) self.collisionNodePath = render.attachNewNode(self.collisionNode) self.collisionNodePath.setPos(-9,5,1) base.cTrav.addCollider(self.collisionNodePath,base.collisionHandlerEvent) self.actor = Actor("arena/gorilla/gorillawalking",{"walk":"arena/gorilla/gorillawalking"}) self.actor.setScale(0.2,0.2,0.2) self.actor.setPos(0,0.3,-1) self.actor.reparentTo(self.collisionNodePath) self.actor.loop("walk") self.actor.showThrough() LerpPosInterval(self.collisionNodePath,10,Point3(-9,-5,1)).loop() LerpHprInterval(self.collisionNodePath,5,Vec3(360,0,0)).loop() base.cTrav.addCollider(self.collisionNodePath,base.collisionHandlerEvent) self.accept('mouseray-i-gorrila',self.collideIn) self.accept('mouseray-o-gorrila',self.collideOut) def collideIn(self,entry): base.arrow.highlight(self.collisionNodePath) def collideOut(self,entry): base.arrow.hide()
def __init__(self, id, name, model): # class properties self.id = id self.name = name self.modelType = model self.isMoving = False self.entity = render.attachNewNode("entity") self.target = render.attachNewNode("target") # set up model if model == Constants.CHAR_RALPH: self.model = Actor("models/ralph", {"run": "models/ralph-run", "walk": "models/ralph-walk"}) self.model.setScale(0.2) elif model == Constants.CHAR_PANDA: self.model = Actor("models/panda-model", {"run": "models/panda-walk4", "walk": "models/panda-walk4"}) self.model.setScale(0.001) elif model == Constants.CHAR_VEHICLE: self.model = Actor("models/car", {}) self.model.setScale(0.3) self.model.setPos(0, 0.2, 0.1) self.model.reparentTo(self.entity) # start movement task taskMgr.doMethodLater(1.0 / Constants.TICKRATE, self.move, "Character[" + str(id) + "].move")
class PostEffect(ShowBase): def __init__(self): ShowBase.__init__(self) self.disableMouse() base.setFrameRateMeter(True) self.accept("escape", sys.exit) self.setup_scene() self.setup_post_effect() def setup_scene(self): # Environment self.environ = self.loader.loadModel("models/environment") self.environ.reparentTo(self.render) self.environ.set_scale(0.25) self.environ.set_pos(-8, 42, 0) # Camera self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Panda self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.reparentTo(self.render) self.pandaActor.loop("walk") pandaPosInterval1 = self.pandaActor.posInterval(13, Point3(0, -10, 0), startPos=Point3(0, 10, 0)) pandaPosInterval2 = self.pandaActor.posInterval(13, Point3(0, 10, 0), startPos=Point3(0, -10, 0)) pandaHprInterval1 = self.pandaActor.hprInterval(3, Point3(180, 0, 0), startHpr=Point3(0, 0, 0)) pandaHprInterval2 = self.pandaActor.hprInterval(3, Point3(0, 0, 0), startHpr=Point3(180, 0, 0)) self.panda_pace = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace") self.panda_pace.loop() # The post-processing effect is set up here. def setup_post_effect(self): self.manager = FilterManager(base.win, base.cam) tex = Texture() dtex = Texture() quad = self.manager.renderSceneInto(colortex=tex, depthtex=dtex) quad.setShader(Shader.load(Shader.SL_GLSL, "vertex.glsl", "fragment.glsl")) quad.setShaderInput("tex", tex) quad.setShaderInput("dtex", dtex) # Define a procedure to move the camera. def spinCameraTask(self, task): angleDegrees = task.time * 6.0 angleRadians = angleDegrees * (pi / 180.0) self.camera.setPos(20 * sin(angleRadians), -20.0 * cos(angleRadians), 3) self.camera.setHpr(angleDegrees, 0, 0) return Task.cont
class MyApp(ShowBase): def __init__(self, q): ShowBase.__init__(self) # Disable the camera trackball controls. self.disableMouse() # Load the environment model. self.environ = self.loader.loadModel("models/environment") # Reparent the model to render. self.environ.reparentTo(self.render) # Apply scale and position transforms on the model. self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(-8, 42, 0) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Load and transform the panda actor. self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.reparentTo(self.render) # Loop its animation. self.pandaActor.loop("walk") # Create the four lerp intervals needed for the panda to # walk back and forth. pandaPosInterval1 = self.pandaActor.posInterval(13, Point3(0, -10, 0), startPos=Point3(0, 10, 0)) pandaPosInterval2 = self.pandaActor.posInterval(13, Point3(0, 10, 0), startPos=Point3(0, -10, 0)) pandaHprInterval1 = self.pandaActor.hprInterval(3, Point3(180, 0, 0), startHpr=Point3(0, 0, 0)) pandaHprInterval2 = self.pandaActor.hprInterval(3, Point3(0, 0, 0), startHpr=Point3(180, 0, 0)) # Create and play the sequence that coordinates the intervals. self.pandaPace = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace") self.pandaPace.loop() textObject = OnscreenText(text = 'My Text String', pos = (-0.5, 0.02), scale = 0.1, fg = (255,0,0,1)) # Define a procedure to move the camera. def spinCameraTask(self, task): angleDegrees = task.time * 6.0 angleRadians = angleDegrees * (pi / 180.0) self.camera.setPos(20 * sin(angleRadians), -20.0 * cos(angleRadians), 3) self.camera.setHpr(angleDegrees, 0, 0) return Task.cont
class Pokemao():#Inimigos): def __init__(self,render, num): self.nome = "Pokemao" self.agi = 10 self.hp = 10 self.int = 5 self.str = 1 self.dano = 5 self.bloqueio = False self.bloqueado = False self.velocAtaque = 0.5 self.arma = None self.escudo = None self.armadura = None self.delete = False self.render = render self.loadModels(num) self.setAI() def getPos(self): return self.pokemao.getPos() def loadModels(self,num): # Seeker pokemaoPos = Vec3(-10,-30.0,2.10) self.pokemao = Actor('personagens/Modelos/Pokeperna/p1', {"andar" :"personagens/Modelos/Pokeperna/p1-andar.egg", "saltar" :"personagens/Modelos/Pokeperna/p1-saltar.egg", "correr" : "personagens/Modelos/Pokeperna/p1-correr", "abaixar" : "personagens/Modelos/Pokeperna/p1-abaixar"}) self.pokemao.reparentTo(self.render) #self.wanderer.setScale(0.5) self.pokemao.setPos(pokemaoPos) self.pokemao.setTag("inimigo",str(num)) def setAI(self): #Creating AI World self.AIworld = AIWorld(self.render) self.AIchar = AICharacter("wanderer",self.pokemao, 100, 0.05, 5) self.AIworld.addAiChar(self.AIchar) self.AIbehaviors = self.AIchar.getAiBehaviors() self.AIbehaviors.wander(5, 0, 10, 1.0) self.pokemao.loop("correr") #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") #to update the AIWorld def AIUpdate(self,task): if self.hp < 1: #self.cleanup() self.pokemao.detachNode() self.delete = True self.AIworld.update() return Task.cont
def enableMixing(self): if self._UsesAnimationMixer__mixer != self.animationMixer: self.disableMixing() self._UsesAnimationMixer__mixer = self.animationMixer if self._UsesAnimationMixer__mixer: Actor.enableBlend(self) self._UsesAnimationMixer__mixer.cleanup()
def play(self, newAnim, partName = None, fromFrame = None, toFrame = None, blendInT = defaultBlendT, blendOutT = defaultBlendT, blendInto = None): partNames = self.getPartsNameList(self.getSectionList(partName)) ival = self._AnimationMixer__getPlayIval(newAnim, partName, fromFrame, toFrame, blendInT, blendOutT, blendInto = blendInto) if ival: Actor.play(self.actor, newAnim, partName = partNames, fromFrame = fromFrame, toFrame = toFrame) ival.start() ival.setT(0.01) self.addIvalToOwnedList(ival)
def __init__(self, name, parentSpell, properties, modifiersList=[]): actorNP = Actor(properties['modelPath'], properties['anims']) actorNP.setName(name) GameObject.__init__(self, actorNP) self.parentSpell = parentSpell self.properties = properties
class GH_Sprinter(GUnit): def __init__(self,conf): self.p3dobject=Actor('data/models/units/v_sprinter.egg', {'run':'data/models/units/v_sprinter-run.egg', } ) GUnit.__init__(self,conf) self.p3dobject.setName('GH_Sprinter_'+str(self.eid))
def pose(self, newAnim, frame, partName = None, blendT = defaultBlendT): ival = self._AnimationMixer__getPoseIval(newAnim, partName, frame, blendT) if ival: partName = self.getPartsNameList(self.getSectionList(partName)) Actor.pose(self.actor, newAnim, frame = frame, partName = partName) ival.start() ival.setT(0.01) self.addIvalToOwnedList(ival)
class Monster(): def __init__(self, setup_data, common, level=1.0, start_pos=(0, 0, 0)): common['monsterList'].append(self) id = len(common['monsterList']) - 1 self.monsterList = common['monsterList'] self.waypoints_data = common['waypoints_data'] self.waypoints = common['waypoints'] self.audio3d = common['audio3d'] self.common = common # root node self.node = render.attachNewNode("monster") self.sound_node = None self.soundset = None self.actor = Actor(setup_data["model"], setup_data["anim"]) self.actor.setBlend(frameBlend=True) self.actor.reparentTo(self.node) self.actor.setScale(setup_data["scale"] * random.uniform(0.9, 1.1)) self.actor.setH(setup_data["heading"]) self.actor.setBin("opaque", 10) self.rootBone = self.actor.exposeJoint(None, 'modelRoot', setup_data["root_bone"]) # sounds self.soundID = self.common['soundPool'].get_id() self.common['soundPool'].set_target(self.soundID, self.node) self.sound_names = { "hit": setup_data["hit_sfx"], "arrow_hit": setup_data["arrowhit_sfx"], "attack": setup_data["attack_sfx"], "die": setup_data["die_sfx"] } self.vfx = setup_data["hit_vfx"] self.stats = { "speed": setup_data["speed"], "hp": setup_data["hp"] * level, "armor": setup_data["armor"] * level, "dmg": setup_data["dmg"] * level } if self.stats['hp'] > 300: self.stats['hp'] = 300 self.maxHP = self.stats['hp'] self.HPring = Actor("models/ring_morph", {'anim': 'models/ring_anim'}) self.HPring.setScale(0.07) self.HPring.setZ(0.4) self.HPring.setLightOff() self.HPring.reparentTo(self.node) self.HPvis = self.HPring.controlJoint(None, 'modelRoot', 'morph01') self.HPvis.setX(self.stats['hp'] / 300) self.HPring.hide(BitMask32.bit(1)) self.HPring.hide() #self.HPring.setColorScale(0.0, 1.0, 0.0, 1.0) # gamestate variables self.attack_pattern = setup_data["attack_pattern"] self.damage = setup_data["dmg"] # self.HP=setup_data["hp"] self.state = "STOP" self.id = id self.nextWaypoint = None self.canSeePC = False self.PCisInRange = False self.PC = common['PC'] self.speed_mode = random.randrange(0 + int(level), 42 + int(level), 7) / 100.0 self.totalSpeed = self.stats['speed'] + self.speed_mode self.sparkSum = 0 self.lastMagmaDmg = 0 self.DOT = 0 self.arrows = set() self.traverser = CollisionTraverser("Trav" + str(self.id)) # self.traverser.showCollisions(render) self.queue = CollisionHandlerQueue() # bit masks: # 1 visibility polygons & coll-rays # 2 walls & radar-ray # 3 spheres # collision ray for testing visibility polygons coll = self.node.attachNewNode(CollisionNode('collRay')) coll.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -180)) coll.setTag("id", str(id)) coll.node().setIntoCollideMask(BitMask32.allOff()) coll.node().setFromCollideMask(BitMask32.bit(1)) self.traverser.addCollider(coll, self.queue) # radar collision ray self.radar = self.node.attachNewNode(CollisionNode('radarRay')) self.radar.node().addSolid(CollisionRay(0, 0, 1, 0, 90, 0)) self.radar.node().setIntoCollideMask(BitMask32.allOff()) self.radar.node().setFromCollideMask(BitMask32.bit(2)) self.radar.setTag("radar", str(id)) # self.radar.show() self.traverser.addCollider(self.radar, self.queue) # collision sphere self.coll_sphere = self.node.attachNewNode( CollisionNode('monsterSphere')) self.coll_sphere.node().addSolid(CollisionSphere(0, 0, 0.8, 0.8)) self.coll_sphere.setTag("id", str(id)) self.coll_sphere.node().setIntoCollideMask(BitMask32.bit(3)) # coll_sphere.show() # other monster blocking self.coll_quad = loader.loadModel("models/plane") self.coll_quad.reparentTo(self.node) # coll_quad=render.attachNewNode(CollisionNode('monsterSphere')) #coll_quad.node().addSolid(CollisionPolygon(Point3(-.5, -.5, 2), Point3(-.5, .5, 0), Point3(.5, .5, 0), Point3(.5, .5, 2))) #coll_quad.setTag("id", str(id)) # coll_quad.node().setIntoCollideMask(BitMask32.bit(2)) # coll_quad.reparentTo(self.node) # coll_quad.show() Sequence(Wait(random.uniform(.6, .8)), Func(self.restart)).start() self.node.setPos(render, start_pos) taskMgr.add(self.runAI, "AIfor" + str(self.id)) taskMgr.doMethodLater(.6, self.runCollisions, 'collFor' + str(self.id)) taskMgr.doMethodLater(1.0, self.damageOverTime, 'DOTfor' + str(self.id)) def damageOverTime(self, task): if self.state == "DIE": return task.done if self.DOT > 0: self.doDamage(self.DOT) self.DOT = int((self.DOT * 0.9) - 1.0) if self.stats['hp'] < 1: self.actor.play("die") #self.common['soundPool'].play(self.soundID, self.sound_names["hit"]) self.common['soundPool'].play(self.soundID, self.sound_names["die"]) self.state = "DIE" vfx(self.node, texture=self.vfx, scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.016, 24) return task.again def restart(self): self.state = "SEEK" def check_stacking(self): for monster in self.monsterList: if monster and monster.id != self.id: if self.node.getDistance(monster.node) < .8: if monster.state != "STOP" and self.state == "SEEK": if self.totalSpeed <= monster.totalSpeed: self.state = "STOP" self.actor.stop() Sequence(Wait(1.5), Func(self.restart)).start() return True def doDamage(self, damage, igoreArmor=False): if self.state == "DIE": return if not igoreArmor: damage -= self.stats['armor'] if damage < 1: damage = 1 # print damage self.stats['hp'] -= damage scale = self.stats['hp'] / self.maxHP self.HPvis.setX(self.stats['hp'] / 300.0) #self.HPring.setColor(0.8*(1.0-scale), 0.8*scale, 0.0, 1.0) self.HPring.show() self.HPring.setColorScale((1.0 - scale), scale, 0.0, 1.0) if self.stats['hp'] < 1: self.HPring.hide() def attack(self, pattern): if self.state == "DIE": return if not self.PC.node: return if pattern: next = pattern.pop() else: self.state = "SEEK" self.PCisInRange = False return if self.PC.node and self.node: range = self.node.getDistance(self.PC.node) else: return # print range if range < 1.8: self.PC.hit(self.damage) Sequence(Wait(next), Func(self.attack, pattern)).start() def onMagmaHit(self): if self.state == "DIE": return damage = self.lastMagmaDmg self.doDamage(damage) self.common['soundPool'].play(self.soundID, "onFire") vfx(self.node, texture="vfx/small_flame.png", scale=.6, Z=.7, depthTest=False, depthWrite=False).start(0.016, stopAtFrame=24) if self.stats['hp'] < 1: self.actor.play("die") self.common['soundPool'].play(self.soundID, "die3") self.state = "DIE" vfx(self.node, texture=self.vfx, scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.016) def onPlasmaHit(self, damage): if self.state == "DIE": return self.doDamage(damage * 1.5, True) # self.soundset["spark"].play() #self.common['soundPool'].play(self.soundID, "spark") if self.stats['hp'] < 1: self.actor.play("die") # self.soundset["die3"].play() self.common['soundPool'].play(self.soundID, "die3") self.state = "DIE" vfx(self.node, texture=self.vfx, scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.016) # else: # short_vfx(self.node, texture="vfx/short_spark.png",scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.03) def onSparkHit(self, damage): if self.state == "DIE": return # print damage self.doDamage(damage) # self.soundset["spark"].play() self.common['soundPool'].play(self.soundID, "spark") if self.stats['hp'] < 1: self.actor.play("die") # self.soundset["die3"].play() self.common['soundPool'].play(self.soundID, "die3") self.state = "DIE" vfx(self.node, texture=self.vfx, scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.016) else: short_vfx(self.node, texture="vfx/short_spark.png", scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.03) def onHit(self, damage, sound="hit"): if self.state == "DIE": return self.doDamage(damage) # print damage vfx(self.node, texture=self.vfx, scale=.5, Z=1.0, depthTest=True, depthWrite=True).start(0.016) if self.stats['hp'] < 1: self.actor.play("die") # self.sounds["die"].play() if sound: self.common['soundPool'].play(self.soundID, self.sound_names[sound]) self.common['soundPool'].play(self.soundID, self.sound_names["die"]) self.state = "DIE" else: # self.sounds["hit"].play() if sound: self.common['soundPool'].play(self.soundID, self.sound_names[sound]) def findFirstWaypoint(self): min = 100000 nearest = None for waypoint in self.waypoints: dist = self.node.getDistance(waypoint) if dist < min: min = dist nearest = waypoint return nearest def runCollisions(self, task): if self.state == "DIE": return task.done if self.node.getDistance(self.PC.node) > 50.0: self.nextWaypoint = None return task.again if self.check_stacking(): return task.again self.radar.lookAt(self.PC.node) valid_waypoints = [] isFirstTest = True self.canSeePC = False self.traverser.traverse(render) self.queue.sortEntries() for entry in self.queue.getEntries(): if entry.getFromNodePath().hasTag( "id"): # it's the monsters collRay # visibility polygons valid_waypoints.append( int(entry.getIntoNodePath().getTag("index"))) elif entry.getFromNodePath().hasTag("radar"): # it's the radar-ray # print "radar hit", entry.getIntoNodePath() if isFirstTest: isFirstTest = False # print "first hit!" # print "radar hit", entry.getIntoNodePath() if entry.getIntoNodePath().hasTag("player"): self.canSeePC = True '''distance={} for target in self.PC.myWaypoints: for waypoint in valid_waypoints: distance[target]=self.waypoints_data[target][waypoint] print(target, distance[target]) if distance: self.nextWaypoint=self.waypoints[min(distance, key=distance.get)] #print self.canSeePC''' if not valid_waypoints: # self.nextWaypoint=self.findFirstWaypoint() print(self.id, ": I'm lost!") valid_waypoints = [self.findFirstWaypoint()] # return task.again if self.state == "STOP": self.nextWaypoint = self.waypoints[random.choice(valid_waypoints)] return task.again best_distance = 9000000 target_node = None for target in self.PC.myWaypoints: for valid in valid_waypoints: distance = self.waypoints_data[target][valid] # print "target->valid=",target, valid, distance if distance < best_distance: best_distance = distance target_node = valid if target_node: self.nextWaypoint = self.waypoints[target_node] else: # print "no target", valid_waypoints self.nextWaypoint = self.findFirstWaypoint() # self.waypoints[random.choice(valid_waypoints)] # print self.nextWaypoint return task.again def runAI(self, task): # print self.state if self.state == "DIE": self.coll_sphere.node().setIntoCollideMask(BitMask32.allOff()) self.coll_quad.removeNode() self.actor.play("die") self.common["kills"] -= 1 if self.common["kills"] == 0: Interactive(self.common, data.items['key'], self.node.getPos(render)) elif random.randrange(10) == 0: Interactive(self.common, data.items['potion'], self.node.getPos(render)) Sequence( Wait(2.0), LerpPosInterval( self.node, 2.0, VBase3(self.node.getX(), self.node.getY(), self.node.getZ() - 5)), Func(self.destroy)).start() return task.done elif self.state == "STOP": target = self.nextWaypoint if not target: return task.again self.node.headsUp(target) if self.node.getDistance(target) > 0.3: self.node.setY(self.node, self.totalSpeed * globalClock.getDt()) if (self.actor.getCurrentAnim() != "walk"): self.actor.loop("walk") return task.again elif self.state == "ATTACK": self.node.headsUp(self.PC.node) if (self.actor.getCurrentAnim() != "attack"): self.actor.play("attack") #Sequence(Wait(self.attack_pattern[-1]+self.speed_mode), Func(self.attack, list(self.attack_pattern))).start() Sequence(Wait(self.attack_pattern[-1]), Func(self.attack, list(self.attack_pattern))).start() return task.again elif self.state == "SEEK": if self.PCisInRange: self.state = "ATTACK" return task.again target = self.nextWaypoint if self.canSeePC and self.PC.HP > 0: target = self.PC.node # print "target pc!" if not target: return task.again self.node.headsUp(target) if self.node.getDistance(target) > 0.3: self.node.setY(self.node, self.totalSpeed * globalClock.getDt()) if (self.actor.getCurrentAnim() != "walk"): self.actor.loop("walk") return task.again else: # print "I'm stuck?" # print target # print self.canSeePC self.nextWaypoint = self.PC.node return task.again def destroy(self): # for sound in self.soundset: # self.soundset[sound].stop() # print "destroy:", # self.sound_node.reparentTo(render) # self.common['soundPool'].append([self.sound_node,self.soundset]) self.common['soundPool'].set_free(self.soundID) # self.sounds=None # print " sounds", self.arrows = None if self.actor: self.actor.cleanup() self.actor.removeNode() # print " actor", if taskMgr.hasTaskNamed("AIfor" + str(self.id)): taskMgr.remove("AIfor" + str(self.id)) # print " AI", if taskMgr.hasTaskNamed('collFor' + str(self.id)): taskMgr.remove('collFor' + str(self.id)) # print " collision", if taskMgr.hasTaskNamed('DOTfor' + str(self.id)): taskMgr.remove('DOTfor' + str(self.id)) if self.node: self.node.removeNode() # print " node", self.monsterList[self.id] = None self.traverser = None self.queue = None
class DistributedPartyFireworksActivity(DistributedPartyActivity, FireworkShowMixin): notify = directNotify.newCategory('DistributedPartyFireworksActivity') def __init__(self, cr): DistributedPartyFireworksActivity.notify.debug('__init__') DistributedPartyActivity.__init__(self, cr, ActivityIds.PartyFireworks, ActivityTypes.HostInitiated, wantLever=True) FireworkShowMixin.__init__(self, restorePlaygroundMusic=True, startDelay=FireworksPostLaunchDelay) def setEventId(self, eventId): DistributedPartyFireworksActivity.notify.debug('setEventId( %s )' % FireworkShows.getString(eventId)) self.eventId = eventId def setShowStyle(self, showStyle): DistributedPartyFireworksActivity.notify.debug('setShowStyle( %d )' % showStyle) self.showStyle = showStyle def setSongId(self, songId): self.songId = songId def load(self): DistributedPartyFireworksActivity.notify.debug('load') DistributedPartyActivity.load(self) self.eventId = PartyGlobals.FireworkShows.Summer self.launchPadModel = loader.loadModel('phase_13/models/parties/launchPad') self.launchPadModel.setH(90.0) self.launchPadModel.setPos(0.0, -18.0, 0.0) self.launchPadModel.reparentTo(self.root) railingsCollection = self.launchPadModel.findAllMatches('**/launchPad_mesh/*railing*') for i in xrange(railingsCollection.getNumPaths()): railingsCollection[i].setAttrib(AlphaTestAttrib.make(RenderAttrib.MGreater, 0.75)) leverLocator = self.launchPadModel.find('**/RocketLever_locator') self.lever.setPosHpr(Vec3.zero(), Vec3.zero()) self.lever.reparentTo(leverLocator) self.toonPullingLeverInterval = None self.sign.reparentTo(self.launchPadModel.find('**/launchPad_sign_locator')) 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) 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.ogg') self.activityFSM = FireworksActivityFSM(self) self.activityFSM.request('Idle') return def unload(self): DistributedPartyFireworksActivity.notify.debug('unload') taskMgr.remove(self.taskName('delayedStartShow')) if self.rocketParticleSeq: self.rocketParticleSeq.pause() self.rocketParticleSeq = None self.launchPadModel.removeNode() del self.launchPadModel del self.toonPullingLeverInterval self.rocketActor.delete() self.rocketExplosionEffect.destroy() self.activityFSM.request('Disabled') del self.rocketActor del self.launchSound del self.activityFSM del self.eventId del self.showStyle DistributedPartyActivity.unload(self) return def _leverPulled(self, collEntry): DistributedPartyFireworksActivity.notify.debug('_leverPulled') hostPulledLever = DistributedPartyActivity._leverPulled(self, collEntry) if self.activityFSM.getCurrentOrNextState() == 'Active': self.showMessage(TTLocalizer.PartyFireworksAlreadyActive) elif self.activityFSM.getCurrentOrNextState() == 'Disabled': self.showMessage(TTLocalizer.PartyFireworksAlreadyDone) elif self.activityFSM.getCurrentOrNextState() == 'Idle': if hostPulledLever: base.cr.playGame.getPlace().fsm.request('activity') self.toonPullingLeverInterval = self.getToonPullingLeverInterval(base.localAvatar) self.toonPullingLeverInterval.append(Func(self.d_toonJoinRequest)) self.toonPullingLeverInterval.append(Func(base.cr.playGame.getPlace().fsm.request, 'walk')) self.toonPullingLeverInterval.start() else: self.showMessage(TTLocalizer.PartyOnlyHostLeverPull) def setState(self, newState, timestamp): DistributedPartyFireworksActivity.notify.debug('setState( newState=%s, ... )' % newState) DistributedPartyActivity.setState(self, newState, timestamp) if newState == 'Active': self.activityFSM.request(newState, timestamp) else: self.activityFSM.request(newState) def startIdle(self): DistributedPartyFireworksActivity.notify.debug('startIdle') def finishIdle(self): DistributedPartyFireworksActivity.notify.debug('finishIdle') def startActive(self, showStartTimestamp): DistributedPartyFireworksActivity.notify.debug('startActive') messenger.send(FireworksStartedEvent) timeSinceStart = globalClockDelta.localElapsedTime(showStartTimestamp) if timeSinceStart > self.rocketActor.getDuration('launch'): self.rocketActor.hide() if timeSinceStart < 60: self.startShow(self.eventId, self.showStyle, self.songId, showStartTimestamp) else: self.rocketActor.play('launch') self.rocketParticleSeq = Sequence(Wait(RocketSoundDelay), Func(base.playSfx, self.launchSound), Func(self.rocketExplosionEffect.start), Wait(RocketDirectionDelay), LerpHprInterval(self.rocketActor, 4.0, Vec3(0, 0, -60)), Func(self.rocketExplosionEffect.end), Func(self.rocketActor.hide)) self.rocketParticleSeq.start() taskMgr.doMethodLater(FireworksPostLaunchDelay, self.startShow, self.taskName('delayedStartShow'), extraArgs=[self.eventId, self.showStyle, self.songId, showStartTimestamp, self.root]) def finishActive(self): self.rocketParticleSeq = None DistributedPartyFireworksActivity.notify.debug('finishActive') messenger.send(FireworksFinishedEvent) taskMgr.remove(self.taskName('delayedStartShow')) FireworkShowMixin.disable(self) return def startDisabled(self): DistributedPartyFireworksActivity.notify.debug('startDisabled') if not self.rocketActor.isEmpty(): self.rocketActor.hide() def finishDisabled(self): DistributedPartyFireworksActivity.notify.debug('finishDisabled') def handleToonDisabled(self, toonId): self.notify.warning('handleToonDisabled no implementation yet')
def __init__(self, setup_data, common, level=1.0, start_pos=(0, 0, 0)): common['monsterList'].append(self) id = len(common['monsterList']) - 1 self.monsterList = common['monsterList'] self.waypoints_data = common['waypoints_data'] self.waypoints = common['waypoints'] self.audio3d = common['audio3d'] self.common = common # root node self.node = render.attachNewNode("monster") self.sound_node = None self.soundset = None self.actor = Actor(setup_data["model"], setup_data["anim"]) self.actor.setBlend(frameBlend=True) self.actor.reparentTo(self.node) self.actor.setScale(setup_data["scale"] * random.uniform(0.9, 1.1)) self.actor.setH(setup_data["heading"]) self.actor.setBin("opaque", 10) self.rootBone = self.actor.exposeJoint(None, 'modelRoot', setup_data["root_bone"]) # sounds self.soundID = self.common['soundPool'].get_id() self.common['soundPool'].set_target(self.soundID, self.node) self.sound_names = { "hit": setup_data["hit_sfx"], "arrow_hit": setup_data["arrowhit_sfx"], "attack": setup_data["attack_sfx"], "die": setup_data["die_sfx"] } self.vfx = setup_data["hit_vfx"] self.stats = { "speed": setup_data["speed"], "hp": setup_data["hp"] * level, "armor": setup_data["armor"] * level, "dmg": setup_data["dmg"] * level } if self.stats['hp'] > 300: self.stats['hp'] = 300 self.maxHP = self.stats['hp'] self.HPring = Actor("models/ring_morph", {'anim': 'models/ring_anim'}) self.HPring.setScale(0.07) self.HPring.setZ(0.4) self.HPring.setLightOff() self.HPring.reparentTo(self.node) self.HPvis = self.HPring.controlJoint(None, 'modelRoot', 'morph01') self.HPvis.setX(self.stats['hp'] / 300) self.HPring.hide(BitMask32.bit(1)) self.HPring.hide() #self.HPring.setColorScale(0.0, 1.0, 0.0, 1.0) # gamestate variables self.attack_pattern = setup_data["attack_pattern"] self.damage = setup_data["dmg"] # self.HP=setup_data["hp"] self.state = "STOP" self.id = id self.nextWaypoint = None self.canSeePC = False self.PCisInRange = False self.PC = common['PC'] self.speed_mode = random.randrange(0 + int(level), 42 + int(level), 7) / 100.0 self.totalSpeed = self.stats['speed'] + self.speed_mode self.sparkSum = 0 self.lastMagmaDmg = 0 self.DOT = 0 self.arrows = set() self.traverser = CollisionTraverser("Trav" + str(self.id)) # self.traverser.showCollisions(render) self.queue = CollisionHandlerQueue() # bit masks: # 1 visibility polygons & coll-rays # 2 walls & radar-ray # 3 spheres # collision ray for testing visibility polygons coll = self.node.attachNewNode(CollisionNode('collRay')) coll.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -180)) coll.setTag("id", str(id)) coll.node().setIntoCollideMask(BitMask32.allOff()) coll.node().setFromCollideMask(BitMask32.bit(1)) self.traverser.addCollider(coll, self.queue) # radar collision ray self.radar = self.node.attachNewNode(CollisionNode('radarRay')) self.radar.node().addSolid(CollisionRay(0, 0, 1, 0, 90, 0)) self.radar.node().setIntoCollideMask(BitMask32.allOff()) self.radar.node().setFromCollideMask(BitMask32.bit(2)) self.radar.setTag("radar", str(id)) # self.radar.show() self.traverser.addCollider(self.radar, self.queue) # collision sphere self.coll_sphere = self.node.attachNewNode( CollisionNode('monsterSphere')) self.coll_sphere.node().addSolid(CollisionSphere(0, 0, 0.8, 0.8)) self.coll_sphere.setTag("id", str(id)) self.coll_sphere.node().setIntoCollideMask(BitMask32.bit(3)) # coll_sphere.show() # other monster blocking self.coll_quad = loader.loadModel("models/plane") self.coll_quad.reparentTo(self.node) # coll_quad=render.attachNewNode(CollisionNode('monsterSphere')) #coll_quad.node().addSolid(CollisionPolygon(Point3(-.5, -.5, 2), Point3(-.5, .5, 0), Point3(.5, .5, 0), Point3(.5, .5, 2))) #coll_quad.setTag("id", str(id)) # coll_quad.node().setIntoCollideMask(BitMask32.bit(2)) # coll_quad.reparentTo(self.node) # coll_quad.show() Sequence(Wait(random.uniform(.6, .8)), Func(self.restart)).start() self.node.setPos(render, start_pos) taskMgr.add(self.runAI, "AIfor" + str(self.id)) taskMgr.doMethodLater(.6, self.runCollisions, 'collFor' + str(self.id)) taskMgr.doMethodLater(1.0, self.damageOverTime, 'DOTfor' + str(self.id))
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Add a directional light dPos = Vec3(40, 40, 40) dirLight = DirectionalLight() dirLight.setDirection(dPos) dirLight.setShadowMapResolution(2048) dirLight.setPssmTarget(self.cam, self.camLens) # dirLight.setAmbientColor(Vec3(0.1,0.1,0.1)) dirLight.setCastsShadows(True) dirLight.setPos(dPos) dirLight.setColor(Vec3(6)) self.renderPipeline.addLight(dirLight) self.renderPipeline.globalIllum.setTargetLight(dirLight) self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.find("**/wall").removeNode() # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # NOTICE: It is important that your update tasks have a lower priority # than -10000 taskMgr.add(self.move, "moveTask", priority=-20000) self.accept("r", self.reloadShader) # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.ralphGroundColNp.show() # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Add earth scattering self.renderPipeline.enableDefaultEarthScattering() self.prepareSRGB(render) self.loadSkybox() self.reloadShader()
class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Load the environment model. self.scene = self.loader.loadModel("models/environment") # Reparent the model to render. self.scene.reparentTo(self.render) # Apply scale and position transforms on the model. self.scene.setScale(0.5, 0.5, 0.5) self.scene.setColor(255, 0, 0, 2) self.scene.setPos(-16, 84, 0) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # PANDA FUNCTION def panda1(x, r1, g1, b1, r2, g2, b2, r3, g3, b3, v1, v2, v3, u1, u2, u3): # Load medium-sized panda self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) # medium scale self.pandaActor.setColorScale(r2, g2, b2, 100) self.pandaActor.reparentTo(self.render) # Leg movement animation self.pandaActor.loop("walk") # Walking animation pandaPosInterval1 = self.pandaActor.posInterval(v2, Point3(x, -10, 5), startPos=Point3( x, 10, 5)) pandaPosInterval2 = self.pandaActor.posInterval(v2, Point3(x, 10, 5), startPos=Point3( x, -10, 5)) pandaHprInterval1 = self.pandaActor.hprInterval(u2, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval2 = self.pandaActor.hprInterval(u2, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace") self.pandaPace.loop() # Load small panda self.pandaActor2 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor2.setScale(0.0025, 0.0025, 0.0025) # small scale self.pandaActor2.setColorScale(r1, g1, b1, 100) self.pandaActor2.reparentTo(self.render) # Leg movement animation self.pandaActor2.loop("walk") # Walking animation pandaPosInterval3 = self.pandaActor2.posInterval(v1, Point3(x, -10, 0), startPos=Point3( x, 10, 7.5)) pandaPosInterval4 = self.pandaActor2.posInterval( v1, Point3(x, 10, 7.5), startPos=Point3(x, -10, 0)) pandaHprInterval3 = self.pandaActor2.hprInterval(u1, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval4 = self.pandaActor2.hprInterval(u1, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace2 = Sequence(pandaPosInterval3, pandaHprInterval3, pandaPosInterval4, pandaHprInterval4, name="pandaPace2") self.pandaPace2.loop() # Load big panda self.pandaActor3 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor3.setScale(0.01, 0.01, 0.01) # large scale self.pandaActor3.setColorScale(r3, g3, b3, 1) self.pandaActor3.reparentTo(self.render) # Leg movement animation. self.pandaActor3.loop("walk") # Walking animation pandaPosInterval5 = self.pandaActor3.posInterval( v3, Point3(x, -10, 7.5), startPos=Point3(x, 10, 0)) pandaPosInterval6 = self.pandaActor3.posInterval(v3, Point3(x, 10, 0), startPos=Point3( x, -10, 7.5)) pandaHprInterval5 = self.pandaActor3.hprInterval(u3, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval6 = self.pandaActor3.hprInterval(u3, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace3 = Sequence(pandaPosInterval5, pandaHprInterval5, pandaPosInterval6, pandaHprInterval6, name="pandaPace3") self.pandaPace3.loop() # PANDA FUNCTION 2 def panda2(x, r1, g1, b1, r2, g2, b2, r3, g3, b3, v1, v2, v3, u1, u2, u3): # Load medium-sized panda self.pandaActor4 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor4.setScale(0.005, 0.005, 0.005) # medium scale self.pandaActor4.setColorScale(r2, g2, b2, 100) self.pandaActor4.reparentTo(self.render) # Leg movement animation self.pandaActor4.loop("walk") # Walking animation pandaPosInterval1 = self.pandaActor4.posInterval(v2, Point3(x, -10, 5), startPos=Point3( x, 10, 5)) pandaPosInterval2 = self.pandaActor4.posInterval(v2, Point3(x, 10, 5), startPos=Point3( x, -10, 5)) pandaHprInterval1 = self.pandaActor4.hprInterval(u2, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval2 = self.pandaActor4.hprInterval(u2, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace4 = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace4") self.pandaPace4.loop() # Load small panda self.pandaActor5 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor5.setScale(0.0025, 0.0025, 0.0025) # small scale self.pandaActor5.setColorScale(r1, g1, b1, 100) self.pandaActor5.reparentTo(self.render) # Leg movement animation self.pandaActor5.loop("walk") # Walking animation pandaPosInterval3 = self.pandaActor5.posInterval(v1, Point3(x, -10, 0), startPos=Point3( x, 10, 7.5)) pandaPosInterval4 = self.pandaActor5.posInterval( v1, Point3(x, 10, 7.5), startPos=Point3(x, -10, 0)) pandaHprInterval3 = self.pandaActor5.hprInterval(u1, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval4 = self.pandaActor5.hprInterval(u1, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace5 = Sequence(pandaPosInterval3, pandaHprInterval3, pandaPosInterval4, pandaHprInterval4, name="pandaPace5") self.pandaPace5.loop() # Load big panda self.pandaActor6 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor6.setScale(0.01, 0.01, 0.01) # large scale self.pandaActor6.setColorScale(r3, g3, b3, 1) self.pandaActor6.reparentTo(self.render) # Leg movement animation. self.pandaActor6.loop("walk") # Walking animation pandaPosInterval5 = self.pandaActor6.posInterval( v3, Point3(x, -10, 7.5), startPos=Point3(x, 10, 0)) pandaPosInterval6 = self.pandaActor6.posInterval(v3, Point3(x, 10, 0), startPos=Point3( x, -10, 7.5)) pandaHprInterval5 = self.pandaActor6.hprInterval(u3, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval6 = self.pandaActor6.hprInterval(u3, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace6 = Sequence(pandaPosInterval5, pandaHprInterval5, pandaPosInterval6, pandaHprInterval6, name="pandaPace6") self.pandaPace6.loop() # PANDA FUNCTION 3 def panda3(x, r1, g1, b1, r2, g2, b2, r3, g3, b3, v1, v2, v3, u1, u2, u3): # Load medium-sized panda self.pandaActor7 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor7.setScale(0.005, 0.005, 0.005) # medium scale self.pandaActor7.setColorScale(r2, g2, b2, 100) self.pandaActor7.reparentTo(self.render) # Leg movement animation self.pandaActor7.loop("walk") # Walking animation pandaPosInterval1 = self.pandaActor7.posInterval(v2, Point3(x, -10, 5), startPos=Point3( x, 10, 5)) pandaPosInterval2 = self.pandaActor7.posInterval(v2, Point3(x, 10, 5), startPos=Point3( x, -10, 5)) pandaHprInterval1 = self.pandaActor7.hprInterval(u2, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval2 = self.pandaActor7.hprInterval(u2, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace7 = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace7") self.pandaPace7.loop() # Load small panda self.pandaActor8 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor8.setScale(0.0025, 0.0025, 0.0025) # small scale self.pandaActor8.setColorScale(r1, g1, b1, 100) self.pandaActor8.reparentTo(self.render) # Leg movement animation self.pandaActor8.loop("walk") # Walking animation pandaPosInterval3 = self.pandaActor8.posInterval(v1, Point3(x, -10, 0), startPos=Point3( x, 10, 7.5)) pandaPosInterval4 = self.pandaActor8.posInterval( v1, Point3(x, 10, 7.5), startPos=Point3(x, -10, 0)) pandaHprInterval3 = self.pandaActor8.hprInterval(u1, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval4 = self.pandaActor8.hprInterval(u1, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace8 = Sequence(pandaPosInterval3, pandaHprInterval3, pandaPosInterval4, pandaHprInterval4, name="pandaPace8") self.pandaPace8.loop() # Load big panda self.pandaActor9 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor9.setScale(0.01, 0.01, 0.01) # large scale self.pandaActor9.setColorScale(r3, g3, b3, 1) self.pandaActor9.reparentTo(self.render) # Leg movement animation. self.pandaActor9.loop("walk") # Walking animation pandaPosInterval5 = self.pandaActor9.posInterval( v3, Point3(x, -10, 7.5), startPos=Point3(x, 10, 0)) pandaPosInterval6 = self.pandaActor9.posInterval(v3, Point3(x, 10, 0), startPos=Point3( x, -10, 7.5)) pandaHprInterval5 = self.pandaActor9.hprInterval(u3, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval6 = self.pandaActor9.hprInterval(u3, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace9 = Sequence(pandaPosInterval5, pandaHprInterval5, pandaPosInterval6, pandaHprInterval6, name="pandaPace9") self.pandaPace9.loop() def panda4(x1, y1, x2, y2, r, g, b, v, u): # Load medium-sized panda self.pandaActor10 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor10.setScale(0.005, 0.005, 0.005) # medium scale self.pandaActor10.setColorScale(r, g, b, 100) self.pandaActor10.reparentTo(self.render) # Leg movement animation self.pandaActor10.loop("walk") # Walking animation pandaPosInterval1 = self.pandaActor10.posInterval( v, Point3(x1, y2, 0), startPos=Point3(x1, y1, 7.5)) pandaPosInterval2 = self.pandaActor10.posInterval( v, Point3(x2, y2, 7.5), startPos=Point3(x1, y2, 0)) pandaPosInterval3 = self.pandaActor10.posInterval( v, Point3(x2, y1, 0), startPos=Point3(x2, y2, 7.5)) pandaPosInterval4 = self.pandaActor10.posInterval( v, Point3(x1, y1, 7.5), startPos=Point3(x2, y1, 0)) pandaHprInterval1 = self.pandaActor10.hprInterval( u, Point3(-90, 0, 0), startHpr=Point3(0, 0, 0)) pandaHprInterval2 = self.pandaActor10.hprInterval( u, Point3(-180, 0, 0), startHpr=Point3(-90, 0, 0)) pandaHprInterval3 = self.pandaActor10.hprInterval( u, Point3(-270, 0, 0), startHpr=Point3(-180, 0, 0)) pandaHprInterval4 = self.pandaActor10.hprInterval( u, Point3(-360, 0, 0), startHpr=Point3(-270, 0, 0)) self.pandaPace10 = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, pandaPosInterval3, pandaHprInterval3, pandaPosInterval4, pandaHprInterval4, name="pandaPace10") self.pandaPace10.loop() # panda_(x,r1,g1,b1,r2,g2,b2,r3,g3,b3,v1,v2,v3,u1,u2,u3) # x = x co-ordinate # r1 = r value for small panda # g1 = g value for small panda # b1 = b value for small panda # r2 = r value for medium panda # b2 = b value for medium panda # g2 = g value for medium panda # r3 = r value for large panda # g3 = g value for large panda # b3 = b value for large panda # v1 = walking speed for small panda # v2 = walking speed for medium panda # v3 = walking speed for large panda # u1 = turning speed for small panda # u2 = turning speed for medium panda # u3 = turning speed for large panda # Allows for easy control of certain variable in the panda generation panda1(0, 0, 255, 0, 255, 255, 0, 255, 0, 0, 5, 2.5, 1.25, 1, 0.5, 0.25) panda2(5, 255, 0, 0, 255, 0, 255, 0, 0, 255, 1.25, 5, 2.5, 0.25, 1, 0.5) panda3(-5, 0, 0, 255, 0, 255, 255, 0, 255, 0, 2.5, 1.25, 5, 0.5, 0.25, 1) panda4(5, 10, -5, -10, 255, 255, 255, 5, 1) # Adding sound def sound(): # Generates a random float between 0 and 1, rounded to 1 decimal place ###vol = round(random.uniform(0, 1), 1) music = self.loader.loadSfx("bensound-dubstep.mp3") music.setVolume(0.5) music.setLoop(True) music.play() # Uses a while loop with an unachievable condition so it lasts forever ###while vol < 1.01: # Sets the volume of the music to random float #music.setVolume(vol) # Waits for the volume of the music multiplied by 60 seconds to determine how long the music plays at that volume for ###time.sleep(vol * 60) # Regenerating the number ###vol = round(random.uniform(0, 1), 1) sound() # Adding text def text(): font = loader.loadFont('cmr12.egg') text1 = TextNode('node name') text1.setText("Pande") text1.setFont(font) text1.setSmallCaps(True) text1.setSlant(-0.3) text1.setTextColor(0, 0, 0, 1) text1.setShadow(0.05, 0.05) text1.setShadowColor(1, 0, 0, 1) text1.setAlign(TextNode.ARight) text2 = TextNode('node name') text2.setText("monium") text2.setFont(font) text2.setSmallCaps(True) text2.setSlant(0.3) text2.setTextColor(0, 0, 0, 1) text2.setShadow(0.05, 0.05) text2.setShadowColor(1, 0, 0, 1) text2.setAlign(TextNode.ALeft) textNodePath = aspect2d.attachNewNode(text1) textNodePath.setScale(0.3) textNodePath = aspect2d.attachNewNode(text2) textNodePath.setScale(0.3) text() # Define a procedure to move the camera. def spinCameraTask(self, task): angleDegrees = task.time * 48.0 angleRadians = angleDegrees * (pi / 180.0) self.camera.setPos(42 * sin(angleRadians), -42.0 * cos(angleRadians), 7) self.camera.setHpr(angleDegrees, 0, 0) return Task.cont
def __init__(self): ShowBase.__init__(self) self.loc_text = addTextField(0.45, "[LOC]: ") self.imageObject = OnscreenImage(image='models/intro.jpg', pos=(-0, 0, 0.02)) self.imageObject.setScale(1.6, 1.2, 1.2) base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.setBackgroundColor(0, 0, 0, 0) base.setFrameRateMeter(True) _sky = Vec4(0.01, 0.01, 0.01, 0.01) _clouds = Vec4(0.01, 0.01, 0.01, 0.01) # vx, vy, vx, vy base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) self.skyNP = loader.loadModel('models/sky') self.skyNP.reparentTo(render) self.skyNP.setScale(1000, 1000, 300) self.skyNP.setPos(0, 0, 0) self.skyNP.setTexture(loader.loadTexture('models/clouds.jpg')) self.skyNP.setShader(loader.loadShader('shaders/sky.sha')) self.skyNP.setShaderInput('sky', _sky) self.skyNP.setShaderInput('clouds', _clouds) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('s', self.doScreenshot) self.accept('space', self.doJump) inputState.watchWithModifiers('forward', 'arrow_up') #inputState.watchWithModifiers('left', 'arrow_left') inputState.watchWithModifiers('reverse', 'arrow_down') #inputState.watchWithModifiers('right', 'arrow_right') inputState.watchWithModifiers('turnLeft', 'arrow_left') inputState.watchWithModifiers('turnRight', 'arrow_right') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) # self.world.setDebugNode(self.debugNP.node()) # Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 0) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, -100) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box # Character self.crouching = False h = 2.75 w = 0.9 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = self.worldNP.attachNewNode(self.character) self.characterNP.setPos(-2, 0, 14) #self.characterNP.setPos(-4, 75, 74) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) base.cam.reparentTo(self.characterNP) self.pvisualNP = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pvisualNP.clearModelNodes() self.pvisualNP.setScale(0.003) self.pvisualNP.setZ(-1.2) self.pvisualNP.reparentTo(self.characterNP) self.pvisualNP.setH(180) #self.pvisualNP.loop("walk") self.accept('arrow_up', self.pandawalk) self.accept('arrow_up-up', self.pandastop) self.accept('arrow_down', self.pandawalk) self.accept('arrow_down-up', self.pandastop) ''' visualNP.reparentTo(self.characterNP) visualNP = loader.loadModel('models/pilot-model') visualNP.clearModelNodes() visualNP.setScale(0.05) visualNP.setZ(-1.1) visualNP.setH(190) visualNP.reparentTo(self.characterNP) ''' shape = BulletBoxShape(Vec3(2, 2, 0.2)) self.Elev = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.Elev.node().setMass(0) self.Elev.node().addShape(shape) self.Elev.setPos(-0.4, 90, 5) self.Elev.setScale(2) self.Elev.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.Elev.node()) visualNP = loader.loadModel('models/elevator') visualNP.clearModelNodes() visualNP.reparentTo(self.Elev) visualNP.setScale(0.5) shape = BulletBoxShape(Vec3(2, 2, 0.2)) self.Elev2 = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.Elev2.node().setMass(0) self.Elev2.node().addShape(shape) self.Elev2.setPos(0, 0, 28) self.Elev2.setScale(2) self.Elev2.setH(180) self.Elev2.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.Elev2.node()) visualNP = loader.loadModel('models/elevator') visualNP.clearModelNodes() visualNP.reparentTo(self.Elev2) visualNP.setScale(0.5) #self.makeblockwood(1,1,1,1,1,1) self.makeblock(0, 0, 0, 5, 5, 0.5) self.makeblock(0, 10, -1, 2, 20, 0.5) self.makeblock(0, 20, 0, 2, 3, 0.5) self.makeblock(0, 25, 1, 2, 3, 0.5) self.makeblock(0, 30, 2, 2, 3, 0.5) self.makeblock(0, 35, 3, 2, 3, 0.5) self.makeblock(0, 40, 4, 2, 3, 0.5) self.makeblock(0, 50, 4, 10, 20, 0.5) self.makeblockgold(-1, 50, 5, 1, 1, 1) self.makeblockcrate(0, 50, 6, 0.7, 0.7, 0.7) self.makeblockwood(1, 50, 5, 1, 1, 1) self.makeblocksilver(-2.5, 50, 5, 1, 1, 1) self.makeblockstone(2.5, 50, 5, 1, 1, 1) self.makeblock(0, 70, 4, 2, 20, 0.5) self.makeblock(0, 90, 4, 20, 20, 0.5) self.makeblock(0, 75, 20, 20, 20, 0.5) self.makeblockcrate(-1, 75, 25, 1, 1, 1) self.makeblockwood(-1, 75, 28, 1, 1, 1) self.makeblocksilver(-1, 75, 31, 1, 1, 1) self.makeblockgold(-1, 75, 34, 1, 1, 1) self.makeblockstone(-1, 75, 38, 1, 1, 1) self.makeblock(-0.53, 50, 21.58, 2, 20, 0.5) self.makeblock(0, 40, 23, 5, 5, 0.5) self.makeblock(0, 20, 23, 5, 5, 0.5) self.makeblock(0, 0, 23, 5, 5, 0.5) self.makeblock(0, 0, 26, 20, 20, 0.5) self.makeblock(0, 25, 46, 50, 50, 0.5) self.imageObject.hide()
def __init__(self, parserClass, mainClass, mapLoaderClass, modelLoaderClass): self.switchState = False #self.t = Timer() self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0} self.ralph = Actor( "data/models/units/ralph/ralph", { "run": "data/models/units/ralph/ralph-run", "walk": "data/models/units/ralph/ralph-walk" }) self.ralph.reparentTo(render) # self.ralph.setPos(42, 30, 0) self.ralph.setPos(6, 10, 0) self.ralph.setScale(0.1) self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("arrow_down", self.setKey, ["backward", 1]) self.accept("arrow_down-up", self.setKey, ["backward", 0]) self.isMoving = False self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) #self.ralphGroundCol.show() base.cam.reparentTo(self.ralph) base.cam.setPos(0, 9, 7) self.floater2 = NodePath(PandaNode("floater2")) self.floater2.reparentTo(self.ralph) self.floater2.setZ(self.floater2.getZ() + 6) base.cam.lookAt(self.floater2) # Uncomment this line to see the collision rays # self.ralphGroundColNp.show() # self.camGroundColNp.show() #Uncomment this line to show a visual representation of the #collisions occuring # self.cTrav.showCollisions(render) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) taskMgr.add(self.move, "movingTask", extraArgs=[ mainClass, parserClass, mapLoaderClass, modelLoaderClass ])
class MyPlayer: def __init__(self, Connection): self.SetModel("") self.keyMap = { "left": 0, "right": 0, "forward": 0, "back": 0, "space": 0 } self.render = 0 self.connection = Connection self.connection.RegisterLocalPlayer(self) self.MyDamage = 20.0 self.MyHealth = 100.0 self.AttackDistance = 10.0 self.AttackCooldown = 0.5 self.AttackCooldownTimer = Timer() #TODO: sets this actor the model set by path def SetModel(self, path): self.Actor = Actor("panda-model", {"walk": "panda-walk4"}) self.Actor.setScale(0.005, 0.005, 0.005) self.CamLoc = NodePath(PandaNode("floater")) self.CamLoc.reparentTo(self.Actor) self.CamLoc.setZ(1000.0) self.CamLoc.setY(1000.0) self.CamLoc.setH(180) self.CamLoc.setP(-15) #adds our character to scene and sets up input def AddToScene(self, app): self.render = app.render self.Actor.reparentTo(app.render) # Loop its animation. self.Actor.loop("walk") app.accept("escape", sys.exit) app.accept("a", self.setKey, ["left", True]) app.accept("d", self.setKey, ["right", True]) app.accept("w", self.setKey, ["forward", True]) app.accept("s", self.setKey, ["back", True]) app.accept("a-up", self.setKey, ["left", False]) app.accept("d-up", self.setKey, ["right", False]) app.accept("w-up", self.setKey, ["forward", False]) app.accept("s-up", self.setKey, ["back", False]) app.accept("space", self.setKey, ["space", True]) app.accept("space-up", self.setKey, ["space", False]) app.taskMgr.add(self.HandleGameplay, "gameplayHandler") def setKey(self, key, value): self.keyMap[key] = value def HandleGameplay(self, task): bHasMoved = False bAttack = False if self.keyMap["left"]: self.Actor.setH(self.Actor.getH() + 3.0) bHasMoved = True if self.keyMap["right"]: self.Actor.setH(self.Actor.getH() - 3.0) bHasMoved = True if self.keyMap["forward"]: self.Actor.setPos( self.Actor.getPos() - self.render.getRelativeVector(self.Actor, Vec3(0, 1, 0)) * 50) bHasMoved = True if self.keyMap["back"]: self.Actor.setPos( self.Actor.getPos() + self.render.getRelativeVector(self.Actor, Vec3(0, 1, 0)) * 50) bHasMoved = True if self.keyMap["space"]: bAttack = True if bHasMoved: pos = self.Actor.getPos() rot = self.Actor.getHpr() self.connection.SendMessage(self.connection.OP_POSITION + " " + str(pos.getX()) + " " + str(pos.getY()) + " " + str(pos.getZ()) + " " + str(rot.getX()) + " " + str(rot.getY()) + " " + str(rot.getZ())) #Only Send Attack if close enough and not in attack cooldown (based on timer) if bAttack and self.AttackCooldownTimer.GetElapsed( ) > self.AttackCooldown: print "Attack" self.AttackCooldownTimer.reset() distanceToOpponent = self.connection.GetDistanceToOpponent() if distanceToOpponent < self.AttackDistance: MSG = self.connection.OP_ATTACK + " " + str(self.MyDamage) self.connection.SendMessage(MSG) return task.cont def TakeDamage(self, Dmg): self.MyHealth -= Dmg if self.MyHealth <= 0.0: print "You Lose!" MSG = self.connection.OP_DESTROYED self.connection.SendMessage(MSG) self.Actor.hide()
class World(DirectObject): def __init__(self): self.keyMap = { "arrow_left": 0, "arrow_right": 0, "arrow_up": 0, "arrow_down": 0, "cam-left": 0, "cam-right": 0, "make-bunny": 0, "do-something": 0, "ignore": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Track all of the bunnies self.bunnies = [] # Post the instructions self.title = addTitle("Keyboard Roaming") self.inst1 = addInstructions(0.95, "[Shift+ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3) self.ralph.setPos(ralphStartPos) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Shift+ESC key exits self.accept("shift-escape", sys.exit) # Tke keyboard is divided into six sections or tiles: # # 1 2 # +----------------+ +-------------+ # | f1 ... F5 | | F6 ... F12 | # +----------------+ +-------------+ # # 3 4 # +----------------+ +-------------------------+ # | ` 1 2 3 4 5 6 | | 7 8 9 0 - = BACKSPACE | # | Q W E R T Y | | Y U I O P [ ] \ | # | A S D F G | | H J K L ; ' ENTER | # | Z X C V B | | N M , . / | # | CTRL WIN ALT | | SPACE ALT WIN MENU CTRL | # +----------------+ +-------------------------+ # # 5 # +----------------------+ # | PRT SCR PAUSE | # | INSERT HOME PAGEUP | # | DELETE END PAGEDOWN | # +----------------------+ # 6 # +----------------------+ # | UP LEFT DOWN RIGHT | # +----------------------+ # Section1 = ["f1", "f2", "f3", "f4", "f5"] Section2 = ["f6", "f7", "f8", "f9", "f10", "f11", "f12"] Section3 = [ "`", "1", "2", "3", "4", "5", "6", "q", "w", "e", "r", "t", "y", "a", "s", "d", "f", "g", "lshift", "z", "x", "c", "v", "b" ] Section4 = [ "7", "8", "9", "0", "backspace", "y", "u", "i", "o", "p", "[", "]", "\\", "h", "j", "k", "l", ";", "'", "enter", "n", "m", ",", ".", "/", "rshift" ] Section5 = [ "print_screen", "scroll_lock", "pause", "insert", "home", "page_up", "delete", "end", "page_down" ] Section6 = ["arrow_left", "arrow_right", "arrow_up", "arrow_down"] # Map each section action = "cam-left" for k in Section1: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "cam-right" for k in Section2: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_up" for k in Section3: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_down" for k in Section4: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "make-bunny" for k in Section5: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) for k in Section6: self.accept(k, self.setKey, [k, 1]) self.accept("shift-" + k, self.setKey, [k, 1]) self.accept(k + "-up", self.setKey, [k, 0]) self.accept("shift-" + k + "-up", self.setKey, [k, 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Set up some sounds self.runSound = base.loader.loadSfx( "sounds/54779__bevangoldswain__running-hard-surface.wav") self.bumpSound = base.loader.loadSfx( "sounds/31126__calethos__bump.wav") self.spawnSound = base.loader.loadSfx( "sounds/51710__bristolstories__u-chimes3.mp3") #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Lines the bunnies up behind Ralph def positionBunnies(self): ralphH = self.ralph.getH() * (3.1415927 / 180.0) X = self.ralph.getX() Y = self.ralph.getY() print "Ralph at " + str(X) + ", " + str(Y) + ", heading " + str(ralphH) dX = math.cos(ralphH + PI / 2.0) dY = math.sin(ralphH + PI / 2.0) i = 1 for bunny in self.bunnies: bX = X + (dX * 2 * i) bY = Y + (dY * 2 * i) bunny.setX(bX) bunny.setY(bY) print " Bunny at " + str(bX) + ", " + str(bY) bunny.setZ(self.ralph.getZ() + 0.5 + random.random()) bunny.lookAt(self.ralph) i = i + 1 print # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # Ignore certain keys if (self.keyMap["ignore"] != 0): self.keyMap["ignore"] = 0 print("Ignoring key...") # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.ralph) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["arrow_left"] != 0): self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt()) self.positionBunnies() if (self.keyMap["arrow_right"] != 0): self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt()) self.positionBunnies() if (self.keyMap["arrow_up"] != 0): self.ralph.setY(self.ralph, -50 * globalClock.getDt()) self.positionBunnies() if (self.keyMap["arrow_down"] != 0): self.ralph.setY(self.ralph, 50 * globalClock.getDt()) self.positionBunnies() # If an object creation key is pressed, create an object of the desired type if (self.keyMap["make-bunny"] != 0): self.keyMap["make-bunny"] = 0 # Avoid multiplying like rabbits! if (self.spawnSound.status() != AudioSound.PLAYING): self.spawnSound.play() if (random.random() < 0.5): new_bunny = Actor("models/Bunny2") else: new_bunny = Actor("models/Chicken") new_bunny.reparentTo(render) new_bunny.setScale(0.3) self.bunnies.append(new_bunny) self.positionBunnies() # Handle the catch-all do-something keys if (self.keyMap["do-something"] != 0): self.keyMap["do-something"] = 0 print "Something!" # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["arrow_up"] != 0) or (self.keyMap["arrow_down"] != 0) or (self.keyMap["arrow_left"] != 0) or (self.keyMap["arrow_right"] != 0): if self.isMoving is False: self.ralph.loop("run") self.isMoving = True if (self.runSound.status() != AudioSound.PLAYING): self.runSound.play() else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False self.runSound.stop() # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.ralph.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # Now check for collisions. self.cTrav.traverse(render) # Adjust ralph's Z coordinate. If ralph's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame. entries = [] for i in range(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): self.ralph.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.ralph.setPos(startpos) if (self.bumpSound.status() != AudioSound.PLAYING): self.bumpSound.play() # Keep the camera at one foot above the terrain, # or two feet above ralph, whichever is greater. entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): base.camera.setZ(entries[0].getSurfacePoint(render).getZ() + 1.0) if (base.camera.getZ() < self.ralph.getZ() + 2.0): base.camera.setZ(self.ralph.getZ() + 2.0) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.ralph.getPos()) self.floater.setZ(self.ralph.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor(BACKGROUND_COLOR) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character playerStartPos = self.environ.find("**/start_point").getPos() self.player = Actor("models/player", {"run": "models/player-run", "walk": "models/player-walk"}) self.player.reparentTo(render) self.player.setScale(.2) self.player.setPos(playerStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above player. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.player) self.floater.setZ(CAMERA_TARGET_HEIGHT_DELTA) self.first_person = False def key_dn(name): return lambda: self.setKey(name, True) def key_up(name): return lambda: self.setKey(name, False) def quit(): self.destroy() def toggle_first(): self.first_person = not self.first_person # Accept the control keys for movement and rotation key_map = [ # key command action help # --- ------- ------ ---- ("escape", "esc", lambda: quit(), '[ESC]: Quit'), ("arrow_left", 'left', key_dn("left"), "[Left Arrow]: Rotate Left"), ("arrow_left-up", 'left', key_up("left"), None), ("arrow_right", 'right', key_dn("right"), "[Right Arrow]: Rotate Right"), ("arrow_right-up", 'right', key_up("right"), None), ("arrow_up", 'forward', key_dn("forward"), "[Up Arrow]: Run Forward"), ("arrow_up-up", 'forward', key_up("forward"), None), ("arrow_down", 'backward', key_dn("backward"), "[Down Arrow]: Run Backward"), ("arrow_down-up", 'backward', key_up("backward"), None), ("a", 'cam-left', key_dn("cam-left"), "[A]: Rotate Camera Left"), ("a-up", 'cam-left', key_up("cam-left"), None), ("s", 'cam-right', key_dn("cam-right"), "[S]: Rotate Camera Right"), ("s-up", 'cam-right', key_up("cam-right"), None), ('f', 'first-pers', lambda: toggle_first(), '[F]: Toggle first-person'), ] self.keyMap = {} inst = Instructions() for key, command, action, description in key_map: if command: self.setKey(command, False) self.accept(key, action) if description: inst.add(description) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.player.getX(), self.player.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above player's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.playerGroundRay = CollisionRay() self.playerGroundRay.setOrigin(0, 0, 9) self.playerGroundRay.setDirection(0, 0, -1) self.playerGroundCol = CollisionNode('playerRay') self.playerGroundCol.addSolid(self.playerGroundRay) self.playerGroundCol.setFromCollideMask(CollideMask.bit(0)) self.playerGroundCol.setIntoCollideMask(CollideMask.allOff()) self.playerGroundColNp = self.player.attachNewNode(self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays self.playerGroundColNp.show() self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
class DistributedPartyJukeboxActivityBase(DistributedPartyActivity): notify = directNotify.newCategory('DistributedPartyJukeboxActivityBase') def __init__(self, cr, actId, phaseToMusicData): DistributedPartyActivity.__init__(self, cr, actId, ActivityTypes.Continuous) self.phaseToMusicData = phaseToMusicData self.jukebox = None self.gui = None self.tunes = [] self.music = None self.currentSongData = None self.localQueuedSongInfo = None self.localQueuedSongListItem = None return def generateInit(self): self.gui = JukeboxGui(self.phaseToMusicData) def load(self): DistributedPartyActivity.load(self) self.jukebox = Actor( 'phase_13/models/parties/jukebox_model', {'dance': 'phase_13/models/parties/jukebox_dance'}) self.jukebox.reparentTo(self.root) self.collNode = CollisionNode(self.getCollisionName()) self.collNode.setCollideMask(ToontownGlobals.CameraBitmask | ToontownGlobals.WallBitmask) collTube = CollisionTube(0, 0, 0, 0.0, 0.0, 4.25, 2.25) collTube.setTangible(1) self.collNode.addSolid(collTube) self.collNodePath = self.jukebox.attachNewNode(self.collNode) self.sign.setPos(-5.0, 0, 0) self.activate() def unload(self): DistributedPartyActivity.unload(self) self.gui.unload() if self.music is not None: self.music.stop() self.jukebox.stop() self.jukebox.delete() self.jukebox = None self.ignoreAll() return def getCollisionName(self): return self.uniqueName('jukeboxCollision') def activate(self): self.accept('enter' + self.getCollisionName(), self.__handleEnterCollision) def __handleEnterCollision(self, collisionEntry): if base.cr.playGame.getPlace().fsm.getCurrentState().getName( ) == 'walk': base.cr.playGame.getPlace().fsm.request('activity') self.d_toonJoinRequest() def joinRequestDenied(self, reason): DistributedPartyActivity.joinRequestDenied(self, reason) self.showMessage(TTLocalizer.PartyJukeboxOccupied) def handleToonJoined(self, toonId): toon = base.cr.doId2do.get(toonId) if toon: self.jukebox.lookAt(base.cr.doId2do[toonId]) self.jukebox.setHpr(self.jukebox.getH() + 180.0, 0, 0) if toonId == base.localAvatar.doId: self.__localUseJukebox() def handleToonExited(self, toonId): if toonId == base.localAvatar.doId and self.gui.isLoaded(): self.__deactivateGui() def handleToonDisabled(self, toonId): self.notify.warning('handleToonDisabled no implementation yet') def __localUseJukebox(self): base.localAvatar.disableAvatarControls() base.localAvatar.stopPosHprBroadcast() self.__activateGui() self.accept(JukeboxGui.CLOSE_EVENT, self.__handleGuiClose) taskMgr.doMethodLater(0.5, self.__localToonWillExitTask, self.uniqueName('toonWillExitJukeboxOnTimeout'), extraArgs=None) self.accept(JukeboxGui.ADD_SONG_CLICK_EVENT, self.__handleQueueSong) if self.isUserHost(): self.accept(JukeboxGui.MOVE_TO_TOP_CLICK_EVENT, self.__handleMoveSongToTop) return def __localToonWillExitTask(self, task): self.localToonExiting() return Task.done def __activateGui(self): self.gui.enable(timer=JUKEBOX_TIMEOUT) self.gui.disableAddSongButton() if self.currentSongData is not None: self.gui.setSongCurrentlyPlaying(self.currentSongData[0], self.currentSongData[1]) self.d_queuedSongsRequest() return def __deactivateGui(self): self.ignore(JukeboxGui.CLOSE_EVENT) self.ignore(JukeboxGui.SONG_SELECT_EVENT) self.ignore(JukeboxGui.MOVE_TO_TOP_CLICK_EVENT) base.cr.playGame.getPlace().setState('walk') base.localAvatar.startPosHprBroadcast() base.localAvatar.enableAvatarControls() self.gui.unload() self.__localClearQueuedSong() def isUserHost(self): return self.party.partyInfo.hostId == base.localAvatar.doId def d_queuedSongsRequest(self): self.sendUpdate('queuedSongsRequest') def queuedSongsResponse(self, songInfoList, index): if self.gui.isLoaded(): for i in range(len(songInfoList)): songInfo = songInfoList[i] self.__addSongToQueue(songInfo, isLocalQueue=index >= 0 and i == index) self.gui.enableAddSongButton() def __handleGuiClose(self): self.__deactivateGui() self.d_toonExitDemand() def __handleQueueSong(self, name, values): self.d_setNextSong(values[0], values[1]) def d_setNextSong(self, phase, filename): self.sendUpdate('setNextSong', [(phase, filename)]) def setSongInQueue(self, songInfo): if self.gui.isLoaded(): phase = sanitizePhase(songInfo[0]) filename = songInfo[1] data = self.getMusicData(phase, filename) if data: if self.localQueuedSongListItem is not None: self.localQueuedSongListItem['text'] = data[0] else: self.__addSongToQueue(songInfo, isLocalQueue=True) return def __addSongToQueue(self, songInfo, isLocalQueue=False): isHost = isLocalQueue and self.isUserHost() data = self.getMusicData(sanitizePhase(songInfo[0]), songInfo[1]) if data: listItem = self.gui.addSongToQueue(data[0], highlight=isLocalQueue, moveToTopButton=isHost) if isLocalQueue: self.localQueuedSongInfo = songInfo self.localQueuedSongListItem = listItem def __localClearQueuedSong(self): self.localQueuedSongInfo = None self.localQueuedSongListItem = None return def __play(self, phase, filename, length): self.music = base.loader.loadMusic( (MUSIC_PATH + '%s') % (phase, filename)) if self.music: if self.__checkPartyValidity() and hasattr( base.cr.playGame.getPlace().loader, 'music') and base.cr.playGame.getPlace().loader.music: base.cr.playGame.getPlace().loader.music.stop() base.resetMusic.play() self.music.setTime(0.0) self.music.setLoopCount(getMusicRepeatTimes(length)) self.music.play() jukeboxAnimControl = self.jukebox.getAnimControl('dance') if not jukeboxAnimControl.isPlaying(): self.jukebox.loop('dance') self.currentSongData = (phase, filename) def __stop(self): self.jukebox.stop() self.currentSongData = None if self.music: self.music.stop() if self.gui.isLoaded(): self.gui.clearSongCurrentlyPlaying() return def setSongPlaying(self, songInfo, toonId): phase = sanitizePhase(songInfo[0]) filename = songInfo[1] if not filename: self.__stop() return data = self.getMusicData(phase, filename) if data: self.__play(phase, filename, data[1]) self.setSignNote(data[0]) if self.gui.isLoaded(): item = self.gui.popSongFromQueue() self.gui.setSongCurrentlyPlaying(phase, filename) if item == self.localQueuedSongListItem: self.__localClearQueuedSong() if toonId == localAvatar.doId: localAvatar.setSystemMessage(0, TTLocalizer.PartyJukeboxNowPlaying) def __handleMoveSongToTop(self): if self.isUserHost() and self.localQueuedSongListItem is not None: self.d_moveHostSongToTopRequest() return def d_moveHostSongToTopRequest(self): self.notify.debug('d_moveHostSongToTopRequest') self.sendUpdate('moveHostSongToTopRequest') def moveHostSongToTop(self): self.notify.debug('moveHostSongToTop') if self.gui.isLoaded(): self.gui.pushQueuedItemToTop(self.localQueuedSongListItem) def getMusicData(self, phase, filename): data = [] phase = sanitizePhase(phase) phase = self.phaseToMusicData.get(phase) if phase: data = phase.get(filename, []) return data def __checkPartyValidity(self): if hasattr(base.cr.playGame, 'getPlace') and base.cr.playGame.getPlace() and hasattr( base.cr.playGame.getPlace(), 'loader') and base.cr.playGame.getPlace().loader: return True else: return False
class Game(ShowBase): def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor(BACKGROUND_COLOR) # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character playerStartPos = self.environ.find("**/start_point").getPos() self.player = Actor("models/player", {"run": "models/player-run", "walk": "models/player-walk"}) self.player.reparentTo(render) self.player.setScale(.2) self.player.setPos(playerStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above player. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.player) self.floater.setZ(CAMERA_TARGET_HEIGHT_DELTA) self.first_person = False def key_dn(name): return lambda: self.setKey(name, True) def key_up(name): return lambda: self.setKey(name, False) def quit(): self.destroy() def toggle_first(): self.first_person = not self.first_person # Accept the control keys for movement and rotation key_map = [ # key command action help # --- ------- ------ ---- ("escape", "esc", lambda: quit(), '[ESC]: Quit'), ("arrow_left", 'left', key_dn("left"), "[Left Arrow]: Rotate Left"), ("arrow_left-up", 'left', key_up("left"), None), ("arrow_right", 'right', key_dn("right"), "[Right Arrow]: Rotate Right"), ("arrow_right-up", 'right', key_up("right"), None), ("arrow_up", 'forward', key_dn("forward"), "[Up Arrow]: Run Forward"), ("arrow_up-up", 'forward', key_up("forward"), None), ("arrow_down", 'backward', key_dn("backward"), "[Down Arrow]: Run Backward"), ("arrow_down-up", 'backward', key_up("backward"), None), ("a", 'cam-left', key_dn("cam-left"), "[A]: Rotate Camera Left"), ("a-up", 'cam-left', key_up("cam-left"), None), ("s", 'cam-right', key_dn("cam-right"), "[S]: Rotate Camera Right"), ("s-up", 'cam-right', key_up("cam-right"), None), ('f', 'first-pers', lambda: toggle_first(), '[F]: Toggle first-person'), ] self.keyMap = {} inst = Instructions() for key, command, action, description in key_map: if command: self.setKey(command, False) self.accept(key, action) if description: inst.add(description) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.player.getX(), self.player.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above player's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.playerGroundRay = CollisionRay() self.playerGroundRay.setOrigin(0, 0, 9) self.playerGroundRay.setDirection(0, 0, -1) self.playerGroundCol = CollisionNode('playerRay') self.playerGroundCol.addSolid(self.playerGroundRay) self.playerGroundCol.setFromCollideMask(CollideMask.bit(0)) self.playerGroundCol.setIntoCollideMask(CollideMask.allOff()) self.playerGroundColNp = self.player.attachNewNode(self.playerGroundCol) self.playerGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.playerGroundColNp, self.playerGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays self.playerGroundColNp.show() self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # Get the time that elapsed since last frame. We multiply this with # the desired speed in order to find out with which distance to move # in order to achieve that desired speed. dt = globalClock.getDt() # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. if self.keyMap["cam-left"]: self.camera.setX(self.camera, -20 * dt) if self.keyMap["cam-right"]: self.camera.setX(self.camera, +20 * dt) # save player's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.player.getPos() # If a move-key is pressed, move player in the specified direction. if self.keyMap["left"]: self.player.setH(self.player.getH() + 300 * dt) if self.keyMap["right"]: self.player.setH(self.player.getH() - 300 * dt) if self.keyMap["forward"]: self.player.setY(self.player, -25 * dt) if self.keyMap["backward"]: self.player.setY(self.player, 25 * dt) # If player is moving, loop the run animation. # If he is standing still, stop the animation. if self.keyMap["forward"] or self.keyMap["backward"] or self.keyMap["left"] or self.keyMap["right"]: if self.isMoving is False: self.player.loop("run") self.isMoving = True else: if self.isMoving: self.player.stop() self.player.pose("walk", 5) self.isMoving = False # If the camera is too far from player, move it closer. # If the camera is too close to player, move it farther. if self.first_person: self.camera.setPos(self.player.getPos()) else: camvec = self.player.getPos() - self.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if camdist > CAMERA_DISTANCE_MAX: self.camera.setPos(self.camera.getPos() + camvec * (camdist - int(CAMERA_DISTANCE_MAX))) camdist = CAMERA_DISTANCE_MAX if camdist < CAMERA_DISTANCE_MIN: self.camera.setPos(self.camera.getPos() - camvec * (int(CAMERA_DISTANCE_MIN) - camdist)) camdist = CAMERA_DISTANCE_MIN # Normally, we would have to call traverse() to check for collisions. # However, the class ShowBase that we inherit from has a task to do # this for us, if we assign a CollisionTraverser to self.cTrav. self.cTrav.traverse(render) # Adjust player's Z coordinate. If player's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame. entries = list(self.playerGroundHandler.getEntries()) entries.sort(key=lambda x: x.getSurfacePoint(render).getZ()) if len(entries) > 0 and entries[0].getIntoNode().getName() == "terrain": self.player.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.player.setPos(startpos) # Keep the camera at one foot above the terrain, # or two feet above player, whichever is greater. entries = list(self.camGroundHandler.getEntries()) entries.sort(key=lambda x: x.getSurfacePoint(render).getZ()) if len(entries) > 0 and entries[0].getIntoNode().getName() == "terrain": self.camera.setZ(entries[0].getSurfacePoint(render).getZ() + CAMERA_POSITION_HEIGHT_DELTA_MIN) if self.camera.getZ() < self.player.getZ() + CAMERA_POSITION_HEIGHT_DELTA_MAX: self.camera.setZ(self.player.getZ() + CAMERA_POSITION_HEIGHT_DELTA_MAX) # The camera should look in player's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above player's head. self.camera.lookAt(self.floater) return task.cont
def setupVarsNPs(self, startPos, name): self.name = name # Stores a unique name for this cycle. self.root = render.attachNewNode("Root") # Creates and stores the NodePath that will be used as the root of the cycle # for the purpose of movement. self.cycle = self.root.attachNewNode("Cycle") # Creates a dummy node to go between self.root and the actualy cycle model. if (startPos == 1): self.root.setPos(5, 0, 0) self.model = loader.loadModel("../Models/RedCycle.bam") self.turret = loader.loadModel("../Models/RedTurr.bam") elif (startPos == 2): self.root.setPos(-5, -5, 0) self.model = loader.loadModel("../Models/BlueCycle.bam") self.turret = loader.loadModel("../Models/BlueTurr.bam") elif (startPos == 3): self.root.setPos(5, -10, 0) self.model = loader.loadModel("../Models/GreenCycle.bam") self.turret = loader.loadModel("../Models/GreenTurr.bam") elif (startPos == 4): self.root.setPos(-5, -15, 0) self.model = loader.loadModel("../Models/YellowCycle.bam") self.turret = loader.loadModel("../Models/YellowTurr.bam") # Sets the root to a new position according to what place it is given. # Also loads the model and turret of the appropriate color. self.mounts = Actor("../Models/Mounts.egg") # Loads an actor with 3 mounting joints for the moving parts of the cycle. self.model.reparentTo(self.cycle) self.mounts.reparentTo(self.model) # Attaches the model to the go-between node and attaches the mounts to # the model. turretMount = self.mounts.exposeJoint(None, "modelRoot", "Turret") fdMount = self.mounts.exposeJoint(None, "modelRoot", "FrontDisc") rdMount = self.mounts.exposeJoint(None, "modelRoot", "RearDisc") # exposes the mount joints so pieces can be attached to them. self.fd = loader.loadModel("../Models/Disc.bam") self.rd = loader.loadModel("../Models/Disc.bam") # loads the models for the discs. self.turretActor = Actor("../Models/TurretActor.egg") self.turretActor.reparentTo(turretMount) self.turret.reparentTo(self.turretActor) self.trgtrMount = self.turretActor.exposeJoint(None, "modelRoot", "TargeterMount") self.fd.reparentTo(fdMount) self.rd.reparentTo(rdMount) # Attaches the turret and discs to their mounts. self.LMGMount = self.turretActor.exposeJoint(None, "modelRoot", "LMGMount") self.RMGMount = self.turretActor.exposeJoint(None, "modelRoot", "RMGMount") self.LMG = MachineGun(self, self.LMGMount) self.RMG = MachineGun(self, self.RMGMount) self.CannonMount = self.turretActor.exposeJoint( None, "modelRoot", "CannonMount") self.cannon = Cannon(self, self.CannonMount) self.dirNP = self.root.attachNewNode("DirNP") self.refNP = self.root.attachNewNode("RefNP") # Creates and stores two more NodePaths, one to track the direction the cycle # is moving in and another to use as a reference during various calculations # the cycle performs. self.dirVec = Vec3(0, 0, 0) self.cycleVec = Vec3(0, 0, 0) self.refVec = Vec3(0, 0, 0) # Creates and stores 3 vector objects to be used in simulating drift when the # cycle turns. self.speed = 0 self.throttle = 0 self.maxSpeed = 200 self.maxShield = 500 self.shield = self.maxShield self.accel = 25 self.handling = 25 self.maxEnergy = 100 self.energy = self.maxEnergy # Sets basic variables for the cycle's racing attributes. self.turning = None self.lean = 0 # Creates two variables to control the cycle's lean self.markerCount = 0 self.currentLap = 0 # Creates two variables that will be used to track the progress # of the cycle on the track. self.freeFall = False self.fallSpeed = 0 # Creates two variables to assist with managing the cycle's falls from # hills and ramps. self.trackNP = render.attachNewNode(self.name + "_TrackNode") # Creates a NodePath to use when setting the cycle's height above the track. # refNP won't serve for this purpose, because it exists in root's coordinate space. # We need a NodePath in render's coordinate space for this purpose. self.active = False # creates a variable that determines if the cycle can be controlled or not. return
class Cycle(DirectObject): def __init__(self, inputManager, track, startPos, name, ai=None): self.inputManager = inputManager # Stores a reference to the InputManager to access user input. self.setupVarsNPs(startPos, name) self.setupCollisions() # Sets up initial variables, NodePaths, and collision objects. self.track = track # Stores a reference to the track. self.lanes = self.track.trackLanes.lanes # gets a reference to the lanes on the track, to shorten the variable name. startingLane = self.track.trackLanes.getNearestMarker(self).lane # Gets the lane for the closest marker to the cycle. self.uc1 = self.lanes[startingLane][0] self.uc2 = self.lanes[startingLane][1] self.uc3 = self.lanes[startingLane][2] # Sets up 3 variables to store references to the 3 up-coming markers on the # track, ahead of the cycle. These are used by the AI to steer, and by player # cycles to measure progress along the track. if (ai == True): self.ai = CycleAI(self) # if the ai input is passed anything, it won't default to None, and the cycle will create # an AI to control itself. elif (ai == None): self.ai = None taskMgr.add(self.cycleControl, "Cycle Control") # If the cycle isn't using an AI, activate player control. # With this set up, if AI == False, the cycle will be completely uncontrolled. self.setupLight() # Calls the method that creates a light to represent the glow of the cycle's discs and engine. def setupVarsNPs(self, startPos, name): self.name = name # Stores a unique name for this cycle. self.root = render.attachNewNode("Root") # Creates and stores the NodePath that will be used as the root of the cycle # for the purpose of movement. self.cycle = self.root.attachNewNode("Cycle") # Creates a dummy node to go between self.root and the actualy cycle model. if (startPos == 1): self.root.setPos(5, 0, 0) self.model = loader.loadModel("../Models/RedCycle.bam") self.turret = loader.loadModel("../Models/RedTurr.bam") elif (startPos == 2): self.root.setPos(-5, -5, 0) self.model = loader.loadModel("../Models/BlueCycle.bam") self.turret = loader.loadModel("../Models/BlueTurr.bam") elif (startPos == 3): self.root.setPos(5, -10, 0) self.model = loader.loadModel("../Models/GreenCycle.bam") self.turret = loader.loadModel("../Models/GreenTurr.bam") elif (startPos == 4): self.root.setPos(-5, -15, 0) self.model = loader.loadModel("../Models/YellowCycle.bam") self.turret = loader.loadModel("../Models/YellowTurr.bam") # Sets the root to a new position according to what place it is given. # Also loads the model and turret of the appropriate color. self.mounts = Actor("../Models/Mounts.egg") # Loads an actor with 3 mounting joints for the moving parts of the cycle. self.model.reparentTo(self.cycle) self.mounts.reparentTo(self.model) # Attaches the model to the go-between node and attaches the mounts to # the model. turretMount = self.mounts.exposeJoint(None, "modelRoot", "Turret") fdMount = self.mounts.exposeJoint(None, "modelRoot", "FrontDisc") rdMount = self.mounts.exposeJoint(None, "modelRoot", "RearDisc") # exposes the mount joints so pieces can be attached to them. self.fd = loader.loadModel("../Models/Disc.bam") self.rd = loader.loadModel("../Models/Disc.bam") # loads the models for the discs. self.turretActor = Actor("../Models/TurretActor.egg") self.turretActor.reparentTo(turretMount) self.turret.reparentTo(self.turretActor) self.trgtrMount = self.turretActor.exposeJoint(None, "modelRoot", "TargeterMount") self.fd.reparentTo(fdMount) self.rd.reparentTo(rdMount) # Attaches the turret and discs to their mounts. self.LMGMount = self.turretActor.exposeJoint(None, "modelRoot", "LMGMount") self.RMGMount = self.turretActor.exposeJoint(None, "modelRoot", "RMGMount") self.LMG = MachineGun(self, self.LMGMount) self.RMG = MachineGun(self, self.RMGMount) self.CannonMount = self.turretActor.exposeJoint( None, "modelRoot", "CannonMount") self.cannon = Cannon(self, self.CannonMount) self.dirNP = self.root.attachNewNode("DirNP") self.refNP = self.root.attachNewNode("RefNP") # Creates and stores two more NodePaths, one to track the direction the cycle # is moving in and another to use as a reference during various calculations # the cycle performs. self.dirVec = Vec3(0, 0, 0) self.cycleVec = Vec3(0, 0, 0) self.refVec = Vec3(0, 0, 0) # Creates and stores 3 vector objects to be used in simulating drift when the # cycle turns. self.speed = 0 self.throttle = 0 self.maxSpeed = 200 self.maxShield = 500 self.shield = self.maxShield self.accel = 25 self.handling = 25 self.maxEnergy = 100 self.energy = self.maxEnergy # Sets basic variables for the cycle's racing attributes. self.turning = None self.lean = 0 # Creates two variables to control the cycle's lean self.markerCount = 0 self.currentLap = 0 # Creates two variables that will be used to track the progress # of the cycle on the track. self.freeFall = False self.fallSpeed = 0 # Creates two variables to assist with managing the cycle's falls from # hills and ramps. self.trackNP = render.attachNewNode(self.name + "_TrackNode") # Creates a NodePath to use when setting the cycle's height above the track. # refNP won't serve for this purpose, because it exists in root's coordinate space. # We need a NodePath in render's coordinate space for this purpose. self.active = False # creates a variable that determines if the cycle can be controlled or not. return # setupVarsNPs: Initializes most of the non-collision variables and NodePaths needed by the cycle. def setupCollisions(self): self.shieldCN = CollisionNode(self.name + "_ShieldCN") # Creates a CollisionNode to store the 3 CollisionSpheres that represent the # invisible energy shield surrounding the cycle. self.shieldCN.setPythonTag("owner", self) # Connects a reference to the instance of this class to the shield CollisionNode. # This will make it much easier to identify this cycle when its shield is struck. CS1 = CollisionSphere(0, -.025, .75, .785) CS2 = CollisionSphere(0, -1.075, .85, .835) CS3 = CollisionSphere(0, 1.125, .6, .61) self.shieldCN.addSolid(CS1) self.shieldCN.addSolid(CS2) self.shieldCN.addSolid(CS3) # Creates the 3 CollisionSpheres that make up the shield and adds them into # the CollisionNode. self.shieldCN.setIntoCollideMask(BitMask32.range(2, 3)) self.shieldCN.setFromCollideMask(BitMask32.bit(2)) # Sets the BitMasks on the CollisionNode. The From mask has bit 2 turned on, so # the shield can bump into things on bit 2. The Into mask has bits 2, 3, and 4 turned # on so the shield can be struck by things on bit 2 (other cycles), 3 (guns), and 4 (explosions) self.shieldCNP = self.model.attachNewNode(self.shieldCN) # Connects the shield and its 3 spheres to the cycle model and gets a NodePath to # the shield. self.bumpCTrav = CollisionTraverser() self.bumpHan = CollisionHandlerPusher() # Creates a CollisionTraverser and a Pusher-type handler to detect and manage # collisions caused by the cycle's shield. self.bumpHan.addCollider(self.shieldCNP, self.root) # Tells the pusher handler to push back on self.root when self.shieldCNP is # involved in a collision. self.bumpHan.addAgainPattern("%fn-again") # Tells the pusher handler to create an event using the From CollisionNode's # name when it handles recurring collisions. self.bumpCTrav.addCollider(self.shieldCNP, self.bumpHan) # Registers the shield and the handler with the traverser. self.accept(self.name + "_ShieldCN-again", self.bump) # Registers the event that the pusher handler will generate and connects it to # the bump method. self.gRayCN = CollisionNode(self.name + "_GRayCN") # Creates a second CollisionNode to store the rays that will be used for collision # with the ground. self.fRay = CollisionRay(0, .5, 10, 0, 0, -1) self.bRay = CollisionRay(0, -.5, 10, 0, 0, -1) # Creates two rays 10 meters up and points them downward. This time we keep a # reference to the rays because we will need them when organizing their collision data. self.gRayCN.addSolid(self.fRay) self.gRayCN.addSolid(self.bRay) # Adds the rays to the CollisionNode. self.gRayCN.setFromCollideMask(BitMask32.bit(1)) self.gRayCN.setIntoCollideMask(BitMask32.allOff()) # Sets the BitMasks for gRayCN. The From mask has bit 1 on so it can cause collisions # with the ground. The Into mask is turned off completely, because rays should never # be collided into. self.gRayCNP = self.cycle.attachNewNode(self.gRayCN) # Attaches the gRayCN to the cycle and gets a NodePath to it. self.gCTrav = CollisionTraverser() self.gHan = CollisionHandlerQueue() self.gCTrav.addCollider(self.gRayCNP, self.gHan) # Creates a traverser and a Queue-type handler to detect and manage the rays' collisions. # Then registers gRayCNP and the handler with the traverser. self.trgtrCN = CollisionNode(self.name + "_TargeterCN") self.trgtrRay = CollisionRay(0, 0, 0, 0, 1, 0) self.trgtrCN.addSolid(self.trgtrRay) self.trgtrCN.setFromCollideMask(BitMask32.bit(3)) self.trgtrCN.setIntoCollideMask(BitMask32.allOff()) self.trgtrCNP = self.trgtrMount.attachNewNode(self.trgtrCN) # creates 1 collision ray to represent the line of fire of the cycle for the purpose shooting. # The ray is added to a collision node which is parented to the targeter mount of the turret. self.trgtrCTrav = CollisionTraverser() self.trgtrCHan = CollisionHandlerQueue() self.trgtrCTrav.addCollider(self.trgtrCNP, self.trgtrCHan) # creates a traverser and Queue-type handler to detect and manage the collisions of the # targeter ray, and registers the ray and handler with the traverser. return # setupCollisions: Preps CollisionNodes, collision solids, traversers, and handlers to get them # ready for use. def setupLight(self): self.glow = self.cycle.attachNewNode(PointLight(self.name + "Glow")) self.glow.node().setColor(Vec4(.2, .6, 1, 1)) # Creates a point light on the cycle and sets it's color to a blue-white. self.glow.node().setAttenuation(Vec3(0, 0, .75)) # Sets the attenuation on the point light. This controls the fall-off. self.cycle.setLight(self.glow) self.track.track.setLight(self.glow) # Sets the light to illuminate the cycle and the track. return # setupLight: Creates a point light to represent the glow of the cycle and sets its attributes. Then # sets the light to illuminate the scene. def cycleControl(self, task): if (self.cycle == None): return task.done # Ends the task if the cycle model is removed. dt = globalClock.getDt() if (dt > .20): return task.cont # Gets the amount of time that has passed since the last frame from the global clock. # If the value is too large, there has been a hiccup and the frame will be skipped. if (self.active == True): # limits player control to only occur when self.active is true. if (self.inputManager.keyMap["up"] == True): self.adjustThrottle("up", dt) elif (self.inputManager.keyMap["down"] == True): self.adjustThrottle("down", dt) # Checks the InputManager for throttle control initiated by the user and performs # the adjustments. if (self.inputManager.keyMap["right"] == True): self.turn("r", dt) self.turning = "r" elif (self.inputManager.keyMap["left"] == True): self.turn("l", dt) self.turning = "l" else: self.turning = None # Checks the InputManager for turning initiated by the user and performs it. # Also updates the self.turning variable to reflect it. if (self.inputManager.keyMap["mouse1"] == True): self.LMG.fire() self.RMG.fire() # If the left mouse button is pressed, fire the machine guns. if (self.inputManager.keyMap["mouse3"] == True): self.cannon.fire() # If the right mouse button is pressed, fire the cannon. aimPoint = self.inputManager.getMouseAim() if (aimPoint != None): self.turretActor.lookAt(render, aimPoint) self.speedCheck(dt) self.simDrift(dt) self.groundCheck(dt) self.move(dt) self.checkMarkers() # Calls the methods that control cycle behavior frame-by-frame. self.bumpCTrav.traverse(render) # Checks for collisions caused by the cycle's shield. return task.cont # cycleControl: Manages the cycle's behavior when under player control. def cameraZoom(self, dir, dt): if (dir == "in"): base.camera.setY(base.camera, 10 * dt) else: base.camera.setY(base.camera, -10 * dt) return # cameraZoom: Moves the camera toward or away from the cycle at a rate of 10 # meters per second. def turn(self, dir, dt): turnRate = self.handling * (2 - (self.speed / self.maxSpeed)) # Determines the current turn rate of the cycle according to its speed. if (dir == "r"): turnRate = -turnRate self.turning = "r" # If this is a right turn, then turnRate should be negative. self.cycle.setH(self.cycle, turnRate * dt) # Rotates the cycle according to the turnRate and time. return # turn: Rotates the cycle based on its speed to execute turns. def adjustThrottle(self, dir, dt): if (dir == "up"): self.throttle += .25 * dt # Increases the throttle setting at a rate of 25% per second. if (self.throttle > 1): self.throttle = 1 # Limits the throttle to a maximum of 100% else: self.throttle -= .25 * dt # Decreases the throttle setting at a rate of 25% per second. if (self.throttle < -1): self.throttle = -1 # Limits the throttle to a minimum of 100% return # adjustThrottle: Increases or decreases the throttle. def speedCheck(self, dt): if (self.freeFall == False): # The cycle can't accelerate or deccelerate under it's own power if # it's in freefall, so we check to make sure it isn't. tSetting = (self.maxSpeed * self.throttle) # Gets the KpH value that corresponds to the current throttle setting. if (self.speed < tSetting): # Checks if the speed is too low. if ((self.speed + (self.accel * dt)) > tSetting): # If so, check if accelerating at the normal rate would raise speed too high. self.speed = tSetting # If so, just set the speed to the throttle setting. else: self.speed += (self.accel * dt) # If accelerating won't raise the speed too high, go ahead and accelerate. elif (self.speed > tSetting): # Checks if the speed is too high. if ((self.speed - (self.accel * dt)) < tSetting): # If so, check if decelerating at the normal rate would lower speed too much. self.speed = tSetting # If so, just set the speed to the throttle setting. else: self.speed -= (self.accel * dt) # If decelerating won't loser the speed too much, go ahead and decelerate. else: self.speed -= (self.speed * .125) * dt # If the cycle is in freefall, lower it's speed by 12.5% per second to simulate loss # of momentum to friction. return # speedCheck: Controls the speed at which the cycle is moving by adjusting it according to the # throttle, or degrading it over time when in freefall. def simDrift(self, dt): self.refNP.setPos(self.dirNP, 0, 1, 0) self.dirVec.set(self.refNP.getX(), self.refNP.getY(), 0) # Uses refNP to get a vector that describes the facing of dirNP. The height value is # discarded as it is unnecessary. self.refNP.setPos(self.cycle, 0, 1, 0) self.cycleVec.set(self.refNP.getX(), self.refNP.getY(), 0) # Uses refNP to get a vector that describes the facing of the cycle. The height value is # discarded as it is unnecessary. self.refVec.set(0, 0, 1) # Sets refVec to point straight up. This vector will be the axis used to determine the # difference in the angle between dirNP and the cycle. vecDiff = self.dirVec.signedAngleDeg(self.cycleVec, self.refVec) # Gets a signed angle that describes the difference between the facing of dirNP and # the cycle. if (vecDiff < .1 and vecDiff > -.1): self.dirNP.setHpr(self.cycle.getH(), 0, 0) # if the difference between the two facings is insignificant, set dirNP to face the # same direction as the cycle. else: self.dirNP.setHpr(self.dirNP, vecDiff * dt * 2.5, 0, 0) # If the difference is significant, tell dirNP to slowly rotate to try and catch up # to the cycle's facing. self.dirNP.setP(self.cycle.getP()) self.dirNP.setR(0) # Constrains dirNP pitch and roll to the cycle and 0, respectively. return # simDrift: This function simulates the cycle drifting when it turns by causing the dirNP, which # faces the direction the cycle is moving in, to slowly catch up to the actual facing of the cycle # over time. def groundCheck(self, dt): self.gCTrav.traverse(render) # Checks for collisions between the ground and the CollisionRays attached to the cycle. points = [None, None] # Preps a list to hold the data from the collisions. if (self.gHan.getNumEntries() > 1): # Verifies that at least 2 collisions occured. If not, there's no point in checking # the collisions because we can't get data from both rays. self.gHan.sortEntries() # Arranges the collision entries in the cues from nearest to furthest. for E in range(self.gHan.getNumEntries()): # Iterates through all the entries in the CollisionHandlerQueue entry = self.gHan.getEntry(E) # Stores the current entry in a temporary variable. if (entry.getFrom() == self.fRay and points[0] == None): # Checks if this entry is a collision caused by the front ray, and # verifies that we don't have front ray data for this frame yet. points[0] = entry.getSurfacePoint(render) # Stores the actual point of collision, in the coordinate system of render, # in the first slot of the points list. elif (entry.getFrom() == self.bRay and points[1] == None): # Checks if this entry is a collision caused by the back ray, and # verifies that we don't have back ray data for this frame yet. points[1] = entry.getSurfacePoint(render) # Stores the actual point of collision, in the coordinate system of render, # in the second slot of the points list. if (points[0] == None or points[1] == None): self.teleport() return # If either ray didn't collide with the track, the cycle is going out of bounds # and needs to be teleported back onto the track. else: # If both rays gave us collision data, we can proceed. ''' The following segment of code controls the pitch of the cycle ''' if (self.freeFall == False): # Checks if the cycle is in freefall. If it's not, we'll need to make the cycle's # pitch match the angle of the track. self.refNP.setPos(points[1]) # Sets refNP to the spot on the track where the back ray collided. self.refNP.lookAt(points[0]) # Tells refNP to point at the spot on the track where the front ray collided. pDiff = self.refNP.getP() - self.cycle.getP() # Finds the difference in pitch between refNP and the cycle, which is equivalent # to the difference between the cycle's pitch and the angle of the track. if (pDiff < .1 and pDiff > -.1): self.cycle.setP(self.refNP.getP()) # If the pitch difference is insignificant, set the cycle to match the pitch of # refNP. else: self.cycle.setP(self.cycle, pDiff * dt * 5) # If the difference is significant, smoothly adjust the cycle's pitch toward the # pitch of refNP. elif ((self.cycle.getP() - (dt * 10)) > -15): self.cycle.setP(self.cycle, -(dt * 10)) # If the cycle is in freefall and slowly dropping the pitch won't lower it past -15, # go ahead and slowly lower it. else: self.cycle.setP(-15) # If we're in freefall and the cycle's pitch is to low to drop it any further, lock it # to exactly -15. ''' End pitch control ''' ''' The following section of code will control the height of the cycle above the track. ''' if (self.speed >= 0): self.trackNP.setPos(points[0].getX(), points[0].getY(), points[0].getZ()) else: self.trackNP.setPos(points[1].getX(), points[1].getY(), points[1].getZ()) # Set trackNP at the collision point on the leading end of the cycle. height = self.root.getZ(self.trackNP) # Get the height of root as seen from the trackNP. if (height > 2 and self.freeFall == False): self.freeFall = True self.fallSpeed = 0 # If the height is greater than 2 and we aren't in freefall, # enter a freefall state and prep freefall variables. if (self.freeFall == True): self.fallSpeed += (self.track.gravity * 9.8) * dt newHeight = height - (self.fallSpeed * dt) # In a freefall state, begin accelerating the fall speed and # calculate a new height based on that fall speed. else: hDiff = 1 - height # If not in a freefall state, calculate the difference in the actual height and the # desired height. if (hDiff > .01 or hDiff < -.01): newHeight = height + (hDiff * dt * 5) # If the difference is significant, calculate a new height that drifts toward # the desired height. else: newHeight = 1 # If you're close to the desired height, just set it as the calculated new height. if (newHeight >= 0): self.root.setZ(self.trackNP, newHeight) # If the new height is greater than or equal to zero, set it as root's height. else: self.root.setZ(self.trackNP, 0) self.freeFall = False # Otherwise, set the root node to a height of 0, and turn off the freefall state. ''' end of height control code ''' self.cycle.setR(0) # Constrain the cycle's roll to 0. return # groundCheck: Controls the cycle's pitch and it's height above the track. def move(self, dt): mps = self.speed * 1000 / 3600 # Convert kph to meters per second self.refNP.setPos(self.dirNP, 0, 1, 0) self.dirVec.set(self.refNP.getX(), self.refNP.getY(), self.refNP.getZ()) # Uses refNP to get a vector describing the direction dirNP is facing. self.root.setPos(self.root, self.dirVec.getX() * dt * mps, self.dirVec.getY() * dt * mps, self.dirVec.getZ() * dt * mps) # Moves root forward according to the direction vector, speed, and time. currentLean = self.model.getR() # Get the current amount of lean. if (self.turning == "r"): self.lean += 2.5 if (self.lean > 25): self.lean = 25 self.model.setR(self.model, (self.lean - currentLean) * dt * 5) # If the cycle is turning right, increase lean up to 25 and model the frame to lean the cycle. elif (self.turning == "l"): self.lean -= 2.5 if (self.lean < -25): self.lean = -25 self.model.setR(self.model, (self.lean - currentLean) * dt * 5) # If the cycle is turning left, decrease lean down to -25 and roll the model to lean the cycle. else: self.lean = 0 self.model.setR(self.model, (self.lean - currentLean) * dt * 5) # If the cycle isn't turning, set lean to 0 and roll the model back toward upright. self.fd.setH(self.fd, 5 + (20 * self.throttle)) self.rd.setH(self.rd, -5 + (-20 * self.throttle)) return # move: Controls the forward or backward movement of the cycle. def checkMarkers(self): if (self.uc1.checkInFront(self) == True): # Checks if the cycle has passed in front of uc1. self.uc1 = self.uc2 self.uc2 = self.uc3 self.uc3 = self.uc2.nextMarker # If so, get the next set of markers on the track. self.markerCount += 1 # Update the cycle's marker count by one. if (self.uc1 == self.lanes[0][1] or self.uc1 == self.lanes[1][1]): self.currentLap += 1 # If the cycle just passed the first marker, which is at the finish line, increment the lap count. return # checkMarkers: Checks if the nearest marker has been passed, and if so, # updates all the markers, marker count, and lap count if needed. def teleport(self): marker = self.track.trackLanes.getNearestMarker(self) markerPos = marker.getPos() self.root.setPos(markerPos.getX(), markerPos.getY(), self.root.getZ()) # Put the cycle back on the track. self.gCTrav.traverse(render) # Checks for collisions between the ground and the CollisionRays attached to the cycle. points = [None, None] # Preps a list to hold the data from the collisions. if (self.gHan.getNumEntries() > 1): # Verifies that at least 2 collisions occured. If not, there's no point in checking # the collisions because we can't get data from both rays. self.gHan.sortEntries() # Arranges the collision entries in the cues from nearest to furthest. for E in range(self.gHan.getNumEntries()): # Iterates through all the entries in the CollisionHandlerQueue entry = self.gHan.getEntry(E) # Stores the current entry in a temporary variable. if (entry.getFrom() == self.fRay and points[0] == None): # Checks if this entry is a collision caused by the front ray, and # verifies that we don't have front ray data for this frame yet. points[0] = entry.getSurfacePoint(render) # Stores the actual point of collision, in the coordinate system of render, # in the first slot of the points list. elif (entry.getFrom() == self.bRay and points[1] == None): # Checks if this entry is a collision caused by the back ray, and # verifies that we don't have back ray data for this frame yet. points[1] = entry.getSurfacePoint(render) # Stores the actual point of collision, in the coordinate system of render, # in the second slot of the points list. if (self.speed >= 0): self.trackNP.setPos(points[0].getX(), points[0].getY(), points[0].getZ()) else: self.trackNP.setPos(points[1].getX(), points[1].getY(), points[1].getZ()) # Set the track node at the collision point on the leading end of the cycle. self.root.setZ(self.trackNP, 1) # Set the root to a height of 1 above trackNP. self.dirNP.setHpr(marker.getHpr()) self.cycle.setHpr(marker.getHpr()) # Reorients dirNP and the cycle to the same facing as the marker we teleported to. self.speed /= 2 # Cuts the speed by half as a penalty for going off the track. return # teleport: Moves the cycle back onto the track, fixes its height, and fixes its orientation. def bump(self, entry): print(entry.getFromNodePath().getPythonTag("owner").name) print("has bumped into:") print(entry.getIntoNodePath().getPythonTag("owner").name) print("") return # bump: Prints a message to the command prompt when the cycle bumps into another cycle. def hit(self, damage): print(self.name + " has taken " + str(damage) + " damage!") return # hit: Handles tracking damage for the cycle. def getPos(self, ref=None): if (ref == None): return (self.root.getPos()) else: return (self.root.getPos(ref)) # getPos: returns the position of root in the coordinate system of the given NodePath, if one is given. def destroy(self): self.root.removeNode() self.cycle.removeNode() self.mounts.delete() self.turretActor.delete() self.model.removeNode() self.turret.removeNode() self.fd.removeNode() self.rd.removeNode() self.dirNP.removeNode() self.refNP.removeNode() self.trackNP.removeNode() self.shieldCNP.removeNode() self.gRayCNP.removeNode() self.trgtrCNP.removeNode() self.glow.removeNode() # removes all of the cycle's NodePaths from the scene. self.LMG.destroy() self.LMG = None self.RMG.destroy() self.RMG = None self.cannon.destroy() self.cannon = None # Removes the cycle's weapons. self.cycle = None # sets self.cycle to None to end player cycle control and notify # any AI that the cycle is being removed. if (self.ai != None): self.ai = None # removes the cycles reference to the AI, if it has one. return
def __init__(self): self.keyMap = { "arrow_left": 0, "arrow_right": 0, "arrow_up": 0, "arrow_down": 0, "cam-left": 0, "cam-right": 0, "make-bunny": 0, "do-something": 0, "ignore": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Track all of the bunnies self.bunnies = [] # Post the instructions self.title = addTitle("Keyboard Roaming") self.inst1 = addInstructions(0.95, "[Shift+ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst4 = addInstructions(0.75, "[Down Arrow]: Run Ralph Backward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(0.3) self.ralph.setPos(ralphStartPos) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Shift+ESC key exits self.accept("shift-escape", sys.exit) # Tke keyboard is divided into six sections or tiles: # # 1 2 # +----------------+ +-------------+ # | f1 ... F5 | | F6 ... F12 | # +----------------+ +-------------+ # # 3 4 # +----------------+ +-------------------------+ # | ` 1 2 3 4 5 6 | | 7 8 9 0 - = BACKSPACE | # | Q W E R T Y | | Y U I O P [ ] \ | # | A S D F G | | H J K L ; ' ENTER | # | Z X C V B | | N M , . / | # | CTRL WIN ALT | | SPACE ALT WIN MENU CTRL | # +----------------+ +-------------------------+ # # 5 # +----------------------+ # | PRT SCR PAUSE | # | INSERT HOME PAGEUP | # | DELETE END PAGEDOWN | # +----------------------+ # 6 # +----------------------+ # | UP LEFT DOWN RIGHT | # +----------------------+ # Section1 = ["f1", "f2", "f3", "f4", "f5"] Section2 = ["f6", "f7", "f8", "f9", "f10", "f11", "f12"] Section3 = [ "`", "1", "2", "3", "4", "5", "6", "q", "w", "e", "r", "t", "y", "a", "s", "d", "f", "g", "lshift", "z", "x", "c", "v", "b" ] Section4 = [ "7", "8", "9", "0", "backspace", "y", "u", "i", "o", "p", "[", "]", "\\", "h", "j", "k", "l", ";", "'", "enter", "n", "m", ",", ".", "/", "rshift" ] Section5 = [ "print_screen", "scroll_lock", "pause", "insert", "home", "page_up", "delete", "end", "page_down" ] Section6 = ["arrow_left", "arrow_right", "arrow_up", "arrow_down"] # Map each section action = "cam-left" for k in Section1: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "cam-right" for k in Section2: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_up" for k in Section3: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "arrow_down" for k in Section4: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) action = "make-bunny" for k in Section5: self.accept(k, self.setKey, [action, 1]) self.accept("shift-" + k, self.setKey, [action, 1]) self.accept(k + "-up", self.setKey, [action, 0]) self.accept("shift-" + k + "-up", self.setKey, [action, 0]) for k in Section6: self.accept(k, self.setKey, [k, 1]) self.accept("shift-" + k, self.setKey, [k, 1]) self.accept(k + "-up", self.setKey, [k, 0]) self.accept("shift-" + k + "-up", self.setKey, [k, 0]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # Set up some sounds self.runSound = base.loader.loadSfx( "sounds/54779__bevangoldswain__running-hard-surface.wav") self.bumpSound = base.loader.loadSfx( "sounds/31126__calethos__bump.wav") self.spawnSound = base.loader.loadSfx( "sounds/51710__bristolstories__u-chimes3.mp3")
def __init__(self): ShowBase.__init__(self) self.actor = Actor("worm.bam") self.actor.reparent_to(render) self.actor.loop("idle")
class DistributedEagleSuit(DistributedSuit): notify = directNotify.newCategory("DistributedEagleSuit") def __init__(self, cr): DistributedSuit.__init__(self, cr) self.eagleCry = base.audio3d.loadSfx( 'phase_5/audio/sfx/tt_s_ara_cfg_eagleCry.ogg') base.audio3d.attachSoundToObject(self.eagleCry, self) self.fallWhistle = base.audio3d.loadSfx( 'phase_5/audio/sfx/incoming_whistleALT.ogg') base.audio3d.attachSoundToObject(self.fallWhistle, self) self.explode = base.audio3d.loadSfx( 'phase_3.5/audio/sfx/ENC_cogfall_apart.ogg') base.audio3d.attachSoundToObject(self.explode, self) self.eventSphereNodePath = None self.fallingPropeller = None self.fallingPropProjectile = None self.mg = None self.flySpeed = 0.0 # A work around to prevent the weird standing eagles in the air. def enterNeutral(self, ts=0): self.show() self.timestampAnimTrack = Sequence(Wait(ts), Func(self.loop, "flyNeutral")) self.timestampAnimTrack.start() def makeStateDict(self): self.suitFSM.addState( State('eagleFly', self.enterEagleFly, self.exitEagleFly)) self.suitFSM.addState( State('eagleFall', self.enterEagleFall, self.exitEagleFall)) self.stateIndex2suitState = { 0: self.suitFSM.getStateNamed('off'), 1: self.suitFSM.getStateNamed('walking'), 2: self.suitFSM.getStateNamed('flyingDown'), 3: self.suitFSM.getStateNamed('flyingUp'), 4: self.suitFSM.getStateNamed('lured'), 5: self.suitFSM.getStateNamed('eagleFly'), 6: self.suitFSM.getStateNamed('eagleFall') } self.suitState2stateIndex = {} for stateId, state in self.stateIndex2suitState.items(): self.suitState2stateIndex[state.getName()] = stateId def setFlySpeed(self, value): self.flySpeed = value def getFlySpeed(self): return self.flySpeed def enterEagleFly(self, startIndex, endIndex, ts=0.0): durationFactor = self.getFlySpeed() if startIndex > -1: startPos = EGG.EAGLE_FLY_POINTS[startIndex] else: startPos = self.getPos(render) endPos = EGG.EAGLE_FLY_POINTS[endIndex] if self.moveIval: self.moveIval.pause() self.moveIval = None self.moveIval = NPCWalkInterval(self, endPos, durationFactor=durationFactor, startPos=startPos, fluid=1) self.moveIval.start(ts) def exitEagleFly(self): if self.moveIval: self.moveIval.pause() self.moveIval = None def enterEagleFall(self, startIndex, endIndex, ts=0.0): self.moveIval = LerpPosInterval(self, duration=4.0, pos=self.getPos(render) - (0, 0, 75), startPos=self.getPos(render), blendType='easeIn') self.moveIval.start(ts) def exitEagleFall(self): if self.moveIval: self.moveIval.finish() self.moveIval = None def fallAndExplode(self): self.cleanupPropeller() self.fallingPropeller = Actor( "phase_4/models/props/propeller-mod.bam", {"chan": "phase_4/models/props/propeller-chan.bam"}) self.fallingPropeller.reparentTo(render) self.fallingPropeller.loop('chan', fromFrame=0, toFrame=3) parentNode = self.attachNewNode('fallingPropParentNode') h = random.randint(0, 359) parentNode.setH(h) dummyNode = parentNode.attachNewNode('dummyNode') dummyNode.setPos(0, 10, -50) self.fallingPropProjectile = FlightProjectileInterval( self.fallingPropeller, startPos=self.find('**/joint_head').getPos(render), endPos=dummyNode.getPos(render), duration=5.0, gravityMult=.25) self.fallingPropProjectile.start() dummyNode.removeNode() del dummyNode parentNode.removeNode() del parentNode self.updateHealthBar(0) self.ignoreHit() base.playSfx(self.fallWhistle, node=self) taskMgr.doMethodLater(4.0, self.doExplodeSound, self.uniqueName("DEagleSuit-doExplodeSound")) def doExplodeSound(self, task): base.playSfx(self.explode, node=self) return Task.done def __initializeEventSphere(self): sphere = CollisionSphere(0, 0, 0, 2) sphere.setTangible(0) node = CollisionNode(self.uniqueName("DEagleSuit-eventSphere")) node.addSolid(sphere) node.setCollideMask(CIGlobals.WallBitmask) np = self.attachNewNode(node) np.setSz(2.5) np.setZ(5.5) #np.show() self.eventSphereNodePath = np def removeEventSphere(self): if self.eventSphereNodePath: self.eventSphereNodePath.removeNode() self.eventSphereNodePath = None def acceptHit(self): self.acceptOnce('enter' + self.eventSphereNodePath.node().getName(), self.__handleHit) def ignoreHit(self): self.ignore('enter' + self.eventSphereNodePath.node().getName()) def __handleHit(self, entry): messenger.send(EGG.EAGLE_HIT_EVENT, [self.doId]) def setSuit(self, arg, variant): DistributedSuit.setSuit(self, arg, 3) self.deleteShadow() self.disableBodyCollisions() self.disableRay() self.__initializeEventSphere() self.show() self.setAnimState('flyNeutral') def __doEagleCry(self, task): base.playSfx(self.eagleCry, node=self) task.delayTime = random.uniform(3, 30) return Task.again def announceGenerate(self): DistributedSuit.announceGenerate(self) taskMgr.doMethodLater(random.uniform(5, 25), self.__doEagleCry, self.uniqueName("DEagleSuit-doEagleCry")) self.acceptHit() def disable(self): self.ignoreHit() self.removeEventSphere() taskMgr.remove(self.uniqueName("DEagleSuit-doExplodeSound")) taskMgr.remove(self.uniqueName("DEagleSuit-doEagleCry")) if self.fallingPropProjectile: self.fallingPropProjectile.finish() self.fallingPropProjectile = None if self.fallingPropeller: self.fallingPropeller.cleanup() self.fallingPropeller = None base.audio3d.detachSound(self.fallWhistle) del self.fallWhistle base.audio3d.detachSound(self.explode) del self.explode base.audio3d.detachSound(self.eagleCry) del self.eagleCry self.mg = None DistributedSuit.disable(self)
def getModel(self): return Actor('models/eve/eve.egg', { 'run': 'models/eve/eve-run.egg', 'walk': 'models/eve/eve-walk.egg' })
def move(self, task): # Ignore certain keys if (self.keyMap["ignore"] != 0): self.keyMap["ignore"] = 0 print("Ignoring key...") # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.ralph) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["arrow_left"] != 0): self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt()) self.positionBunnies() if (self.keyMap["arrow_right"] != 0): self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt()) self.positionBunnies() if (self.keyMap["arrow_up"] != 0): self.ralph.setY(self.ralph, -50 * globalClock.getDt()) self.positionBunnies() if (self.keyMap["arrow_down"] != 0): self.ralph.setY(self.ralph, 50 * globalClock.getDt()) self.positionBunnies() # If an object creation key is pressed, create an object of the desired type if (self.keyMap["make-bunny"] != 0): self.keyMap["make-bunny"] = 0 # Avoid multiplying like rabbits! if (self.spawnSound.status() != AudioSound.PLAYING): self.spawnSound.play() if (random.random() < 0.5): new_bunny = Actor("models/Bunny2") else: new_bunny = Actor("models/Chicken") new_bunny.reparentTo(render) new_bunny.setScale(0.3) self.bunnies.append(new_bunny) self.positionBunnies() # Handle the catch-all do-something keys if (self.keyMap["do-something"] != 0): self.keyMap["do-something"] = 0 print "Something!" # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["arrow_up"] != 0) or (self.keyMap["arrow_down"] != 0) or (self.keyMap["arrow_left"] != 0) or (self.keyMap["arrow_right"] != 0): if self.isMoving is False: self.ralph.loop("run") self.isMoving = True if (self.runSound.status() != AudioSound.PLAYING): self.runSound.play() else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False self.runSound.stop() # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.ralph.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # Now check for collisions. self.cTrav.traverse(render) # Adjust ralph's Z coordinate. If ralph's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame. entries = [] for i in range(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): self.ralph.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.ralph.setPos(startpos) if (self.bumpSound.status() != AudioSound.PLAYING): self.bumpSound.play() # Keep the camera at one foot above the terrain, # or two feet above ralph, whichever is greater. entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): base.camera.setZ(entries[0].getSurfacePoint(render).getZ() + 1.0) if (base.camera.getZ() < self.ralph.getZ() + 2.0): base.camera.setZ(self.ralph.getZ() + 2.0) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.ralph.getPos()) self.floater.setZ(self.ralph.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont
class Me(DirectObject): """Testing self controlled player, can be build upon""" def __init__(self): self.model = Actor("assets/models/ninja", {"walk": "assets/models/ninja"}) self.actorHead = self.model.exposeJoint(None, 'modelRoot', 'Joint8') # self.model.setScale(4) self.username = input("Input username: \n") self.player_id = None self.Dt_update = self.Dt = 0 self.model.reparentTo(base.render) self.model.setScale(0.5) self.moving = False self.AnimControl = self.model.getAnimControl('walk') self.AnimControl.setPlayRate(0.05) self.model.setBlend(frameBlend=1) self.model.setPos(244, 188, 0) # STORE TERRAIN SCALE FOR LATER USE# self.terrainScale = terrain.terrain.getRoot().getSz() base.camera.reparentTo(self.model) self.camDummy = self.model.attachNewNode("camDummy") self.camDummy.setZ(5) def move(self, arg): # self.meTerrainHeight = terrainClass.terrain.getElevation(self.model.getX(),self.model.getY()) * self.terrainScale # self.camTerrainHeight = terrainClass.terrain.getElevation(camera.getX(),camera.getY()) * self.terrainScale self.Dt = globalClock.getDt() # base.camera.lookAt(self.actorHead) if keys.keyMap["left"] != 0: self.model.setH(self.model.getH() + self.Dt * 300) logging.debug(f"{self.model.getY()}, {self.model.getX()}") if keys.keyMap["right"] != 0: self.model.setH(self.model.getH() - self.Dt * 300) if keys.keyMap["forward"] != 0: self.model.setY(self.model, (self.Dt * 40)) if keys.keyMap["back"] != 0: self.model.setY(self.model, -(self.Dt * 40)) if (keys.keyMap["forward"] != 0) or \ (keys.keyMap["left"] != 0) or \ (keys.keyMap["right"] != 0): if self.moving is False: self.model.loop("walk", fromFrame=1, toFrame=11) self.moving = True else: if self.moving: self.model.stop() self.model.pose("walk", 5) self.moving = False self.meTerrainHeight = terrain.terrain.getElevation( self.model.getX(), self.model.getY()) * self.terrainScale self.model.setZ(self.meTerrainHeight) # base.camera.reparentTo(self.model) base.camera.lookAt(self.camDummy) base.camLens.setNear(.1) if keys.keyMap["cam"] == 1: # base.camera.setZ(5) # base.camera.setY(1) base.disableMouse() base.camera.setPosHpr(0, 2, 5, 0, 0, 0) elif keys.keyMap["cam"] == 2: # base.camera.setPosHpr(0,-30,10,0,0,0) base.enableMouse() else: base.disableMouse() base.camera.setPosHpr(0, -30, 10, 0, 0, 0) # base.camera.setZ(10) # base.camera.setY(-30) return Task.cont
class World(ShowBase): def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Add a directional light dPos = Vec3(40, 40, 15) dirLight = DirectionalLight() dirLight.setPos(dPos * 1000000.0) dirLight.setShadowMapResolution(1024) dirLight.setCastsShadows(True) dirLight.setColor(Vec3(8)) self.renderPipeline.addLight(dirLight) self.renderPipeline.setScatteringSource(dirLight) self.dirLight = dirLight self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right") # Set up the environment # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) self.environ.setPos(0, 0, 0) self.environ.find("**/wall").removeNode() # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos) self.renderPipeline.setEffect(self.ralph, "Effects/Default/Default.effect", {"dynamic": True}) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # NOTICE: It is important that your update tasks have a lower priority # than -10000 taskMgr.add(self.move, "moveTask", priority=-20000) self.accept("r", self.reloadShader) # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 1.2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays # self.ralphGroundColNp.show() # self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring # self.cTrav.showCollisions(render) # Create some ocean self.water = ProjectedWaterGrid(self.renderPipeline) self.water.setWaterLevel(-3.0) # Create the skybox self.skybox = self.renderPipeline.getDefaultSkybox() self.skybox.reparentTo(render) self.prepareSRGB(render) self.reloadShader() self.renderPipeline.onSceneInitialized() # Add demo slider to move the sun position if self.renderPipeline.settings.displayOnscreenDebugger: self.renderPipeline.guiManager.demoSlider.node[ "command"] = self.setSunPos self.renderPipeline.guiManager.demoSlider.node["value"] = 50 def setSunPos(self): rawValue = self.renderPipeline.guiManager.demoSlider.node["value"] dPos = Vec3(100, 100, rawValue - 20) self.dirLight.setPos(dPos * 100000000.0) def reloadShader(self): self.renderPipeline.reloadShaders() # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value def prepareSRGB(self, np): """ Sets the correct texture format for all textures found in <np> """ for tex in np.findAllTextures(): baseFormat = tex.getFormat() if baseFormat == Texture.FRgb: tex.setFormat(Texture.FSrgb) elif baseFormat == Texture.FRgba: tex.setFormat(Texture.FSrgbAlpha) else: print "Unkown texture format:", baseFormat print "\tTexture:", tex # tex.setMinfilter(Texture.FTLinearMipmapLinear) # tex.setMagfilter(Texture.FTLinear) tex.setAnisotropicDegree(16) # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. base.camera.lookAt(self.ralph) if (self.keyMap["cam-left"] != 0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"] != 0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["left"] != 0): self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt()) if (self.keyMap["right"] != 0): self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt()) if (self.keyMap["forward"] != 0): self.ralph.setY(self.ralph, -25 * globalClock.getDt()) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if (self.keyMap["forward"] != 0) or (self.keyMap["left"] != 0) or (self.keyMap["right"] != 0): if self.isMoving is False: self.ralph.loop("run") self.isMoving = True else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. camvec = self.ralph.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 7.0): base.camera.setPos(base.camera.getPos() + camvec * (camdist - 7)) camdist = 7.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist)) camdist = 5.0 # Now check for collisions. self.cTrav.traverse(render) # Adjust ralph's Z coordinate. If ralph's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame. entries = [] for i in range(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): self.ralph.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.ralph.setPos(startpos) # Keep the camera at one foot above the terrain, # or two feet above ralph, whichever is greater. entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName() == "terrain"): base.camera.setZ(entries[0].getSurfacePoint(render).getZ() + 1.0) if (base.camera.getZ() < self.ralph.getZ() + 2.5): base.camera.setZ(self.ralph.getZ() + 2.5) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.floater.setPos(self.ralph.getPos()) self.floater.setZ(self.ralph.getZ() + 2.0) base.camera.lookAt(self.floater) return task.cont
class thirdPerson(DirectObject): def __init__(self, parserClass, mainClass, mapLoaderClass, modelLoaderClass): self.switchState = False #self.t = Timer() self.keyMap = {"left": 0, "right": 0, "forward": 0, "backward": 0} self.ralph = Actor( "data/models/units/ralph/ralph", { "run": "data/models/units/ralph/ralph-run", "walk": "data/models/units/ralph/ralph-walk" }) self.ralph.reparentTo(render) # self.ralph.setPos(42, 30, 0) self.ralph.setPos(6, 10, 0) self.ralph.setScale(0.1) self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("arrow_down", self.setKey, ["backward", 1]) self.accept("arrow_down-up", self.setKey, ["backward", 0]) self.isMoving = False self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) #self.ralphGroundCol.show() base.cam.reparentTo(self.ralph) base.cam.setPos(0, 9, 7) self.floater2 = NodePath(PandaNode("floater2")) self.floater2.reparentTo(self.ralph) self.floater2.setZ(self.floater2.getZ() + 6) base.cam.lookAt(self.floater2) # Uncomment this line to see the collision rays # self.ralphGroundColNp.show() # self.camGroundColNp.show() #Uncomment this line to show a visual representation of the #collisions occuring # self.cTrav.showCollisions(render) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) taskMgr.add(self.move, "movingTask", extraArgs=[ mainClass, parserClass, mapLoaderClass, modelLoaderClass ]) #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value def move(self, mainClass, parserClass, mapLoaderClass, modelLoaderClass): # Get the time elapsed since last frame. We need this # for framerate-independent movement. elapsed = globalClock.getDt() # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if (self.keyMap["left"] != 0): self.ralph.setH(self.ralph.getH() + elapsed * 300) if (self.keyMap["right"] != 0): self.ralph.setH(self.ralph.getH() - elapsed * 300) if (self.keyMap["forward"] != 0): self.ralph.setY(self.ralph, -(elapsed * 50)) #25)) if (self.keyMap["backward"] != 0): self.ralph.setY(self.ralph, +(elapsed * 20)) if (self.keyMap["forward"] != 0) or (self.keyMap["left"] != 0) or (self.keyMap["right"] != 0): if self.isMoving is False: self.ralph.loop("run") self.isMoving = True elif (self.keyMap["backward"] != 0): if self.isMoving is False: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False # Now check for collisions. self.cTrav.traverse(render) # Adjust ralph's Z coordinate. If ralph's ray hit terrain, # update his Z. If it hit anything else, or didn't hit anything, put # him back where he was last frame. entries = [] for i in range(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x, y: cmp( y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries) > 0) and (entries[0].getIntoNode().getName()[0:4] == "tile"): self.ralph.setZ(entries[0].getSurfacePoint(render).getZ()) elif (len(entries) > 0) and (entries[0].getIntoNode().getName()[0:5] == "solid"): self.ralph.setPos(startpos) x = int(entries[0].getIntoNode().getName() [len(entries[0].getIntoNode().getName()) - 6:len(entries[0].getIntoNode().getName()) - 4]) y = int(entries[0].getIntoNode().getName() [len(entries[0].getIntoNode().getName()) - 2:]) if (mapLoaderClass.tileArray[y][x].drillTime != None): mainClass.changeTile(mapLoaderClass.tileArray[y][x], 0, parserClass, modelLoaderClass, mapLoaderClass) else: self.ralph.setPos(startpos) self.ralph.setP(0) return Task.cont
class Player(): def __init__(self, _game, _name): self.game = _game self.name = _name # Player physics body self.pPhysicsBody = None self.pRayNode = None self.playerModel = None # Fsm State self.playerActiveState = None ## Physics self.physics = PlayerPhysics(self) # Player Device self.device = Device(self) def start(self): self.buildPlayerPhysicsBody() self.setPlayerModel("ball") # Player FSM self.playerFSM = PlayerFSM(self, self.playerModel) # Update taskMgr.add(self.update, "player-update") def stop(self): taskMgr.remove("player-update") def buildPlayerPhysicsBody(self): self.pPhysicsBody = self.physics.createPlayerBody(self.name) #self.playerRopeNode = self.physics.createRopeNode() def setPlayerModel(self, _modelName): self.playerModel = Actor( "assets/models/" + _modelName, {'walk': "assets/models/" + _modelName + "-walk"}) self.playerModel.setScale(.65) #self.playerModel.setHpr(180, 0, 0) #self.playerModel.setPos(0, 0, 0) if self.pPhysicsBody != None: self.playerModel.reparentTo(self.pPhysicsBody) #self.playerModel.setPos(0, 0, -1.15) else: print "No Player Physics Body found!" ## Attach a raynode used for jumping. playerRayNode = self.pPhysicsBody.attachNewNode("ray-dummy") #playerRayNode.setCompass() self.pRayNode = playerRayNode ## Attach a dummy node for the camera self.camDummy = self.pPhysicsBody.attachNewNode("cam-dummy") # #self.camDummy.setCompass() ## Telekinesis np to hack pivot self.centerRotNode = self.camDummy.attachNewNode("tele-dummy") self.centerRotNode.setCompass() self.centerRotNode.setPos(-12, 10, 0) def update(self, task): ## Get the direction to the mouse and set it so that it directs the player to it. # Make a change depending on gear mpos = self.game.input.getMousePointAlways() vector = Vec3(0, 0, 0) if mpos != None: vector = mpos - self.playerModel.getPos(render) #print vector self.pPhysicsBody.lookAt(mpos) #self.physics.telekinesisTask() if self.game.input.rightMDown: self.physics.doMovement(vector) return task.cont ## Event Methods def evtPlaceDevice(self, _mouseFromTo): pass def requestState(self, _state): if self.playerActiveState == _state: return else: self.playerFSM.request(_state) self.playerActiveState = _state
def getModel(self): return Actor( 'models/ralph/ralph.egg.pz', { 'run': 'models/ralph/ralph-run.egg.pz', 'walk': 'models/ralph/ralph-walk.egg.pz' })
class Agent(NodePath): """ The Agent class takes care of the Actor component (game) and the ActorNode component (physics) inside an agent. You can call this as you would any NodePath. """ def __init__(self, modelStanding, modelAnimationDict, turnRate, speed, agentList, massKg, collisionMask, name="", collisionHandler = None, collisionTraverser = None): NodePath.__init__(self, ActorNode(name + " actor node")) self.name = name self.actor = Actor() self.actor.loadModel(modelStanding) self.actor.loadAnims(modelAnimationDict) self.loop = self.actor.loop self.stop = self.actor.stop self.pose = self.actor.pose self.turnRate = turnRate self.speed = speed self.agentList = agentList self.massKg = massKg self.collisionMask = collisionMask if self.actor not in agentList: self.agentList.append(self.actor) self.actor.reparentTo(self) self.__setupCollisionHandling(collisionHandler, collisionTraverser) def turnLeft(self, angle): self.setH(self, angle) def turnRight(self, angle): self.setH(self, -angle) def moveForward(self, distance): self.setFluidY(self, -distance) def moveBackward(self, distance): self.setFluidY(self, distance) def __setupCollisionHandling(self, collisionHandler, collisionTraverser): if not collisionTraverser.getRespectPrevTransform(): collisionTraverser.setRespectPrevTransform(True) # We do this so we don't take into account the actual model, but the collision sphere self.actor.setCollideMask(BitMask32.allOff()) self.node().getPhysicsObject().setMass(self.massKg) base.physicsMgr.attachPhysicalNode(self.node()) fromObject = self.attachNewNode(CollisionNode(self.name + " collision node")) fromObject.node().setIntoCollideMask(fromObject.node().getIntoCollideMask() & ~GeomNode.getDefaultCollideMask()) fromObject.node().setFromCollideMask(self.collisionMask) fromObject.node().addSolid(CollisionSphere(0, 0, 2.5, 2.5)) collisionHandler.addCollider(fromObject, self) collisionTraverser.addCollider(fromObject, collisionHandler)
def __init__(self): self.keyMap = {"left":0, "right":0, "forward":0, "back":0, "cam-left":0, "cam-right":0} self.flag1=0 self.flag2=0 self.flag3=0 self.flag4=0 self.count=0 self.health = 100 self.points = -5 self.flagd=1 self.player_points = 0 base.win.setClearColor(Vec4(0,0,0,1)) self.mySound=base.loader.loadSfx("sounds/trial.mp3") self.mySound.play() self.title = addTitle("Bumping Cars") #Full Screen props = WindowProperties.getDefault() w=base.pipe.getDisplayWidth() h=base.pipe.getDisplayHeight() props.setSize(w,h) props.setFullscreen(True) props.setCursorHidden(True) base.win.requestProperties(props) # Load World self.environ = loader.loadModel("models/world.egg") self.environ.reparentTo(render) self.environ.setPos(0,0,0) #Load Sky self.sky = loader.loadModel("models/clouds.egg") self.sky.reparentTo(render) self.sky.setPos(60,0,-450) # Create Player Car carStartPos = self.environ.find("**/start_point").getPos() self.car = Actor("models/carnsx") self.car.reparentTo(render) self.car.setScale(0.25) #self.car.place() self.car.setPos(carStartPos) # Create Enemy Car 1 enemyCarStartPos1 = (-108,-1,-.5) self.car1 = Actor("models/enemy_cars/monstercar/carmonster") self.car1.reparentTo(render) self.car1.setScale(0.25) #self.car1.place() self.car1.setPos(enemyCarStartPos1) # Create Enemy Car 2 enemyCarStartPos2 = (-104,-26,-.02) self.car2 = Actor("models/enemy_cars/yugo/yugo") self.car2.reparentTo(render) self.car2.setScale(0.15) #self.car2.place() self.car2.setPos(enemyCarStartPos2) # Create Enemy Car 3 enemyCarStartPos3 = (-111,-26,0) self.car3 = Actor("models/enemy_cars/truck/cartruck") self.car3.reparentTo(render) self.car3.setScale(0.25) #self.car3.place() self.car3.setPos(enemyCarStartPos3) # Create Enemy Car 4 enemyCarStartPos4 = (-111,-2,-.5) self.car4 = Actor("models/enemy_cars/truck/cartruck-purple") self.car4.reparentTo(render) self.car4.setScale(0.25) #self.car4.place() self.car4.setPos(enemyCarStartPos4) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("a", self.setKey, ["cam-left",1]) self.accept("s", self.setKey, ["cam-right",1]) self.accept("arrow_up",self.setKey, ["forward",1]) self.accept("arrow_left",self.setKey, ["left",1]) self.accept("arrow_down",self.setKey, ["back",1]) self.accept("arrow_right",self.setKey, ["right",1]) self.accept("a-up", self.setKey, ["cam-left",0]) self.accept("s-up", self.setKey, ["cam-right",0]) self.accept("arrow_up-up",self.setKey, ["forward",0]) self.accept("arrow_left-up",self.setKey, ["left",0]) self.accept("arrow_right-up",self.setKey, ["right",0]) self.accept("arrow_down-up",self.setKey, ["back",0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.car.getX(),self.car.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # AI self.AIworld = AIWorld(render) # AI Car 1 self.AIchar1 = AICharacter("car1",self.car1, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar1) self.AIbehaviors1 = self.AIchar1.getAiBehaviors() self.AIbehaviors1.pursue(self.car) # AI Car 2 self.AIchar2 = AICharacter("car2",self.car2, 180, 0.1, 1) self.AIworld.addAiChar(self.AIchar2) self.AIbehaviors2 = self.AIchar2.getAiBehaviors() self.AIbehaviors2.pursue(self.car4) # AI Car 3 self.AIchar3 = AICharacter("car3",self.car3, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar3) self.AIbehaviors3 = self.AIchar3.getAiBehaviors() self.AIbehaviors3.pursue(self.car) # AI Car 4 self.AIchar4 = AICharacter("car4",self.car4, 200, 0.5, 2) self.AIworld.addAiChar(self.AIchar4) self.AIbehaviors4 = self.AIchar4.getAiBehaviors() self.AIbehaviors4.pursue(self.car3) # Obstacle avoidance self.AIbehaviors1.obstacleAvoidance(1.0) self.AIworld.addObstacle(self.car2) self.AIworld.addObstacle(self.car3) self.AIworld.addObstacle(self.car4) self.AIbehaviors2.obstacleAvoidance(1.0) self.AIbehaviors3.obstacleAvoidance(1.0) self.AIbehaviors4.obstacleAvoidance(1.0) #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") self.cTrav = CollisionTraverser() #self.cTrav.showCollisions(render) self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0,0,1000) self.ralphGroundRay.setDirection(0,0,-1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.carGroundColNp = self.car.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.carGroundColNp, self.ralphGroundHandler) #car1 self.car1Ray = CollisionSphere(0,0,0,4) self.car1GroundCol = CollisionNode('car1Ray') self.car1GroundCol.addSolid(self.car1Ray) self.car1GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car1GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car1GroundColNp = self.car.attachNewNode(self.car1GroundCol) self.car1GroundHandler = CollisionHandlerQueue() #self.car1GroundColNp.show() self.cTrav.addCollider(self.car1GroundColNp, self.car1GroundHandler) cnodePath = self.car1.attachNewNode(CollisionNode('cnode1')) cnodePath.node().addSolid(self.car1Ray) #cnodePath.show() #car2 self.car2Ray = CollisionSphere(0,0,0,4) self.car2GroundCol = CollisionNode('car2Ray') self.car2GroundCol.addSolid(self.car2Ray) self.car2GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car2GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car2GroundColNp = self.car.attachNewNode(self.car2GroundCol) self.car2GroundHandler = CollisionHandlerQueue() #self.car2GroundColNp.show() self.cTrav.addCollider(self.car2GroundColNp, self.car2GroundHandler) cnodePath = self.car2.attachNewNode(CollisionNode('cnode2')) cnodePath.node().addSolid(self.car2Ray) #cnodePath.show() #car3 self.car3Ray = CollisionSphere(0,0,0,4) self.car3GroundCol = CollisionNode('car3Ray') self.car3GroundCol.addSolid(self.car3Ray) self.car3GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car3GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car3GroundColNp = self.car.attachNewNode(self.car3GroundCol) self.car3GroundHandler = CollisionHandlerQueue() #self.car3GroundColNp.show() self.cTrav.addCollider(self.car3GroundColNp, self.car3GroundHandler) cnodePath = self.car3.attachNewNode(CollisionNode('cnode3')) cnodePath.node().addSolid(self.car3Ray) #cnodePath.show() #car4 self.car4Ray = CollisionSphere(0,0,0,4) self.car4GroundCol = CollisionNode('car4Ray') self.car4GroundCol.addSolid(self.car4Ray) self.car4GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car4GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car4GroundColNp = self.car.attachNewNode(self.car4GroundCol) self.car4GroundHandler = CollisionHandlerQueue() #self.car4GroundColNp.show() self.cTrav.addCollider(self.car4GroundColNp, self.car4GroundHandler) cnodePath = self.car4.attachNewNode(CollisionNode('cnode4')) cnodePath.node().addSolid(self.car4Ray) #cnodePath.show() #camera self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0,0,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
def panda1(x, r1, g1, b1, r2, g2, b2, r3, g3, b3, v1, v2, v3, u1, u2, u3): # Load medium-sized panda self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) # medium scale self.pandaActor.setColorScale(r2, g2, b2, 100) self.pandaActor.reparentTo(self.render) # Leg movement animation self.pandaActor.loop("walk") # Walking animation pandaPosInterval1 = self.pandaActor.posInterval(v2, Point3(x, -10, 5), startPos=Point3( x, 10, 5)) pandaPosInterval2 = self.pandaActor.posInterval(v2, Point3(x, 10, 5), startPos=Point3( x, -10, 5)) pandaHprInterval1 = self.pandaActor.hprInterval(u2, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval2 = self.pandaActor.hprInterval(u2, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace = Sequence(pandaPosInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name="pandaPace") self.pandaPace.loop() # Load small panda self.pandaActor2 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor2.setScale(0.0025, 0.0025, 0.0025) # small scale self.pandaActor2.setColorScale(r1, g1, b1, 100) self.pandaActor2.reparentTo(self.render) # Leg movement animation self.pandaActor2.loop("walk") # Walking animation pandaPosInterval3 = self.pandaActor2.posInterval(v1, Point3(x, -10, 0), startPos=Point3( x, 10, 7.5)) pandaPosInterval4 = self.pandaActor2.posInterval( v1, Point3(x, 10, 7.5), startPos=Point3(x, -10, 0)) pandaHprInterval3 = self.pandaActor2.hprInterval(u1, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval4 = self.pandaActor2.hprInterval(u1, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace2 = Sequence(pandaPosInterval3, pandaHprInterval3, pandaPosInterval4, pandaHprInterval4, name="pandaPace2") self.pandaPace2.loop() # Load big panda self.pandaActor3 = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor3.setScale(0.01, 0.01, 0.01) # large scale self.pandaActor3.setColorScale(r3, g3, b3, 1) self.pandaActor3.reparentTo(self.render) # Leg movement animation. self.pandaActor3.loop("walk") # Walking animation pandaPosInterval5 = self.pandaActor3.posInterval( v3, Point3(x, -10, 7.5), startPos=Point3(x, 10, 0)) pandaPosInterval6 = self.pandaActor3.posInterval(v3, Point3(x, 10, 0), startPos=Point3( x, -10, 7.5)) pandaHprInterval5 = self.pandaActor3.hprInterval(u3, Point3(180, 0, 0), startHpr=Point3( 0, 0, 0)) pandaHprInterval6 = self.pandaActor3.hprInterval(u3, Point3(0, 0, 0), startHpr=Point3( 180, 0, 0)) self.pandaPace3 = Sequence(pandaPosInterval5, pandaHprInterval5, pandaPosInterval6, pandaHprInterval6, name="pandaPace3") self.pandaPace3.loop()
class World(DirectObject): def __init__(self): self.keyMap = {"left":0, "right":0, "forward":0, "back":0, "cam-left":0, "cam-right":0} self.flag1=0 self.flag2=0 self.flag3=0 self.flag4=0 self.count=0 self.health = 100 self.points = -5 self.flagd=1 self.player_points = 0 base.win.setClearColor(Vec4(0,0,0,1)) self.mySound=base.loader.loadSfx("sounds/trial.mp3") self.mySound.play() self.title = addTitle("Bumping Cars") #Full Screen props = WindowProperties.getDefault() w=base.pipe.getDisplayWidth() h=base.pipe.getDisplayHeight() props.setSize(w,h) props.setFullscreen(True) props.setCursorHidden(True) base.win.requestProperties(props) # Load World self.environ = loader.loadModel("models/world.egg") self.environ.reparentTo(render) self.environ.setPos(0,0,0) #Load Sky self.sky = loader.loadModel("models/clouds.egg") self.sky.reparentTo(render) self.sky.setPos(60,0,-450) # Create Player Car carStartPos = self.environ.find("**/start_point").getPos() self.car = Actor("models/carnsx") self.car.reparentTo(render) self.car.setScale(0.25) #self.car.place() self.car.setPos(carStartPos) # Create Enemy Car 1 enemyCarStartPos1 = (-108,-1,-.5) self.car1 = Actor("models/enemy_cars/monstercar/carmonster") self.car1.reparentTo(render) self.car1.setScale(0.25) #self.car1.place() self.car1.setPos(enemyCarStartPos1) # Create Enemy Car 2 enemyCarStartPos2 = (-104,-26,-.02) self.car2 = Actor("models/enemy_cars/yugo/yugo") self.car2.reparentTo(render) self.car2.setScale(0.15) #self.car2.place() self.car2.setPos(enemyCarStartPos2) # Create Enemy Car 3 enemyCarStartPos3 = (-111,-26,0) self.car3 = Actor("models/enemy_cars/truck/cartruck") self.car3.reparentTo(render) self.car3.setScale(0.25) #self.car3.place() self.car3.setPos(enemyCarStartPos3) # Create Enemy Car 4 enemyCarStartPos4 = (-111,-2,-.5) self.car4 = Actor("models/enemy_cars/truck/cartruck-purple") self.car4.reparentTo(render) self.car4.setScale(0.25) #self.car4.place() self.car4.setPos(enemyCarStartPos4) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("a", self.setKey, ["cam-left",1]) self.accept("s", self.setKey, ["cam-right",1]) self.accept("arrow_up",self.setKey, ["forward",1]) self.accept("arrow_left",self.setKey, ["left",1]) self.accept("arrow_down",self.setKey, ["back",1]) self.accept("arrow_right",self.setKey, ["right",1]) self.accept("a-up", self.setKey, ["cam-left",0]) self.accept("s-up", self.setKey, ["cam-right",0]) self.accept("arrow_up-up",self.setKey, ["forward",0]) self.accept("arrow_left-up",self.setKey, ["left",0]) self.accept("arrow_right-up",self.setKey, ["right",0]) self.accept("arrow_down-up",self.setKey, ["back",0]) taskMgr.add(self.move,"moveTask") # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.car.getX(),self.car.getY()+10,2) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor(Vec4(.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(Vec3(-5, -5, -5)) directionalLight.setColor(Vec4(1, 1, 1, 1)) directionalLight.setSpecularColor(Vec4(1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight)) # AI self.AIworld = AIWorld(render) # AI Car 1 self.AIchar1 = AICharacter("car1",self.car1, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar1) self.AIbehaviors1 = self.AIchar1.getAiBehaviors() self.AIbehaviors1.pursue(self.car) # AI Car 2 self.AIchar2 = AICharacter("car2",self.car2, 180, 0.1, 1) self.AIworld.addAiChar(self.AIchar2) self.AIbehaviors2 = self.AIchar2.getAiBehaviors() self.AIbehaviors2.pursue(self.car4) # AI Car 3 self.AIchar3 = AICharacter("car3",self.car3, 70, 0.1, 3) self.AIworld.addAiChar(self.AIchar3) self.AIbehaviors3 = self.AIchar3.getAiBehaviors() self.AIbehaviors3.pursue(self.car) # AI Car 4 self.AIchar4 = AICharacter("car4",self.car4, 200, 0.5, 2) self.AIworld.addAiChar(self.AIchar4) self.AIbehaviors4 = self.AIchar4.getAiBehaviors() self.AIbehaviors4.pursue(self.car3) # Obstacle avoidance self.AIbehaviors1.obstacleAvoidance(1.0) self.AIworld.addObstacle(self.car2) self.AIworld.addObstacle(self.car3) self.AIworld.addObstacle(self.car4) self.AIbehaviors2.obstacleAvoidance(1.0) self.AIbehaviors3.obstacleAvoidance(1.0) self.AIbehaviors4.obstacleAvoidance(1.0) #AI World update taskMgr.add(self.AIUpdate,"AIUpdate") self.cTrav = CollisionTraverser() #self.cTrav.showCollisions(render) self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0,0,1000) self.ralphGroundRay.setDirection(0,0,-1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff()) self.carGroundColNp = self.car.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.carGroundColNp, self.ralphGroundHandler) #car1 self.car1Ray = CollisionSphere(0,0,0,4) self.car1GroundCol = CollisionNode('car1Ray') self.car1GroundCol.addSolid(self.car1Ray) self.car1GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car1GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car1GroundColNp = self.car.attachNewNode(self.car1GroundCol) self.car1GroundHandler = CollisionHandlerQueue() #self.car1GroundColNp.show() self.cTrav.addCollider(self.car1GroundColNp, self.car1GroundHandler) cnodePath = self.car1.attachNewNode(CollisionNode('cnode1')) cnodePath.node().addSolid(self.car1Ray) #cnodePath.show() #car2 self.car2Ray = CollisionSphere(0,0,0,4) self.car2GroundCol = CollisionNode('car2Ray') self.car2GroundCol.addSolid(self.car2Ray) self.car2GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car2GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car2GroundColNp = self.car.attachNewNode(self.car2GroundCol) self.car2GroundHandler = CollisionHandlerQueue() #self.car2GroundColNp.show() self.cTrav.addCollider(self.car2GroundColNp, self.car2GroundHandler) cnodePath = self.car2.attachNewNode(CollisionNode('cnode2')) cnodePath.node().addSolid(self.car2Ray) #cnodePath.show() #car3 self.car3Ray = CollisionSphere(0,0,0,4) self.car3GroundCol = CollisionNode('car3Ray') self.car3GroundCol.addSolid(self.car3Ray) self.car3GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car3GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car3GroundColNp = self.car.attachNewNode(self.car3GroundCol) self.car3GroundHandler = CollisionHandlerQueue() #self.car3GroundColNp.show() self.cTrav.addCollider(self.car3GroundColNp, self.car3GroundHandler) cnodePath = self.car3.attachNewNode(CollisionNode('cnode3')) cnodePath.node().addSolid(self.car3Ray) #cnodePath.show() #car4 self.car4Ray = CollisionSphere(0,0,0,4) self.car4GroundCol = CollisionNode('car4Ray') self.car4GroundCol.addSolid(self.car4Ray) self.car4GroundCol.setFromCollideMask(BitMask32.bit(0)) self.car4GroundCol.setIntoCollideMask(BitMask32.allOff()) self.car4GroundColNp = self.car.attachNewNode(self.car4GroundCol) self.car4GroundHandler = CollisionHandlerQueue() #self.car4GroundColNp.show() self.cTrav.addCollider(self.car4GroundColNp, self.car4GroundHandler) cnodePath = self.car4.attachNewNode(CollisionNode('cnode4')) cnodePath.node().addSolid(self.car4Ray) #cnodePath.show() #camera self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0,0,1000) self.camGroundRay.setDirection(0,0,-1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) def onCollision(self, entry): print("123") def displayHealth(self): healthBar['scale'] = (self.health*0.01*BAR_WIDTH,0.2,0.2) #Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value def makezero4(self,task): self.flag4=0 def makezero3(self,task): self.flag3=0 #to update the AIWorld def AIUpdate(self,task): self.AIworld.update() return task.cont def makezero1(self,task): self.flag1=0 def makezero2(self,task): self.flag2=0 def move(self, task): if (self.flagd==1): self.points = self.points + globalClock.getDt() self.player_points = int(self.points) printPointObj(self.player_points) #print int(self.points) base.camera.lookAt(self.car) if (self.keyMap["cam-left"]!=0): base.camera.setX(base.camera, -20 * globalClock.getDt()) if (self.keyMap["cam-right"]!=0): base.camera.setX(base.camera, +20 * globalClock.getDt()) # save car's initial position so that we can restore it, # in case he falls off the map or runs into something. startposcar = self.car.getPos() # If a move-key is pressed, move the car in the specified direction. if (self.keyMap["left"]!=0): self.car.setH(self.car.getH() + 100 * globalClock.getDt()) if (self.keyMap["right"]!=0): self.car.setH(self.car.getH() - 100 * globalClock.getDt()) if (self.keyMap["forward"]!=0): self.car.setY(self.car, -40 * globalClock.getDt()) if (self.keyMap["back"]!=0): self.car.setY(self.car, 40 * globalClock.getDt()) if (self.keyMap["forward"]!=0) or (self.keyMap["left"]!=0) or (self.keyMap["right"]!=0) or (self.keyMap["back"]!=0): if self.isMoving is False: self.isMoving = True else: if self.isMoving: self.car.stop() self.isMoving = False # If the camera is too far from the car, move it closer. # If the camera is too close to the car, move it farther. camvec = self.car.getPos() - base.camera.getPos() camvec.setZ(0) camdist = camvec.length() camvec.normalize() if (camdist > 10.0): base.camera.setPos(base.camera.getPos() + camvec*(camdist-10)) camdist = 10.0 if (camdist < 5.0): base.camera.setPos(base.camera.getPos() - camvec*(5-camdist)) camdist = 5.0 # Now check for collisions. self.cTrav.traverse(render) entries = [] for i in range(self.ralphGroundHandler.getNumEntries()): entry = self.ralphGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"): self.car.setZ(entries[0].getSurfacePoint(render).getZ()) else: self.car.setPos(startposcar) entries=[] for i in range(self.car1GroundHandler.getNumEntries()): entry = self.car1GroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries)>0) and (entries[0].getIntoNode().getName() == "cnode1") and (self.flag1==0): #print "car1" self.flag1=1 self.health=self.health - 10 printHealthObj(self.health) print "car1" taskMgr.doMethodLater(5,self.makezero1,"flag1") entries=[] for i in range(self.car2GroundHandler.getNumEntries()): entry = self.car2GroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries)>0) and (entries[0].getIntoNode().getName() == "cnode2") and (self.flag2==0): #print "car2" self.flag2=1 self.health=self.health - 10 printHealthObj(self.health) print "car2" taskMgr.doMethodLater(5,self.makezero2,"flag2") entries=[] for i in range(self.car3GroundHandler.getNumEntries()): entry = self.car3GroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries)>0) and (entries[0].getIntoNode().getName() == "cnode3") and (self.flag3==0): #print "car3" self.flag3=1 self.health=self.health - 10 printHealthObj(self.health) print "car3" taskMgr.doMethodLater(5,self.makezero3,"flag3") entries=[] for i in range(self.car4GroundHandler.getNumEntries()): entry = self.car4GroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries)>0) and (entries[0].getIntoNode().getName() == "cnode4") and (self.flag4==0): #print "car4" self.flag4=1 self.health=self.health - 10 printHealthObj(self.health) print "car4" taskMgr.doMethodLater(5,self.makezero4,"flag4") entries = [] for i in range(self.camGroundHandler.getNumEntries()): entry = self.camGroundHandler.getEntry(i) entries.append(entry) entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(), x.getSurfacePoint(render).getZ())) if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"): base.camera.setZ(entries[0].getSurfacePoint(render).getZ()+1.0) if (base.camera.getZ() < self.car.getZ() + 2.0): base.camera.setZ(self.car.getZ() + 2.0) if self.health <= 0: self.flagd=0 frame=DirectFrame(image=r"end.jpg",frameSize=(-3, 3, -3, 3)) textObject1 = OnscreenText(text = 'You Died!', pos = (0, 0.7), scale = 0.22) textObject2 = OnscreenText(text = 'Press ESC to Exit', pos = (0,0.9), scale=0.1) b = DirectButton(text="Exit Game",scale=0.1,command = sys.exit) textObject3 = OnscreenText(text = 'Your Score: ' + str(self.player_points), pos = (-0.2, -0.9), scale = 0.22) self.floater.setPos(self.car.getPos()) self.floater.setZ(self.car.getZ() + 2.0) base.camera.lookAt(self.floater) self.displayHealth() return task.cont
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) self.loc_text = addTextField(0.45, "[LOC]: ") self.imageObject = OnscreenImage(image='models/intro.jpg', pos=(-0, 0, 0.02)) self.imageObject.setScale(1.6, 1.2, 1.2) base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.graphicsEngine.renderFrame() base.setBackgroundColor(0, 0, 0, 0) base.setFrameRateMeter(True) _sky = Vec4(0.01, 0.01, 0.01, 0.01) _clouds = Vec4(0.01, 0.01, 0.01, 0.01) # vx, vy, vx, vy base.cam.setPos(0, -20, 4) base.cam.lookAt(0, 0, 0) self.skyNP = loader.loadModel('models/sky') self.skyNP.reparentTo(render) self.skyNP.setScale(1000, 1000, 300) self.skyNP.setPos(0, 0, 0) self.skyNP.setTexture(loader.loadTexture('models/clouds.jpg')) self.skyNP.setShader(loader.loadShader('shaders/sky.sha')) self.skyNP.setShaderInput('sky', _sky) self.skyNP.setShaderInput('clouds', _clouds) # Light alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.5, 0.5, 0.5, 1)) alightNP = render.attachNewNode(alight) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) dlight.setColor(Vec4(0.7, 0.7, 0.7, 1)) dlightNP = render.attachNewNode(dlight) render.clearLight() render.setLight(alightNP) render.setLight(dlightNP) # Input self.accept('escape', self.doExit) self.accept('r', self.doReset) self.accept('f1', self.toggleWireframe) self.accept('f2', self.toggleTexture) self.accept('f3', self.toggleDebug) self.accept('s', self.doScreenshot) self.accept('space', self.doJump) inputState.watchWithModifiers('forward', 'arrow_up') #inputState.watchWithModifiers('left', 'arrow_left') inputState.watchWithModifiers('reverse', 'arrow_down') #inputState.watchWithModifiers('right', 'arrow_right') inputState.watchWithModifiers('turnLeft', 'arrow_left') inputState.watchWithModifiers('turnRight', 'arrow_right') # Task taskMgr.add(self.update, 'updateWorld') # Physics self.worldNP = render.attachNewNode('World') # World self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug')) self.debugNP.show() self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) # self.world.setDebugNode(self.debugNP.node()) # Ground shape = BulletPlaneShape(Vec3(0, 0, 1), 0) #img = PNMImage(Filename('models/elevation2.png')) #shape = BulletHeightfieldShape(img, 1.0, ZUp) np = self.worldNP.attachNewNode(BulletRigidBodyNode('Ground')) np.node().addShape(shape) np.setPos(0, 0, -100) np.setCollideMask(BitMask32.allOn()) self.world.attachRigidBody(np.node()) # Box # Character self.crouching = False h = 2.75 w = 0.9 shape = BulletCapsuleShape(w, h - 2 * w, ZUp) self.character = BulletCharacterControllerNode(shape, 0.4, 'Player') self.characterNP = self.worldNP.attachNewNode(self.character) self.characterNP.setPos(-2, 0, 14) #self.characterNP.setPos(-4, 75, 74) self.characterNP.setCollideMask(BitMask32.allOn()) self.world.attachCharacter(self.character) base.cam.reparentTo(self.characterNP) self.pvisualNP = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pvisualNP.clearModelNodes() self.pvisualNP.setScale(0.003) self.pvisualNP.setZ(-1.2) self.pvisualNP.reparentTo(self.characterNP) self.pvisualNP.setH(180) #self.pvisualNP.loop("walk") self.accept('arrow_up', self.pandawalk) self.accept('arrow_up-up', self.pandastop) self.accept('arrow_down', self.pandawalk) self.accept('arrow_down-up', self.pandastop) ''' visualNP.reparentTo(self.characterNP) visualNP = loader.loadModel('models/pilot-model') visualNP.clearModelNodes() visualNP.setScale(0.05) visualNP.setZ(-1.1) visualNP.setH(190) visualNP.reparentTo(self.characterNP) ''' shape = BulletBoxShape(Vec3(2, 2, 0.2)) self.Elev = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.Elev.node().setMass(0) self.Elev.node().addShape(shape) self.Elev.setPos(-0.4, 90, 5) self.Elev.setScale(2) self.Elev.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.Elev.node()) visualNP = loader.loadModel('models/elevator') visualNP.clearModelNodes() visualNP.reparentTo(self.Elev) visualNP.setScale(0.5) shape = BulletBoxShape(Vec3(2, 2, 0.2)) self.Elev2 = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.Elev2.node().setMass(0) self.Elev2.node().addShape(shape) self.Elev2.setPos(0, 0, 28) self.Elev2.setScale(2) self.Elev2.setH(180) self.Elev2.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.Elev2.node()) visualNP = loader.loadModel('models/elevator') visualNP.clearModelNodes() visualNP.reparentTo(self.Elev2) visualNP.setScale(0.5) #self.makeblockwood(1,1,1,1,1,1) self.makeblock(0, 0, 0, 5, 5, 0.5) self.makeblock(0, 10, -1, 2, 20, 0.5) self.makeblock(0, 20, 0, 2, 3, 0.5) self.makeblock(0, 25, 1, 2, 3, 0.5) self.makeblock(0, 30, 2, 2, 3, 0.5) self.makeblock(0, 35, 3, 2, 3, 0.5) self.makeblock(0, 40, 4, 2, 3, 0.5) self.makeblock(0, 50, 4, 10, 20, 0.5) self.makeblockgold(-1, 50, 5, 1, 1, 1) self.makeblockcrate(0, 50, 6, 0.7, 0.7, 0.7) self.makeblockwood(1, 50, 5, 1, 1, 1) self.makeblocksilver(-2.5, 50, 5, 1, 1, 1) self.makeblockstone(2.5, 50, 5, 1, 1, 1) self.makeblock(0, 70, 4, 2, 20, 0.5) self.makeblock(0, 90, 4, 20, 20, 0.5) self.makeblock(0, 75, 20, 20, 20, 0.5) self.makeblockcrate(-1, 75, 25, 1, 1, 1) self.makeblockwood(-1, 75, 28, 1, 1, 1) self.makeblocksilver(-1, 75, 31, 1, 1, 1) self.makeblockgold(-1, 75, 34, 1, 1, 1) self.makeblockstone(-1, 75, 38, 1, 1, 1) self.makeblock(-0.53, 50, 21.58, 2, 20, 0.5) self.makeblock(0, 40, 23, 5, 5, 0.5) self.makeblock(0, 20, 23, 5, 5, 0.5) self.makeblock(0, 0, 23, 5, 5, 0.5) self.makeblock(0, 0, 26, 20, 20, 0.5) self.makeblock(0, 25, 46, 50, 50, 0.5) self.imageObject.hide() # _____HANDLER_____ def doExit(self): self.cleanup() sys.exit(1) def pandawalk(self): self.pvisualNP.loop("walk") def pandastop(self): self.pvisualNP.stop() def doReset(self): self.characterNP.setPos(-2, 0, 14) self.Elev.setPos(-0.4, 90, 5) self.Elev2.setPos(0, 0, 28) def toggleWireframe(self): base.toggleWireframe() def toggleTexture(self): base.toggleTexture() def toggleDebug(self): if self.debugNP.isHidden(): self.debugNP.show() else: self.debugNP.hide() def doScreenshot(self): base.screenshot('Bullet') def doJump(self): self.character.setMaxJumpHeight(5.0) self.character.setJumpSpeed(8.0) self.character.doJump() def doCrouch(self): self.crouching = not self.crouching sz = self.crouching and 0.6 or 1.0 self.characterNP.setScale(Vec3(1, 1, sz)) #self.character.getShape().setLocalScale(Vec3(1, 1, sz)) #self.characterNP.setScale(Vec3(1, 1, sz) * 0.3048) #self.characterNP.setPos(0, 0, -1 * sz) # ____TASK___ def processInput(self, dt): speed = Vec3(0, 0, 0) omega = 0.0 if inputState.isSet('forward'): speed.setY(20.0) if inputState.isSet('reverse'): speed.setY(-20.0) if inputState.isSet('left'): speed.setX(-10.0) if inputState.isSet('right'): speed.setX(10.0) if inputState.isSet('turnLeft'): omega = 120.0 if inputState.isSet('turnRight'): omega = -120.0 self.character.setAngularMovement(omega) self.character.setLinearMovement(speed, True) def update(self, task): dt = globalClock.getDt() # self.characterNP.setHpr(0,0,0) base.cam.setHpr(0, -5, 0) self.processInput(dt) self.world.doPhysics(dt, 4, 1. / 240.) render.setShaderInput('time', task.time) #charpos = self.characterNP.getPos() # self.Elev.setHpr(0,0,0) self.Elevtask() self.Elevtask2() #import pickle #gg = pickle.dumps(charpos) # self.title.setText(gg) self.loc_text.setText('[LOC] : %03.2f, %03.2f,%03.2f ' % \ ( self.characterNP.getX(), self.characterNP.getY(), self.characterNP.getZ() ) ) return task.cont def Elevtask(self): if not self.characterNP.node() or not self.Elev.node(): return result = self.world.contactTestPair(self.characterNP.node(), self.Elev.node()) for contact in result.getContacts(): cp = contact.getManifoldPoint() node0 = contact.getNode0() node1 = contact.getNode1() dt = globalClock.getDt() # print('HI') #force = Vec3(0, 0, 0) self.ElevZ = self.Elev.getZ() print(self.ElevZ) #force.setZ( 100.0) #force *= 30.0 #force = render.getRelativeVector(self.Elev, force) self.Elev.setZ(self.Elev.getZ() + 4 * dt) #self.characterNP.setZ(self.Elev.getZ() + 30 * dt) #self.characterNP.setH(180) def Elevtask2(self): if not self.characterNP.node() or not self.Elev2.node(): return result = self.world.contactTestPair(self.characterNP.node(), self.Elev2.node()) for contact in result.getContacts(): cp = contact.getManifoldPoint() node0 = contact.getNode0() node1 = contact.getNode1() dt = globalClock.getDt() # print('HI') #force = Vec3(0, 0, 0) self.ElevZ2 = self.Elev2.getZ() print(self.ElevZ2) #force.setZ( 100.0) #force *= 30.0 #force = render.getRelativeVector(self.Elev, force) self.Elev2.setZ(self.Elev2.getZ() + 4 * dt) #self.characterNP.setZ(self.Elev.getZ() + 30 * dt) #self.characterNP.setH(180) def cleanup(self): self.world = None self.worldNP.removeNode() def makeblock(self, x, y, z, xs, ys, zs): shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.boxNP.node().setMass(0.0) self.boxNP.node().addShape(shape) self.boxNP.setX(x) self.boxNP.setY(y) self.boxNP.setZ(z) self.boxNP.setScale(xs, ys, zs) self.boxNP.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.boxNP.node()) visualNP = loader.loadModelCopy('models/blockmetal') visualNP.clearModelNodes() visualNP.reparentTo(self.boxNP) visualNP.setScale(0.5) def makeblockwood(self, x, y, z, xs, ys, zs): shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.boxNP.node().setMass(10.2) self.boxNP.node().addShape(shape) self.boxNP.setX(x) self.boxNP.setY(y) self.boxNP.setZ(z) self.boxNP.setScale(xs, ys, zs) self.boxNP.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.boxNP.node()) visualNP = loader.loadModelCopy('models/blockwood') visualNP.clearModelNodes() visualNP.reparentTo(self.boxNP) visualNP.setScale(0.5) def makeblockgold(self, x, y, z, xs, ys, zs): shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.boxNP.node().setMass(10.2) self.boxNP.node().addShape(shape) self.boxNP.setX(x) self.boxNP.setY(y) self.boxNP.setZ(z) self.boxNP.setScale(xs, ys, zs) self.boxNP.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.boxNP.node()) visualNP = loader.loadModelCopy('models/blockgold') visualNP.clearModelNodes() visualNP.reparentTo(self.boxNP) visualNP.setScale(0.5) def makeblocksilver(self, x, y, z, xs, ys, zs): shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.boxNP.node().setMass(10.2) self.boxNP.node().addShape(shape) self.boxNP.setX(x) self.boxNP.setY(y) self.boxNP.setZ(z) self.boxNP.setScale(xs, ys, zs) self.boxNP.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.boxNP.node()) visualNP = loader.loadModelCopy('models/blocksilver') visualNP.clearModelNodes() visualNP.reparentTo(self.boxNP) visualNP.setScale(0.5) def makeblockstone(self, x, y, z, xs, ys, zs): shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.boxNP.node().setMass(10.2) self.boxNP.node().addShape(shape) self.boxNP.setX(x) self.boxNP.setY(y) self.boxNP.setZ(z) self.boxNP.setScale(xs, ys, zs) self.boxNP.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.boxNP.node()) visualNP = loader.loadModelCopy('models/blockstone') visualNP.clearModelNodes() visualNP.reparentTo(self.boxNP) visualNP.setScale(0.5) def makeblockcrate(self, x, y, z, xs, ys, zs): shape = BulletBoxShape(Vec3(0.5, 0.5, 0.5)) self.boxNP = self.worldNP.attachNewNode(BulletRigidBodyNode('Box')) self.boxNP.node().setMass(10.2) self.boxNP.node().addShape(shape) self.boxNP.setX(x) self.boxNP.setY(y) self.boxNP.setZ(z) self.boxNP.setScale(xs, ys, zs) self.boxNP.setCollideMask(BitMask32.allOn()) #self.boxNP.node().setDeactivationEnabled(False) self.world.attachRigidBody(self.boxNP.node()) visualNP = loader.loadModelCopy('models/crate') visualNP.clearModelNodes() visualNP.reparentTo(self.boxNP) visualNP.setScale(0.5)
def getModel(self): return Actor('models/panda/panda-model.egg.pz', {'walk': 'models/panda/panda-walk4.egg.pz'})