def loadFood(self, foodIndex): self.foodNum += 1 if foodIndex in self.foodModelDict: foodModel = self.foodModelDict[foodIndex] foodModel.reparentTo(self.foodNodes[foodIndex]) colNp = foodModel.find('**/FoodCol*') colNp.setTag('foodNum', str(self.foodNum)) else: foodModelScale = ToontownGlobals.BossbotFoodModelScale foodModel = loader.loadModel('phase_12/models/bossbotHQ/canoffood') foodModel.setScale(foodModelScale) foodModel.reparentTo(self.foodNodes[foodIndex]) target = CollisionTube(4, 0, 0, -4, 0, 0, 2) target.setTangible(0) colName = 'FoodCol-%d-%d' % (self.index, foodIndex) targetNode = CollisionNode(colName) targetNode.addSolid(target) targetNode.setCollideMask(ToontownGlobals.WallBitmask) targetNodePath = foodModel.attachNewNode(targetNode) targetNodePath.setScale(1.0 / foodModelScale) targetNodePath.setTag('foodIndex', str(foodIndex)) targetNodePath.setTag('beltIndex', str(self.index)) targetNodePath.setTag('foodNum', str(self.foodNum)) targetNodePath.setZ(targetNodePath.getZ() - 1.5) self.accept('enter' + colName, self.touchedFood) self.foodModelDict[foodIndex] = foodModel
def loadToonup(self, toonupIndex): self.toonupNum += 1 if toonupIndex in self.toonupModelDict: toonupModel = self.toonupModelDict[toonupIndex] toonupModel.reparentTo(self.foodNodes[toonupIndex]) colNp = toonupModel.find('**/ToonupCol*') colNp.setTag('toonupNum', str(self.toonupNum)) else: toonupModelScale = self.ToonupScales[toonupIndex] modelName = self.ToonupModels[toonupIndex] toonupModel = loader.loadModel(modelName) self.foodNodes[toonupIndex].setZ(self.beltHeight - 0.1) toonupModel.setZ(self.ToonupZOffsets[toonupIndex]) toonupModel.setScale(toonupModelScale) toonupModel.reparentTo(self.foodNodes[toonupIndex]) target = CollisionTube(4, 0, 0, -4, 0, 0, 2) target.setTangible(0) colName = 'ToonupCol-%d-%d' % (self.index, toonupIndex) targetNode = CollisionNode(colName) targetNode.addSolid(target) targetNode.setCollideMask(ToontownGlobals.WallBitmask) targetNodePath = toonupModel.attachNewNode(targetNode) targetNodePath.setScale(1.0 / toonupModelScale) targetNodePath.setTag('toonupIndex', str(toonupIndex)) targetNodePath.setTag('beltIndex', str(self.index)) targetNodePath.setTag('toonupNum', str(self.toonupNum)) targetNodePath.setZ(targetNodePath.getZ() - 1.5 / toonupModelScale) self.accept('enter' + colName, self.touchedToonup) self.toonupModelDict[toonupIndex] = toonupModel
def initGagCollision(self, name, radius): self.gagCollisionName = name collision = CollisionTube(0, 0, 0, 0, 0, 4, radius) collision.setTangible(1) self.gagCollNode = CollisionNode(self.gagCollisionName) self.gagCollNode.setIntoCollideMask(ToontownGlobals.PieBitmask) self.gagCollNode.addSolid(collision) self.gagCollNodePath = self.object.attachNewNode(self.gagCollNode)
def loadModels(self): self.playArea = loader.loadModel('phase_13/models/parties/partyTugOfWar') self.playArea.reparentTo(self.root) self.sign.reparentTo(self.playArea.find('**/TugOfWar_sign_locator')) self.dockPositions = [[], []] for i in xrange(4): self.dockPositions[0].append(Point3(-PartyGlobals.TugOfWarInitialToonPositionsXOffset - PartyGlobals.TugOfWarToonPositionXSeparation * i, 0.0, PartyGlobals.TugOfWarToonPositionZ)) for i in xrange(4): self.dockPositions[1].append(Point3(PartyGlobals.TugOfWarInitialToonPositionsXOffset + PartyGlobals.TugOfWarToonPositionXSeparation * i, 0.0, PartyGlobals.TugOfWarToonPositionZ)) self.hopOffPositions = [[], []] for i in xrange(1, 5): self.hopOffPositions[PartyGlobals.TeamActivityTeams.LeftTeam].append(self.playArea.find('**/leftTeamHopOff%d_locator' % i).getPos()) self.hopOffPositions[PartyGlobals.TeamActivityTeams.RightTeam].append(self.playArea.find('**/rightTeamHopOff%d_locator' % i).getPos()) for i in xrange(1, 5): pos = self.playArea.find('**/fallenToon%d_locator' % i).getPos() self.fallenPositions.append(pos) self.joinCollision = [] self.joinCollisionNodePaths = [] for i in xrange(len(PartyGlobals.TeamActivityTeams)): collShape = CollisionTube(PartyGlobals.TugOfWarJoinCollisionEndPoints[0], PartyGlobals.TugOfWarJoinCollisionEndPoints[1], PartyGlobals.TugOfWarJoinCollisionRadius) collShape.setTangible(True) self.joinCollision.append(CollisionNode('TugOfWarJoinCollision%d' % i)) self.joinCollision[i].addSolid(collShape) tubeNp = self.playArea.attachNewNode(self.joinCollision[i]) tubeNp.node().setCollideMask(ToontownGlobals.WallBitmask) self.joinCollisionNodePaths.append(tubeNp) self.joinCollisionNodePaths[i].setPos(PartyGlobals.TugOfWarJoinCollisionPositions[i]) self.__enableCollisions() ropeModel = loader.loadModel('phase_4/models/minigames/tug_of_war_rope') self.ropeTexture = ropeModel.findTexture('*') ropeModel.removeNode() for i in xrange(PartyGlobals.TugOfWarMaximumPlayersPerTeam * 2 - 1): rope = Rope(self.uniqueName('TugRope%d' % i)) if rope.showRope: rope.ropeNode.setRenderMode(RopeNode.RMBillboard) rope.ropeNode.setThickness(0.2) rope.setTexture(self.ropeTexture) rope.ropeNode.setUvMode(RopeNode.UVDistance) rope.ropeNode.setUvDirection(1) rope.setTransparency(1) rope.setColor(0.89, 0.89, 0.6, 1.0) rope.reparentTo(self.root) rope.stash() self.tugRopes.append(rope) self.splash = Splash.Splash(self.root) self.splash.setScale(2.0, 4.0, 1.0) pos = self.fallenPositions[0] self.splash.setPos(pos[0], pos[1], PartyGlobals.TugOfWarSplashZOffset) self.splash.hide()
def loadCollision(self): collTube = CollisionTube(0.0, 0.0, 0.0, 0.0, 0.0, 6.0, 5.4) collTube.setTangible(True) self.trampolineCollision = CollisionNode(self.uniqueName('TrampolineCollision')) self.trampolineCollision.addSolid(collTube) self.trampolineCollision.setCollideMask(OTPGlobals.CameraBitmask | OTPGlobals.WallBitmask) self.trampolineCollisionNP = self.tramp.attachNewNode(self.trampolineCollision) collSphere = CollisionSphere(0.0, 0.0, 0.0, 7.0) collSphere.setTangible(False) self.trampolineTrigger = CollisionNode(self.uniqueName('TrampolineTrigger')) self.trampolineTrigger.addSolid(collSphere) self.trampolineTrigger.setIntoCollideMask(OTPGlobals.WallBitmask) self.trampolineTriggerNP = self.tramp.attachNewNode(self.trampolineTrigger) self.accept('enter%s' % self.uniqueName('TrampolineTrigger'), self.onTrampolineTrigger)
def __init__(self, game, id, x, y): NodePath.__init__(self, 'dropNode%s' % id) self.game = game self.id = id self.reparentTo(hidden) self.setPos(x, y, 0) shadow = loader.loadModel('phase_3/models/props/square_drop_shadow') shadow.setZ(0.2) shadow.setBin('ground', 10) shadow.setColor(1, 1, 1, 1) shadow.reparentTo(self) self.shadow = shadow drop = CogdoUtil.loadMazeModel('cabinetSmFalling') roll = random.randint(-15, 15) drop.setHpr(0, 0, roll) drop.setZ(Globals.DropHeight) self.collTube = CollisionTube(0, 0, 0, 0, 0, 4, Globals.DropCollisionRadius) self.collTube.setTangible(0) name = Globals.DropCollisionName self.collNode = CollisionNode(name) self.collNode.addSolid(self.collTube) self.collNodePath = drop.attachNewNode(self.collNode) self.collNodePath.hide() self.collNodePath.setTag('isFalling', str('True')) drop.reparentTo(self) self.drop = drop self._dropSfx = base.cogdoGameAudioMgr.createSfxIval('drop', volume=0.6)
def initCollisions(self): self.collSphere = CollisionSphere(0, 0, 0, 1.25) self.collSphere.setTangible(1) name = 'CogThiefSphere-%d' % self.cogIndex self.collSphereName = self.uniqueName(name) self.collNode = CollisionNode(self.collSphereName) self.collNode.setIntoCollideMask(CTGG.BarrelBitmask | ToontownGlobals.WallBitmask) self.collNode.addSolid(self.collSphere) self.collNodePath = self.suit.attachNewNode(self.collNode) self.accept('enter' + self.collSphereName, self.handleEnterSphere) self.pieCollSphere = CollisionTube(0, 0, 0, 0, 0, 4, self.CollisionRadius) self.pieCollSphere.setTangible(1) name = 'CogThiefPieSphere-%d' % self.cogIndex self.pieCollSphereName = self.uniqueName(name) self.pieCollNode = CollisionNode(self.pieCollSphereName) self.pieCollNode.setIntoCollideMask(ToontownGlobals.PieBitmask) self.pieCollNode.addSolid(self.pieCollSphere) self.pieCollNodePath = self.suit.attachNewNode(self.pieCollNode)
def __init__(self): ShowBase.__init__(self) self.player = Player() self.tempEnemy = WalkingEnemy(Vec3(5, 0, 0)) properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) #loader.loadModel("Models/Misc/environment") self.environment = loader.loadModel("mirroredwalltest.x") self.environment.reparentTo(render) self.environment.getChild(0).setPos(0, 50, -4) self.environment.getChild(0).setH(90) self.environment.getChild(0).setP(0) base.disableMouse() self.camera.setPos(0, 0, 50) # Tilt the camera down by setting its pitch. self.camera.setP(-45) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) # In the body of your code mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) # Turn it around by 45 degrees, and tilt it down by 45 degrees self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) render.setShaderAuto() # walls wallSolid = CollisionTube(-10.0, 32, -2, 10, 32, -2, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wall.show() wallSolid = CollisionTube(-10.0, 51, -2, 10, 51, -2, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wall.show() wallSolid = CollisionTube(-8.0, 30, -2, -8, 55, -2, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wall.show() wallSolid = CollisionTube(8.0, 30, -2, 8, 55, -2, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wall.show() # towers wallSolid = CollisionTube(-1, 37, -4, -1, 37, 3, 1) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wall.show() wallSolid = CollisionTube(-4.5, 48, -4, -4.5, 48, 3, 1) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wall.show()
class CogThief(DirectObject): notify = directNotify.newCategory('CogThief') DefaultSpeedWalkAnim = 4.0 CollisionRadius = 1.25 MaxFriendsVisible = 4 Infinity = 100000.0 SeparationDistance = 6.0 MinUrgency = 0.5 MaxUrgency = 0.75 def __init__(self, cogIndex, suitType, game, cogSpeed): self.cogIndex = cogIndex self.suitType = suitType self.game = game self.cogSpeed = cogSpeed suit = Suit.Suit() d = SuitDNA.SuitDNA() d.newSuit(suitType) suit.setDNA(d) suit.pose('walk', 0) self.suit = suit self.goal = CTGG.NoGoal self.goalId = CTGG.InvalidGoalId self.lastLocalTimeStampFromAI = 0 self.lastPosFromAI = Point3(0, 0, 0) self.lastThinkTime = 0 self.doneAdjust = False self.barrel = CTGG.NoBarrelCarried self.signalledAtReturnPos = False self.defaultPlayRate = 1.0 self.netTimeSentToStartByHit = 0 self.velocity = Vec3(0, 0, 0) self.oldVelocity = Vec3(0, 0, 0) self.acceleration = Vec3(0, 0, 0) self.bodyLength = self.CollisionRadius * 2 self.cruiseDistance = 2 * self.bodyLength self.maxVelocity = self.cogSpeed self.maxAcceleration = 5.0 self.perceptionRange = 6 self.notify.debug('cogSpeed=%s' % self.cogSpeed) self.kaboomSound = loader.loadSfx('phase_4/audio/sfx/MG_cannon_fire_alt.ogg') self.kaboom = loader.loadModel('phase_4/models/minigames/ice_game_kaboom') self.kaboom.setScale(2.0) self.kaboom.setBillboardPointEye() self.kaboom.hide() self.kaboomTrack = None splatName = 'splat-creampie' self.splat = globalPropPool.getProp(splatName) self.splat.setBillboardPointEye() self.splatType = globalPropPool.getPropType(splatName) self.pieHitSound = globalBattleSoundCache.getSound('AA_wholepie_only.ogg') return def destroy(self): self.ignoreAll() self.suit.delete() self.game = None return def uniqueName(self, baseStr): return baseStr + '-' + str(self.game.doId) def handleEnterSphere(self, collEntry): intoNp = collEntry.getIntoNodePath() self.notify.debug('handleEnterSphere suit %d hit %s' % (self.cogIndex, intoNp)) if self.game: self.game.handleEnterSphere(collEntry) def gameStart(self, gameStartTime): self.gameStartTime = gameStartTime self.initCollisions() self.startWalkAnim() def gameEnd(self): self.moveIval.pause() del self.moveIval self.shutdownCollisions() self.suit.loop('neutral') def initCollisions(self): self.collSphere = CollisionSphere(0, 0, 0, 1.25) self.collSphere.setTangible(1) name = 'CogThiefSphere-%d' % self.cogIndex self.collSphereName = self.uniqueName(name) self.collNode = CollisionNode(self.collSphereName) self.collNode.setIntoCollideMask(CTGG.BarrelBitmask | ToontownGlobals.WallBitmask) self.collNode.addSolid(self.collSphere) self.collNodePath = self.suit.attachNewNode(self.collNode) self.accept('enter' + self.collSphereName, self.handleEnterSphere) self.pieCollSphere = CollisionTube(0, 0, 0, 0, 0, 4, self.CollisionRadius) self.pieCollSphere.setTangible(1) name = 'CogThiefPieSphere-%d' % self.cogIndex self.pieCollSphereName = self.uniqueName(name) self.pieCollNode = CollisionNode(self.pieCollSphereName) self.pieCollNode.setIntoCollideMask(ToontownGlobals.PieBitmask) self.pieCollNode.addSolid(self.pieCollSphere) self.pieCollNodePath = self.suit.attachNewNode(self.pieCollNode) def shutdownCollisions(self): self.ignore(self.uniqueName('enter' + self.collSphereName)) del self.collSphere self.collNodePath.removeNode() del self.collNodePath del self.collNode def updateGoal(self, timestamp, inResponseClientStamp, goalType, goalId, pos): self.notify.debug('self.netTimeSentToStartByHit =%s' % self.netTimeSentToStartByHit) if not self.game: self.notify.debug('updateGoal self.game is None, just returning') return if not self.suit: self.notify.debug('updateGoal self.suit is None, just returning') return if self.goal == CTGG.NoGoal: self.startWalkAnim() if goalType == CTGG.NoGoal: self.notify.debug('updateGoal setting position to %s' % pos) self.suit.setPos(pos) self.lastThinkTime = 0 self.velocity = Vec3(0, 0, 0) self.oldVelocity = Vec3(0, 0, 0) self.acceleration = Vec3(0, 0, 0) if goalType == CTGG.RunAwayGoal: pass if inResponseClientStamp < self.netTimeSentToStartByHit and self.goal == CTGG.NoGoal and goalType == CTGG.RunAwayGoal: self.notify.warning('ignoring newGoal %s as cog %d was recently hit responsetime=%s hitTime=%s' % (CTGG.GoalStr[goalType], self.cogIndex, inResponseClientStamp, self.netTimeSentToStartByHit)) else: self.lastLocalTimeStampFromAI = globalClockDelta.networkToLocalTime(timestamp, bits=32) self.goal = goalType self.goalId = goalId self.lastPosFromAI = pos self.doneAdjust = False self.signalledAtReturnPos = False def startWalkAnim(self): if self.suit: self.suit.loop('walk') speed = self.cogSpeed self.defaultPlayRate = float(self.cogSpeed / self.DefaultSpeedWalkAnim) self.suit.setPlayRate(self.defaultPlayRate, 'walk') def think(self): if self.goal == CTGG.ToonGoal: self.thinkAboutCatchingToon() elif self.goal == CTGG.BarrelGoal: self.thinkAboutGettingBarrel() elif self.goal == CTGG.RunAwayGoal: self.thinkAboutRunAway() def thinkAboutCatchingToon(self): if not self.game: return av = self.game.getAvatar(self.goalId) if av: if not self.lastThinkTime: self.lastThinkTime = globalClock.getFrameTime() diffTime = globalClock.getFrameTime() - self.lastThinkTime avPos = av.getPos() myPos = self.suit.getPos() if not self.doneAdjust: myPos = self.lastPosFromAI self.notify.debug('thinkAboutCatchingToon not doneAdjust setting pos %s' % myPos) self.doneAdjust = True self.suit.setPos(myPos) if self.game.isToonPlayingHitTrack(self.goalId): self.suit.headsUp(av) self.velocity = Vec3(0, 0, 0) self.oldVelocity = Vec3(0, 0, 0) self.acceleration = Vec3(0, 0, 0) else: self.commonMove() newPos = self.suit.getPos() self.adjustPlayRate(newPos, myPos, diffTime) self.lastThinkTime = globalClock.getFrameTime() def convertNetworkStampToGameTime(self, timestamp): localStamp = globalClockDelta.networkToLocalTime(timestamp, bits=32) gameTime = self.game.local2GameTime(localStamp) return gameTime def respondToToonHit(self, timestamp): localStamp = globalClockDelta.networkToLocalTime(timestamp, bits=32) if self.netTimeSentToStartByHit < timestamp: self.clearGoal() self.showKaboom() startPos = CTGG.CogStartingPositions[self.cogIndex] oldPos = self.suit.getPos() self.suit.setPos(startPos) if self.netTimeSentToStartByHit < timestamp: self.netTimeSentToStartByHit = timestamp else: self.notify.debug('localStamp = %s, lastLocalTimeStampFromAI=%s, ignoring respondToToonHit' % (localStamp, self.lastLocalTimeStampFromAI)) self.notify.debug('respondToToonHit self.netTimeSentToStartByHit = %s' % self.netTimeSentToStartByHit) def clearGoal(self): self.goal = CTGG.NoGoal self.goalId = CTGG.InvalidGoalId def thinkAboutGettingBarrel(self): if not self.game: return if not hasattr(self.game, 'barrels'): return if self.goalId not in xrange(len(self.game.barrels)): return if not self.lastThinkTime: self.lastThinkTime = globalClock.getFrameTime() diffTime = globalClock.getFrameTime() - self.lastThinkTime barrel = self.game.barrels[self.goalId] barrelPos = barrel.getPos() myPos = self.suit.getPos() if not self.doneAdjust: myPos = self.lastPosFromAI self.notify.debug('thinkAboutGettingBarrel not doneAdjust setting position to %s' % myPos) self.suit.setPos(myPos) self.doneAdjust = True displacement = barrelPos - myPos distanceToToon = displacement.length() self.suit.headsUp(barrel) lengthTravelled = diffTime * self.cogSpeed if lengthTravelled > distanceToToon: lengthTravelled = distanceToToon displacement.normalize() dirVector = displacement dirVector *= lengthTravelled newPos = myPos + dirVector newPos.setZ(0) self.suit.setPos(newPos) self.adjustPlayRate(newPos, myPos, diffTime) self.lastThinkTime = globalClock.getFrameTime() def stopWalking(self, timestamp): localStamp = globalClockDelta.networkToLocalTime(timestamp, bits=32) if localStamp > self.lastLocalTimeStampFromAI: self.suit.loop('neutral') self.clearGoal() def thinkAboutRunAway(self): if not self.game: return if not self.lastThinkTime: self.lastThinkTime = globalClock.getFrameTime() diffTime = globalClock.getFrameTime() - self.lastThinkTime returnPos = CTGG.CogReturnPositions[self.goalId] myPos = self.suit.getPos() if not self.doneAdjust: myPos = self.lastPosFromAI self.suit.setPos(myPos) self.doneAdjust = True displacement = returnPos - myPos distanceToToon = displacement.length() tempNp = render.attachNewNode('tempRet') tempNp.setPos(returnPos) self.suit.headsUp(tempNp) tempNp.removeNode() lengthTravelled = diffTime * self.cogSpeed if lengthTravelled > distanceToToon: lengthTravelled = distanceToToon displacement.normalize() dirVector = displacement dirVector *= lengthTravelled newPos = myPos + dirVector newPos.setZ(0) self.suit.setPos(newPos) self.adjustPlayRate(newPos, myPos, diffTime) if (self.suit.getPos() - returnPos).length() < 0.0001: if not self.signalledAtReturnPos and self.barrel >= 0: self.game.sendCogAtReturnPos(self.cogIndex, self.barrel) self.signalledAtReturnPos = True self.lastThinkTime = globalClock.getFrameTime() def makeCogCarryBarrel(self, timestamp, inResponseClientStamp, barrelModel, barrelIndex, cogPos): if not self.game: return localTimeStamp = globalClockDelta.networkToLocalTime(timestamp, bits=32) self.lastLocalTimeStampFromAI = localTimeStamp inResponseGameTime = self.convertNetworkStampToGameTime(inResponseClientStamp) self.notify.debug('inResponseGameTime =%s timeSentToStart=%s' % (inResponseGameTime, self.netTimeSentToStartByHit)) if inResponseClientStamp < self.netTimeSentToStartByHit and self.goal == CTGG.NoGoal: self.notify.warning('ignoring makeCogCarrybarrel') else: barrelModel.setPos(0, -1.0, 1.5) barrelModel.reparentTo(self.suit) self.suit.setPos(cogPos) self.barrel = barrelIndex def makeCogDropBarrel(self, timestamp, inResponseClientStamp, barrelModel, barrelIndex, barrelPos): localTimeStamp = globalClockDelta.networkToLocalTime(timestamp, bits=32) self.lastLocalTimeStampFromAI = localTimeStamp barrelModel.reparentTo(render) barrelModel.setPos(barrelPos) self.barrel = CTGG.NoBarrelCarried def respondToPieHit(self, timestamp): localStamp = globalClockDelta.networkToLocalTime(timestamp, bits=32) if self.netTimeSentToStartByHit < timestamp: self.clearGoal() self.showSplat() startPos = CTGG.CogStartingPositions[self.cogIndex] oldPos = self.suit.getPos() self.suit.setPos(startPos) if self.netTimeSentToStartByHit < timestamp: self.netTimeSentToStartByHit = timestamp else: self.notify.debug('localStamp = %s, lastLocalTimeStampFromAI=%s, ignoring respondToPieHit' % (localStamp, self.lastLocalTimeStampFromAI)) self.notify.debug('respondToPieHit self.netTimeSentToStartByHit = %s' % self.netTimeSentToStartByHit) def cleanup(self): self.clearGoal() self.ignoreAll() self.suit.delete() if self.kaboomTrack and self.kaboomTrack.isPlaying(): self.kaboomTrack.finish() self.suit = None self.game = None return def adjustPlayRate(self, newPos, oldPos, diffTime): lengthTravelled = (newPos - oldPos).length() if diffTime: speed = lengthTravelled / diffTime else: speed = self.cogSpeed rateMult = speed / self.cogSpeed newRate = rateMult * self.defaultPlayRate self.suit.setPlayRate(newRate, 'walk') def commonMove(self): if not self.lastThinkTime: self.lastThinkTime = globalClock.getFrameTime() dt = globalClock.getFrameTime() - self.lastThinkTime self.oldpos = self.suit.getPos() pos = self.suit.getPos() pos += self.velocity * dt self.suit.setPos(pos) self.seeFriends() acc = Vec3(0, 0, 0) self.accumulate(acc, self.getTargetVector()) if self.numFlockmatesSeen > 0: keepDistanceVector = self.keepDistance() oldAcc = Vec3(acc) self.accumulate(acc, keepDistanceVector) if self.cogIndex == 0: pass if acc.length() > self.maxAcceleration: acc.normalize() acc *= self.maxAcceleration self.oldVelocity = self.velocity self.velocity += acc if self.velocity.length() > self.maxVelocity: self.velocity.normalize() self.velocity *= self.maxVelocity forwardVec = Vec3(1, 0, 0) heading = rad2Deg(math.atan2(self.velocity[1], self.velocity[0])) heading -= 90 self.suit.setH(heading) def getTargetVector(self): targetPos = Point3(0, 0, 0) if self.goal == CTGG.ToonGoal: av = self.game.getAvatar(self.goalId) if av: targetPos = av.getPos() elif self.goal == CTGG.BarrelGoal: barrel = self.game.barrels[self.goalId] targetPos = barrel.getPos() elif self.goal == CTGG.RunAwayGoal: targetPos = CTGG.CogReturnPositions[self.goalId] targetPos.setZ(0) myPos = self.suit.getPos() diff = targetPos - myPos if diff.length() > 1.0: diff.normalize() diff *= 1.0 return diff def accumulate(self, accumulator, valueToAdd): accumulator += valueToAdd return accumulator.length() def seeFriends(self): self.clearVisibleList() for cogIndex in self.game.cogInfo.keys(): if cogIndex == self.cogIndex: continue if self.sameGoal(cogIndex): dist = self.canISee(cogIndex) if dist != self.Infinity: self.addToVisibleList(cogIndex) if dist < self.distToNearestFlockmate: self.nearestFlockmate = cogIndex self.distToNearestFlockmate = dist return self.numFlockmatesSeen def clearVisibleList(self): self.visibleFriendsList = [] self.numFlockmatesSeen = 0 self.nearestFlockmate = None self.distToNearestFlockmate = self.Infinity return def addToVisibleList(self, cogIndex): if self.numFlockmatesSeen < self.MaxFriendsVisible: self.visibleFriendsList.append(cogIndex) self.numFlockmatesSeen += 1 if self.cogIndex == 0: pass def canISee(self, cogIndex): if self.cogIndex == cogIndex: return self.Infinity cogThief = self.game.getCogThief(cogIndex) distance = self.suit.getDistance(cogThief.suit) if distance < self.perceptionRange: return distance return self.Infinity def sameGoal(self, cogIndex): cogThief = self.game.getCogThief(cogIndex) result = cogThief.goalId == self.goalId and cogThief.goal == self.goal return result def keepDistance(self): ratio = self.distToNearestFlockmate / self.SeparationDistance nearestThief = self.game.getCogThief(self.nearestFlockmate) change = nearestThief.suit.getPos() - self.suit.getPos() if ratio < self.MinUrgency: ratio = self.MinUrgency if ratio > self.MaxUrgency: ratio = self.MaxUrgency if self.distToNearestFlockmate < self.SeparationDistance: change.normalize() change *= -(1 - ratio) elif self.distToNearestFlockmate > self.SeparationDistance: change.normalize() change *= ratio else: change = Vec3(0, 0, 0) return change def showKaboom(self): if self.kaboomTrack and self.kaboomTrack.isPlaying(): self.kaboomTrack.finish() self.kaboom.reparentTo(render) self.kaboom.setPos(self.suit.getPos()) self.kaboom.setZ(3) self.kaboomTrack = Parallel(SoundInterval(self.kaboomSound, volume=0.5), Sequence(Func(self.kaboom.showThrough), LerpScaleInterval(self.kaboom, duration=0.5, scale=Point3(10, 10, 10), startScale=Point3(1, 1, 1), blendType='easeOut'), Func(self.kaboom.hide))) self.kaboomTrack.start() def showSplat(self): if self.kaboomTrack and self.kaboomTrack.isPlaying(): self.kaboomTrack.finish() self.splat.reparentTo(render) self.splat.setPos(self.suit.getPos()) self.splat.setZ(3) self.kaboomTrack = Parallel(SoundInterval(self.pieHitSound, volume=1.0), Sequence(Func(self.splat.showThrough), LerpScaleInterval(self.splat, duration=0.5, scale=1.75, startScale=Point3(0.1, 0.1, 0.1), blendType='easeOut'), Func(self.splat.hide))) self.kaboomTrack.start()
def __init__(self): ShowBase.__init__(self) #loader.loadModel("models/environment") properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.disableMouse() self.environment = loader.loadModel("environment/environment") self.environment.reparentTo(render) self.tempActor = Actor("models/act_p3d_chan", {"walk": "models/a_p3d_chan_run"}) self.tempActor2 = Actor("models/cube.bam") self.tempActor.reparentTo(render) self.tempActor2.reparentTo(render) self.tempActor.setPos(0, 3, 0) self.tempActor2.setPos(0, 3, 0) self.tempActor.getChild(0).setH(180) self.tempActor.loop("walk") #self.useDrive() self.useTrackball() # Move the camera to a position high above the screen # --that is, offset it along the z-axis. self.camera.setPos(0, 0, 32) # Tilt the camera down by setting its pitch. self.camera.setP(-90) self.camera.reparentTo(self.tempActor) self.makeCamera(self.win, displayRegion=(0, 0.5, 0, 1)) self.makeCamera(self.win, displayRegion=(0.5, 1, 0, 1)) self.camList[1].reparentTo(self.tempActor) self.camList[1].setPos(-0.5, 10, 20) self.camList[2].setPos(0.5, 0, 0) self.camList[2].reparentTo(render) #self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") self.cTrav = CollisionTraverser() self.pusher = CollisionHandlerPusher() colliderNode = CollisionNode("player") colliderNode.addSolid(CollisionSphere(0, 0, 0, 0.3)) collider = self.tempActor.attachNewNode(colliderNode) collider.show() # The pusher wants a collider, and a NodePath that # should be moved by that collider's collisions. # In this case, we want our player-Actor to be moved. base.pusher.addCollider(collider, self.tempActor) # The traverser wants a collider, and a handler # that responds to that collider's collisions base.cTrav.addCollider(collider, self.pusher) self.pusher.setHorizontal(True) # Tubes are defined by their start-points, end-points, and radius. # In this first case, the tube goes from (-8, 0, 0) to (8, 0, 0), # and has a radius of 0.2. wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) # buffer = self.win.make_texture_buffer("renderBuffer", 1000, 750, to_ram=True) # data = buffer.get_texture().getRamImage() # np_buffer = np.frombuffer(data, np.float32) # print(np_buffer) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) # In the body of your code mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) # Turn it around by 45 degrees, and tilt it down by 45 degrees self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) render.setShaderAuto() self.keyMap = { "up": False, "down": False, "left": False, "right": False, "shoot": False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.updateTask = taskMgr.add(self.update, "update")
def __init__(self): ShowBase.__init__(self) #window properties properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.disableMouse() self.environ = loader.loadModel( "/c/Users/ryand/Desktop/VSCode_Workspace/Panda3D Practice/Game/Models/environment" ) self.environ.reparentTo(render) #place camera high above the ground (z axis) self.camera.setPos(0, 0, 32) #set pitch to look down (camera points straight by default) self.camera.setP(-90) #ambient light (light for entire scene) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) #use render.setLight to make the light affect the entire scene render.setLight(self.ambientLightNodePath) #directional light (shading) directLight = DirectionalLight("direct light") self.directLightNodePath = render.attachNewNode(directLight) self.directLightNodePath.setHpr(-45, -45, 0) render.setLight(self.directLightNodePath) #use pandas built in shader generator render.setShaderAuto() self.keyMap = { "up": False, "down": False, "left": False, "right": False, "shoot": False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.updateTask = taskMgr.add(self.update, "update") #panda will automatically update the travserser with this cTrav variable self.cTrav = CollisionTraverser() #we want to add and remove objects as called for, so add this self.pusher = CollisionHandlerPusher() #because its a 2d game self.pusher.setHorizontal(True) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) #instantiate a player instance and walking enemy instance self.player = Player() self.tempEnemy = WalkingEnemy(Vec3(5, 0, 0)) #starter code for button controls self.bk_text = "Test Button" self.textObject = OnscreenText(text=self.bk_text, pos=(0.95, -0.95), scale=0.07, fg=(1, 0.5, 0.5, 1), align=TextNode.ACenter, mayChange=1) self.button = DirectButton(text=("OK", "click!", "rolling over", "disabled"), scale=.1, command=self.setText)
def createUniqueToon(name, dna, hat, glasses, backpack, shoes, x=0, y=0, z=0, h=0, p=0, r=0, parent=render, anim='neutral', LOD=1000, isDisguised=False, suitType='f', isWaiter=False, coll=True, isRental=False, colorType=NametagGroup.CCNonPlayer, cogLevels=[0, 0, 0, 0, 0], cheesyEffect=ToontownGlobals.CENormal, nametagStyle=100): newToon = Toon.Toon() newToon.setName(name) newToon.setPickable(0) newToon.setPlayerType(colorType) if nametagStyle == 100: font = loader.loadFont('phase_3/models/fonts/ImpressBT.ttf') else: font = loader.loadFont(TTLocalizer.NametagFonts[nametagStyle]) newToon.nametag.setFont(font) coolDNA = ToonDNA.ToonDNA() coolDNA.newToonFromProperties(*dna) newToon.setDNAString(coolDNA.makeNetString()) newToon.applyCheesyEffect(cheesyEffect, 0) newToon.head = newToon.find('**/__Actor_head') a, b, c = hat newToon.setHat(a, b, c) a, b, c = backpack newToon.setBackpack(a, b, c) a, b, c = glasses newToon.setGlasses(a, b, c) a, b, c = shoes newToon.setShoes(a, b, c) if isDisguised: if isWaiter: becomeCog = 5 else: becomeCog = 0 newToon.cogLevels = [] for l in cogLevels: newToon.cogLevels.append(l) newToon.putOnSuit(suitType, rental=isRental, becomeCog=becomeCog) if coll: collTube = CollisionTube(0, 0, 0.5, 0, 0, 4, 2) collNode = CollisionNode('suit') collNode.addSolid(collTube) collNodePath = newToon.attachNewNode(collNode) else: newToon.useLOD(LOD) if coll: newToon.initializeBodyCollisions('toon') newToon.setPosHpr(x, y, z, h, p, r) newToon.reparentTo(parent) newToon.loop(anim) return newToon
def loadModels(self): self.playArea = loader.loadModel( 'phase_13/models/parties/partyTugOfWar') self.playArea.reparentTo(self.root) self.sign.reparentTo(self.playArea.find('**/TugOfWar_sign_locator')) self.dockPositions = [[], []] for i in xrange(4): self.dockPositions[0].append( Point3( -PartyGlobals.TugOfWarInitialToonPositionsXOffset - PartyGlobals.TugOfWarToonPositionXSeparation * i, 0.0, PartyGlobals.TugOfWarToonPositionZ)) for i in xrange(4): self.dockPositions[1].append( Point3( PartyGlobals.TugOfWarInitialToonPositionsXOffset + PartyGlobals.TugOfWarToonPositionXSeparation * i, 0.0, PartyGlobals.TugOfWarToonPositionZ)) self.hopOffPositions = [[], []] for i in xrange(1, 5): self.hopOffPositions[ PartyGlobals.TeamActivityTeams.LeftTeam].append( self.playArea.find('**/leftTeamHopOff%d_locator' % i).getPos()) self.hopOffPositions[ PartyGlobals.TeamActivityTeams.RightTeam].append( self.playArea.find('**/rightTeamHopOff%d_locator' % i).getPos()) for i in xrange(1, 5): pos = self.playArea.find('**/fallenToon%d_locator' % i).getPos() self.fallenPositions.append(pos) self.joinCollision = [] self.joinCollisionNodePaths = [] for i in xrange(len(PartyGlobals.TeamActivityTeams)): collShape = CollisionTube( PartyGlobals.TugOfWarJoinCollisionEndPoints[0], PartyGlobals.TugOfWarJoinCollisionEndPoints[1], PartyGlobals.TugOfWarJoinCollisionRadius) collShape.setTangible(True) self.joinCollision.append( CollisionNode('TugOfWarJoinCollision%d' % i)) self.joinCollision[i].addSolid(collShape) tubeNp = self.playArea.attachNewNode(self.joinCollision[i]) tubeNp.node().setCollideMask(ToontownGlobals.WallBitmask) self.joinCollisionNodePaths.append(tubeNp) self.joinCollisionNodePaths[i].setPos( PartyGlobals.TugOfWarJoinCollisionPositions[i]) self.__enableCollisions() ropeModel = loader.loadModel( 'phase_4/models/minigames/tug_of_war_rope') self.ropeTexture = ropeModel.findTexture('*') ropeModel.removeNode() for i in xrange(PartyGlobals.TugOfWarMaximumPlayersPerTeam * 2 - 1): rope = Rope(self.uniqueName('TugRope%d' % i)) if rope.showRope: rope.ropeNode.setRenderMode(RopeNode.RMBillboard) rope.ropeNode.setThickness(0.2) rope.setTexture(self.ropeTexture) rope.ropeNode.setUvMode(RopeNode.UVDistance) rope.ropeNode.setUvDirection(1) rope.setTransparency(1) rope.setColor(0.89, 0.89, 0.6, 1.0) rope.reparentTo(self.root) rope.stash() self.tugRopes.append(rope) self.splash = Splash.Splash(self.root) self.splash.setScale(2.0, 4.0, 1.0) pos = self.fallenPositions[0] self.splash.setPos(pos[0], pos[1], PartyGlobals.TugOfWarSplashZOffset) self.splash.hide()
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.tempActor = Actor("Models/PandaChan/act_p3d_chan", {"walk" : "Models/PandaChan/a_p3d_chan_run"}) self.tempActor.getChild(0).setH(180) self.tempActor.reparentTo(render) self.tempActor.loop("walk") self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.pusher = CollisionHandlerPusher() self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) colliderNode = CollisionNode("player") colliderNode.addSolid(CollisionSphere(0, 0, 0, 0.3)) collider = self.tempActor.attachNewNode(colliderNode) base.pusher.addCollider(collider, self.tempActor) base.cTrav.addCollider(collider, self.pusher) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) self.updateTask = taskMgr.add(self.update, "update")
def __init__(self): ShowBase.__init__(self) properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.disableMouse() #Load in the environment and actor self.environ = loader.loadModel("resources/PandaSampleModels-master/Environment/environment") self.environ.reparentTo(render) self.tempActor = Actor("resources/p3d_samples-master/models/act_p3d_chan", {"walk" : "resources/p3d_samples-master/models/a_p3d_chan_run"}) self.tempActor.reparentTo(render) #Set ambient light ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) #Set directional light mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) #Turn the light around by 45 degrees, and tilt it down by 45 degrees. self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) #Applying a shader that is automatically generated via the setShaderAuto method. render.setShaderAuto() #Move the camera to a position high above the screen #that is, offset it along the z-axis. self.camera.setPos(0, 0, 32) #Tilt the camera down by setting its pitch. self.camera.setP(-90) self.tempActor.getChild(0).setH(180) self.tempActor.loop("walk") #User input dictionary self.userInput = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False } #Tells panda what to do when certain keys are pressed self.accept("w", self.updateUserInput, ["up", True]) self.accept("w-up", self.updateUserInput, ["up", False]) self.accept("s", self.updateUserInput, ["down", True]) self.accept("s-up", self.updateUserInput, ["down", False]) self.accept("a", self.updateUserInput, ["left", True]) self.accept("a-up", self.updateUserInput, ["left", False]) self.accept("d", self.updateUserInput, ["right", True]) self.accept("d-up", self.updateUserInput, ["right", False]) self.accept("mouse1", self.updateUserInput, ["shoot", True]) self.accept("mouse1-up", self.updateUserInput, ["shoot", False]) #Use task-manager to run an update loop self.updateTask = taskMgr.add(self.update, "update") #A pusher prevents solid objects from intersecting other solids self.pusher = CollisionHandlerPusher() #Call the default variable cTrav to have panda update that traverser self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) colliderNode = CollisionNode("player") #Add a collision-sphere centered on (0,0,0), and with a radius of 0.3 colliderNode.addSolid(CollisionSphere(0, 0, 0, 0.3)) collider = self.tempActor.attachNewNode(colliderNode) # The pusher wants a collider, and a NodePath that # should be moved by that collider's collisions. # In this case, we want the player-Actor to be moved. base.pusher.addCollider(collider, self.tempActor) # The traverser wants a collider, and a handler # that responds to that collider's collisions base.cTrav.addCollider(collider, self.pusher) # Tubes are defined by their start-points, end-points, and radius. # In this first case, the tube goes from (-8, 0, 0) to (8, 0, 0), # and has a radius of 0.2. wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0)
def createUniqueToon(name, dna, hat, glasses, backpack, shoes, x=0, y=0, z=0, h=0, p=0, r=0, parent=render, anim='neutral', LOD=1000, isDisguised=False, suitType='f', suitDept='c', isWaiter=False, isRental=False, coll=True, colorType=NametagGroup.CCNonPlayer, cogLevels=(0, 0, 0, 0, 0), cheesyEffect=ToontownGlobals.CENormal, nametagStyle=100): newToon = Toon.Toon() newToon.setName(name) newToon.setPickable(0) newToon.setPlayerType(colorType) if nametagStyle == 100: font = loader.loadFont(TTLocalizer.InterfaceFont) else: font = loader.loadFont(TTLocalizer.NametagFonts[nametagStyle]) newToon.nametag.setFont(font) newDNA = ToonDNA.ToonDNA() newDNA.newToonFromProperties(*dna) newToon.setDNAString(newDNA.makeNetString()) newToon.applyCheesyEffect(cheesyEffect, 0) newToon.head = newToon.find('**/__Actor_head') newToon.setHat(*hat) newToon.setBackpack(*backpack) newToon.setGlasses(*glasses) newToon.setShoes(*shoes) if isDisguised: if isWaiter: cogType = 4 else: cogType = 0 newToon.cogLevels = [] for l in cogLevels: newToon.cogLevels.append(l) if cogType in ToontownGlobals.PutOnSuitRental or isRental: index = ToontownGlobals.CogDepts.index(suitDept) newToon.putOnSuit(index, cogType=cogType, rental=True) else: newToon.putOnSuit(suitType, cogType=cogType, rental=isRental) if coll: collTube = CollisionTube(0, 0, 0.5, 0, 0, 4, 2) collNode = CollisionNode('suit') collNode.addSolid(collTube) newToon.attachNewNode(collNode) else: newToon.useLOD(LOD) if coll: newToon.initializeBodyCollisions('toon') newToon.setPosHpr(x, y, z, h, p, r) newToon.reparentTo(parent) newToon.loop(anim) return newToon
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) # Turn it around by 45 degrees, and tilt it down by 45 degrees self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.tempActor = Actor("Models/PandaChan/act_p3d_chan", {"walk" : "Models/PandaChan/a_p3d_chan_run"}) self.tempActor.getChild(0).setH(180) self.tempActor.reparentTo(render) self.tempActor.setPos(0, 2, 0) self.tempActor.loop("walk") self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.updateTask = taskMgr.add(self.update, "update") # Panda should now automatically update that traverser! self.cTrav = CollisionTraverser() self.pusher = CollisionHandlerPusher() # prevents nominated solid objects from intersecting other solid objects. colliderNode = CollisionNode("player") # Add a collision-sphere centred on (0, 0, 0), and with a radius of 0.3 colliderNode.addSolid(CollisionSphere(0, 0, 0, 0.4)) collider = self.tempActor.attachNewNode(colliderNode) collider.show() # The pusher wants a collider, and a NodePath that # should be moved by that collider's collisions. # In this case, we want our player-Actor to be moved. base.pusher.addCollider(collider, self.tempActor) # The traverser wants a collider, and a handler # that responds to that collider's collisions base.cTrav.addCollider(collider, self.pusher) self.pusher.setHorizontal(True) # Tubes are defined by their start-points, end-points, and radius. # In this first case, the tube goes from (-8, 0, 0) to (8, 0, 0), # and has a radius of 0.2. wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0)
def makeColl(self, pos, newPos, radius): """ make a collision tube for the given stem-parameters """ tube = CollisionTube(Point3(pos), Point3(newPos), radius) self.coll.node().addSolid(tube)
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up": False, "down": False, "left": False, "right": False, "shoot": False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.pusher = CollisionHandlerPusher() self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) self.pusher.add_in_pattern("%fn-into-%in") self.accept("trapEnemy-into-wall", self.stopTrap) self.accept("trapEnemy-into-trapEnemy", self.stopTrap) self.accept("trapEnemy-into-player", self.trapHitsSomething) self.accept("trapEnemy-into-walkingEnemy", self.trapHitsSomething) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) self.updateTask = taskMgr.add(self.update, "update") self.player = Player() self.tempEnemy = WalkingEnemy(Vec3(5, 0, 0)) self.tempTrap = TrapEnemy(Vec3(-2, 7, 0))
def drawTree(self, base, drawResourcesFactories, collision, scale=1.0): age = random.random()**3.5 to = 12 * age if to < 3: return leafScaler = age**.5 leafSize = 10.0 * self.scalar * leafScaler * scale maxbend = 40 + random.random() * 20 forks = int(to / 2 - 1) lengthList = [] numCopiesList = [] radiusList = [] currR = age * 1.0 * (random.random() * 2 + 1) forkCount = 0 lengthScale = 2.0 * scale for i in xrange(forks + 1): currR *= 1 / math.sqrt(2) endR = currR * .9 * .9 if i == forks: endR = 0 forkCount = 0 if i < 2: lengthList.extend([lengthScale, lengthScale, lengthScale]) numCopiesList.extend([forkCount, 0, 0]) radiusList.extend([currR, currR * .9, endR]) else: lengthList.extend([lengthScale * 3]) numCopiesList.extend([forkCount]) radiusList.extend([endR]) forkCount = 2 + (i % 2) doLeaves = True dotCount = 1 stack = [base] LODs = list(drawResourcesFactories.keys()) angleDatas = [] for LODnum, LOD in enumerate(LODs): drawResourcesFactory = drawResourcesFactories[LOD] if LOD == self.minLOD: numVertices = 2 elif LOD == self.lowLOD: numVertices = 3 elif LOD == self.midLOD: numVertices = 4 else: numVertices = 6 #cache some info needed for placeing the vertexes angleData = [] if self.barkTexture: vNum = numVertices + 1 else: vNum = numVertices for i in xrange(vNum): #doubles the last vertex to fix UV seam angle = -2 * i * math.pi / numVertices angleData.append( (math.cos(angle), math.sin(angle), 1.0 * i / numVertices)) angleDatas.append(angleData) bottom = True if collision: cNode = CollisionNode('cnode') cnodePath = NodePath(cNode) cnodePath.reparentTo(collision) cnodePath.setCollideMask(collisionUtil.groundMask) #cnodePath.show() while stack: pos, quat, depth, previousRows, sCoord = stack.pop() length = lengthList[depth] sCoord += length / 4.0 radius = radiusList[depth] perp1 = quat.getRight() perp2 = quat.getForward() startRows = [] for LODnum, LOD in enumerate(LODs): drawResourcesFactory = drawResourcesFactories[LOD] previousRow = previousRows[LODnum] angleData = angleDatas[LODnum] vNum = len(angleData) if LOD == self.minLOD: cutoffRadius = .7 elif LOD == self.lowLOD: cutoffRadius = .5 elif LOD == self.midLOD: cutoffRadius = .1 else: cutoffRadius = -1 trunkResources = drawResourcesFactory.getDrawResources( self.trunkDataIndex[LOD]) lines = trunkResources.getGeomTristrips() vertWriter = trunkResources.getWriter("vertex") normalWriter = trunkResources.getWriter("normal") if self.barkTexture: texWriter = trunkResources.getWriter("texcoord") # else: # colorWriter = trunkResources.getWriter("color") startRow = vertWriter.getWriteRow() startRows.append(startRow) if radius > cutoffRadius: #this draws the body of the tree. This draws a ring of vertices and connects the rings with #triangles to form the body. #vertex information is written here for cos, sin, tex in angleData: adjCircle = pos + (perp1 * cos + perp2 * sin) * radius * self.scalar normal = perp1 * cos + perp2 * sin normalWriter.addData3f(normal) vertWriter.addData3f(adjCircle) if self.barkTexture is not None: texWriter.addData2f(tex, sCoord) # else: # colorWriter.addData4f(.4,.3,.3,1) #we cant draw quads directly so we use Tristrips if not bottom: for i in xrange(vNum): lines.addVertices(i + previousRow, i + startRow) if not self.barkTexture: lines.addVertices(previousRow, startRow) lines.closePrimitive() bottom = False if depth + 1 < len(lengthList): #move foward along the correct axis newPos = pos + quat.getUp() * length * self.scalar # if makeColl: # self.makeColl(pos, newPos, radiusList[depth]) numCopies = numCopiesList[depth] if numCopies: angleOffset = random.random() * 2 * math.pi for i in xrange(numCopies): newQuat = _angleRandomAxis( quat, 2 * math.pi * i / numCopies + angleOffset, maxbend) newPos2 = pos + newQuat.getUp() * length * self.scalar stack.append( (newPos2, newQuat, depth + 1, startRows, sCoord)) if collision: tube = CollisionTube(Point3(pos), Point3(newPos2), radius) cNode.addSolid(tube) else: #just make another branch connected to this one with a small variation in direction stack.append((newPos, _randomBend(quat, 20), depth + 1, startRows, sCoord)) if collision: tube = CollisionTube(Point3(pos), Point3(newPos), radius) cNode.addSolid(tube) elif doLeaves: q = Quat() q.setHpr((random.random() * 2 * math.pi, 0, 0)) quat = quat * q up = quat.getUp() down = -up # size s = leafSize dir1 = perp1 * s dir2 = perp2 * s bend = -up * (s / 4.0) v0 = pos + dir1 v1 = pos + dir2 + bend v2 = pos - dir1 v3 = pos - dir2 + bend norm1 = dir1.cross(dir2 + bend) norm1.normalize() norm2 = dir1.cross(dir2 - bend) norm2.normalize() for LOD, drawResourcesFactory in drawResourcesFactories.iteritems( ): leafResources = drawResourcesFactory.getDrawResources( self.leafDataIndex[LOD]) leafTri = leafResources.getGeomTriangles() n1 = norm1 n2 = norm2 upVec = up leafVertexWriter = leafResources.getWriter("vertex") leafNormalWriter = leafResources.getWriter("normal") if self.leafTexture: leafTexcoordWriter = leafResources.getWriter( "texcoord") else: leafColorWriter = leafResources.getWriter("color") if self.doTangentsAndBinormals: leafTangentWriter = leafResources.getWriter("tangent") leafBinormalWriter = leafResources.getWriter( "binormal") for x in range(2): leafRow = leafVertexWriter.getWriteRow() leafVertexWriter.addData3f(v0) leafVertexWriter.addData3f(v1) leafVertexWriter.addData3f(v2) leafVertexWriter.addData3f(v3) if self.leafTexture is not None: n = dotCount leafTexcoordWriter.addData2f(0, 0) leafTexcoordWriter.addData2f(0, n) leafTexcoordWriter.addData2f(n, n) leafTexcoordWriter.addData2f(n, 0) else: leafColorWriter.addData4f(.5, .4, .0, 1) leafColorWriter.addData4f(.0, .4, .0, 1) leafColorWriter.addData4f(.5, .4, .0, 1) leafColorWriter.addData4f(.0, .4, .0, 1) if x == 1: # back sides upVec = -up n1 = -norm1 n2 = -norm2 leafTri.addVertices(leafRow + 1, leafRow, leafRow + 2) leafTri.addVertices(leafRow + 2, leafRow, leafRow + 3) else: leafTri.addVertices(leafRow, leafRow + 1, leafRow + 2) leafTri.addVertices(leafRow, leafRow + 2, leafRow + 3) leafNormalWriter.addData3f(upVec) leafNormalWriter.addData3f(n1) leafNormalWriter.addData3f(upVec) leafNormalWriter.addData3f(n2) if self.doTangentsAndBinormals: # TODO : This is just a random guess. Make it actually correct tangent = norm1.cross(dir1 + dir2) tangent.normalize() binormalCenter = upVec.cross(tangent) binormal1 = n1.cross(tangent) binormal2 = n2.cross(tangent) leafTangentWriter.addData3f(tangent) leafTangentWriter.addData3f(tangent) leafTangentWriter.addData3f(tangent) leafTangentWriter.addData3f(tangent) leafBinormalWriter.addData3f(binormalCenter) leafBinormalWriter.addData3f(binormal1) leafBinormalWriter.addData3f(binormalCenter) leafBinormalWriter.addData3f(binormal2)
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.exitFunc = self.cleanup mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up": False, "down": False, "left": False, "right": False, "shoot": False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.pusher = CollisionHandlerPusher() self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) self.pusher.add_in_pattern("%fn-into-%in") self.accept("trapEnemy-into-wall", self.stopTrap) self.accept("trapEnemy-into-trapEnemy", self.stopTrap) self.accept("trapEnemy-into-player", self.trapHitsSomething) self.accept("trapEnemy-into-walkingEnemy", self.trapHitsSomething) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) self.updateTask = taskMgr.add(self.update, "update") self.player = None self.enemies = [] self.trapEnemies = [] self.deadEnemies = [] self.spawnPoints = [] numPointsPerWall = 5 for i in range(numPointsPerWall): coord = 7.0 / numPointsPerWall + 0.5 self.spawnPoints.append(Vec3(-7.0, coord, 0)) self.spawnPoints.append(Vec3(7.0, coord, 0)) self.spawnPoints.append(Vec3(coord, -7.0, 0)) self.spawnPoints.append(Vec3(coord, 7.0, 0)) self.initialSpawnInterval = 1.0 self.minimumSpawnInterval = 0.2 self.spawnInterval = self.initialSpawnInterval self.spawnTimer = self.spawnInterval self.maxEnemies = 2 self.maximumMaxEnemies = 20 self.numTrapsPerSide = 2 self.difficultyInterval = 5.0 self.difficultyTimer = self.difficultyInterval self.startGame()
class CogdoMazeDrop(NodePath, DirectObject): def __init__(self, game, id, x, y): NodePath.__init__(self, 'dropNode%s' % id) self.game = game self.id = id self.reparentTo(hidden) self.setPos(x, y, 0) shadow = loader.loadModel('phase_3/models/props/square_drop_shadow') shadow.setZ(0.2) shadow.setBin('ground', 10) shadow.setColor(1, 1, 1, 1) shadow.reparentTo(self) self.shadow = shadow drop = CogdoUtil.loadMazeModel('cabinetSmFalling') roll = random.randint(-15, 15) drop.setHpr(0, 0, roll) drop.setZ(Globals.DropHeight) self.collTube = CollisionTube(0, 0, 0, 0, 0, 4, Globals.DropCollisionRadius) self.collTube.setTangible(0) name = Globals.DropCollisionName self.collNode = CollisionNode(name) self.collNode.addSolid(self.collTube) self.collNodePath = drop.attachNewNode(self.collNode) self.collNodePath.hide() self.collNodePath.setTag('isFalling', str('True')) drop.reparentTo(self) self.drop = drop self._dropSfx = base.cogdoGameAudioMgr.createSfxIval('drop', volume=0.6) def disableCollisionDamage(self): self.collTube.setTangible(1) self.collTube.setRadius(Globals.DroppedCollisionRadius) self.collNode.setIntoCollideMask(ToontownGlobals.WallBitmask) self.collNodePath.setTag('isFalling', str('False')) def getDropIval(self): shadow = self.shadow drop = self.drop id = self.id hangTime = Globals.ShadowTime dropTime = Globals.DropTime dropHeight = Globals.DropHeight targetShadowScale = 0.5 targetShadowAlpha = 0.4 shadowScaleIval = LerpScaleInterval(shadow, dropTime, targetShadowScale, startScale=0) shadowAlphaIval = LerpColorScaleInterval(shadow, hangTime, Point4(1, 1, 1, targetShadowAlpha), startColorScale=Point4(1, 1, 1, 0)) shadowIval = Parallel(shadowScaleIval, shadowAlphaIval) startPos = Point3(0, 0, dropHeight) drop.setPos(startPos) dropIval = LerpPosInterval(drop, dropTime, Point3(0, 0, 0), startPos=startPos, blendType='easeIn') dropSoundIval = self._dropSfx dropSoundIval.node = self self.drop.setTransparency(1) def _setRandScale(t): self.drop.setScale(self, 1 - random.random() / 16, 1 - random.random() / 16, 1 - random.random() / 4) scaleChange = 0.4 + random.random() / 4 dropShakeSeq = Sequence( LerpScaleInterval(self.drop, 0.25, Vec3(1.0 + scaleChange, 1.0 + scaleChange / 2, 1.0 - scaleChange), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.25, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), Func(self.disableCollisionDamage), LerpScaleInterval(self.drop, 0.2, Vec3(1.0 + scaleChange / 8, 1.0 + scaleChange / 8, 1.0 - scaleChange / 8), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.2, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.15, Vec3(1.0 + scaleChange / 16, 1.0 + scaleChange / 16, 1.0 - scaleChange / 16), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.15, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.1, Vec3(1.0 + scaleChange / 16, 1.0 + scaleChange / 8, 1.0 - scaleChange / 16), blendType='easeInOut'), LerpColorScaleInterval(self.drop, Globals.DropFadeTime, Vec4(1.0, 1.0, 1.0, 0.0))) ival = Sequence( Func(self.reparentTo, render), Parallel(Sequence(WaitInterval(hangTime), dropIval), shadowIval), Parallel(Func(self.game.dropHit, self, id), dropSoundIval, dropShakeSeq), Func(self.game.cleanupDrop, id), name='drop%s' % id) self.ival = ival return ival def destroy(self): self.ival.pause() self.ival = None self._dropSfx.pause() self._dropSfx = None self.collTube = None self.collNode = None self.collNodePath.removeNode() self.collNodePath = None self.removeNode() return
'L': L0, 'nSegs': numSegs, 'Anoise': posNoise * R0, 'upVector': _UP_ } Params.update({'rTaper': rTaper, 'R0': R0}) Params.update(cXfactors=[(.05 * R0, 1, 0), (.05 * R0, 2, 0)], cYfactors=[(.05 * R0, 1, pi / 2), (.05 * R0, 2, pi / 2)]) np = 6 plts = range(np**2) # 6x6 array ds = 5.0 for it in range(1): tree = GeneralTree(L0, R0, numSegs, bark, "my tree") cnp = tree.attachNewNode(CollisionNode('TreeCollisionSolid')) cnp.node().addSolid(CollisionTube(0, 0, R0, 0, 0, R0 + 3, R0)) # cnp.show() tree.generate(Params, baseflair=1.45) tree.reparentTo(base.render) # DONE GENERATING. WRITE OUT UNSCALED MODEL print "writing out file" tree.setScale(1) tree.setH(180) tree.setZ(-0.1) tree.flattenStrong() tree.writeBamFile('./models/sampleTree' + str(it) + '.bam') p = random.choice(plts) tx = ds * (p / np)
def createDistributedCog(cogType, x=0, y=0, z=0, h=0, p=0, r=0, isSkelecog=False, isWaiter=False, anim='neutral', parent=render, name=None, dept=None, level=None, coll=True, isVirtual=False, colorType=NametagGroup.CCSuit): newCog = DistributedSuitBase.DistributedSuitBase(base.cr) newCog.dna = SuitDNA.SuitDNA() newCog.dna.newSuit(cogType) newCog.setDNA(newCog.dna) newCog.setPlayerType(colorType) if isWaiter: newCog.makeWaiter() if isSkelecog: newCog.makeSkeleton() if isVirtual: newCog.virtualify() newCog.setPickable(0) newCog.doId = id(newCog) if name != None: newCog.setName(name) if dept is False: nameInfo = TTLocalizer.SuitBaseNameWithoutDept % { 'name': newCog._name, 'level': level if level != None else newCog.getActualLevel() } else: if cogType == 'sj': nameInfo = 'Shadow Justice' else: if cogType == 'ph': nameInfo = TTLocalizer.SuitBaseNameWithLevel % { 'name': newCog._name, 'dept': 'Crazybot', 'level': level if level != None else newCog.getActualLevel() } else: nameInfo = TTLocalizer.SuitBaseNameWithLevel % { 'name': newCog._name, 'dept': dept if dept != None else newCog.getStyleDept(), 'level': level if level != None else newCog.getActualLevel() } newCog.setDisplayName(nameInfo) newCog.reparentTo(parent) newCog.setPosHpr(x, y, z, h, p, r) newCog.loop(anim) if coll: collTube = CollisionTube(0, 0, 0.5, 0, 0, 4, 2) collNode = CollisionNode('suit') collNode.addSolid(collTube) collNodePath = newCog.attachNewNode(collNode) return newCog
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) base.setBackgroundColor(0, 0, 0) self.accept("escape", sys.exit) # Escape quits self.disableMouse() camera.setPosHpr(0, 0, 0, 0, 0, 0) lens = PerspectiveLens() lens.setFov(90, 60) lens.setNear(0.01) lens.setFar(100000) self.cam.node().setLens(lens) self.ballSize = 0.025 self.cueLength = 0.2 # self.ballRoot = render.attachNewNode("ballRoot") # #self.ball = loader.loadModel("models/ball") # self.ball = loader.loadModel("models/ball_0_center.egg") # #self.ball = loader.loadModel("models/ball.dae") # self.ball.setScale(ballSize, ballSize, ballSize) # self.ball.reparentTo(self.ballRoot) # #print(self.ball.getBounds()) # #exit(1) # #self.ballSphere = self.ball.find("**/ball") # #print(self.ball.getScale()[0]) # cs = CollisionSphere(0, 0, 0, 1) # self.ballSphere = self.ball.attachNewNode(CollisionNode('ball')) # self.ballSphere.node().addSolid(cs) # self.ballSphere.node().setFromCollideMask(BitMask32.bit(0)) # self.ballSphere.node().setIntoCollideMask(BitMask32.bit(1)) self.sceneIndex = 0 self.planeInfo = PlaneScene(self.sceneIndex) self.planeScene = self.planeInfo.generateEggModel() self.planeScene.setTwoSided(True) self.planeScene.reparentTo(render) self.planeScene.hide() #get geometries from plane predictions planeTriangles, horizontalPlaneTriangles, self.gravityDirection = self.planeInfo.getPlaneTriangles( ) # add pool balls self.ballRoots = [] self.balls = [] self.ballSpheres = [] self.ballGroundRays = [] for ballIndex in xrange(3): ballRoot = render.attachNewNode("ballRoot_" + str(ballIndex)) ball = loader.loadModel("models/ball_" + str(ballIndex) + "_center.egg") ball.setScale(self.ballSize, self.ballSize, self.ballSize) cs = CollisionSphere(0, 0, 0, 1) ballSphere = ball.attachNewNode( CollisionNode('ball_' + str(ballIndex))) ballSphere.node().addSolid(cs) ballSphere.node().setFromCollideMask( BitMask32.bit(0) | BitMask32.bit(1) | BitMask32.bit(3) | BitMask32.bit(4)) ballSphere.node().setIntoCollideMask(BitMask32.bit(1)) ball.reparentTo(ballRoot) self.ballRoots.append(ballRoot) self.balls.append(ball) self.ballSpheres.append(ballSphere) ballGroundRay = CollisionRay() # Create the ray ballGroundRay.setOrigin(0, 0, 0) # Set its origin ballGroundRay.setDirection( self.gravityDirection[0], self.gravityDirection[1], self.gravityDirection[2]) # And its direction # Collision solids go in CollisionNode # Create and name the node ballGroundCol = CollisionNode('ball_ray_' + str(ballIndex)) ballGroundCol.addSolid(ballGroundRay) # Add the ray ballGroundCol.setFromCollideMask( BitMask32.bit(2)) # Set its bitmasks ballGroundCol.setIntoCollideMask(BitMask32.allOff()) # Attach the node to the ballRoot so that the ray is relative to the ball # (it will always be 10 feet over the ball and point down) ballGroundColNp = ballRoot.attachNewNode(ballGroundCol) self.ballGroundRays.append(ballGroundColNp) ballRoot.hide() continue # Finally, we create a CollisionTraverser. CollisionTraversers are what # do the job of walking the scene graph and calculating collisions. # For a traverser to actually do collisions, you need to call # traverser.traverse() on a part of the scene. Fortunately, ShowBase # has a task that does this for the entire scene once a frame. By # assigning it to self.cTrav, we designate that this is the one that # it should call traverse() on each frame. self.cTrav = CollisionTraverser() # Collision traversers tell collision handlers about collisions, and then # the handler decides what to do with the information. We are using a # CollisionHandlerQueue, which simply creates a list of all of the # collisions in a given pass. There are more sophisticated handlers like # one that sends events and another that tries to keep collided objects # apart, but the results are often better with a simple queue self.cHandler = CollisionHandlerQueue() # Now we add the collision nodes that can create a collision to the # traverser. The traverser will compare these to all others nodes in the # scene. There is a limit of 32 CollisionNodes per traverser # We add the collider, and the handler to use as a pair #self.cTrav.addCollider(self.ballSphere, self.cHandler) for ballSphere in self.ballSpheres: self.cTrav.addCollider(ballSphere, self.cHandler) continue for ballGroundRay in self.ballGroundRays: self.cTrav.addCollider(ballGroundRay, self.cHandler) continue #self.cTrav.addCollider(self.ballGroundColNp, self.cHandler) # Collision traversers have a built in tool to help visualize collisions. # Uncomment the next line to see it. #self.cTrav.showCollisions(render) # This section deals with lighting for the ball. Only the ball was lit # because the maze has static lighting pregenerated by the modeler ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.55, .55, .55, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection(LVector3(0, 0, -1)) directionalLight.setColor((0.375, 0.375, 0.375, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) for ballRoot in self.ballRoots: ballRoot.setLight(render.attachNewNode(ambientLight)) ballRoot.setLight(render.attachNewNode(directionalLight)) continue # This section deals with adding a specular highlight to the ball to make # it look shiny. Normally, this is specified in the .egg file. m = Material() m.setSpecular((1, 1, 1, 1)) m.setShininess(96) for ball in self.balls: ball.setMaterial(m, 1) continue # self.original = False # if self.original: # camera.setPosHpr(0, 0, 25, 0, -90, 0) # self.maze = loader.loadModel("models/maze") # self.maze.reparentTo(render) # self.walls = self.maze.find("**/wall_collide") # self.walls.node().setIntoCollideMask(BitMask32.bit(0)) # self.walls.show() # pass # create collision entities from plane predictions self.triNPs = [] for triangleIndex, triangle in enumerate(planeTriangles): #print(triangleIndex) #for triangle in triangles: #print(triangle) tri = CollisionPolygon( Point3(triangle[0][0], triangle[0][1], triangle[0][2]), Point3(triangle[1][0], triangle[1][1], triangle[1][2]), Point3(triangle[2][0], triangle[2][1], triangle[2][2])) triNP = render.attachNewNode( CollisionNode('tri_' + str(triangleIndex))) triNP.node().setIntoCollideMask(BitMask32.bit(0)) triNP.node().addSolid(tri) self.triNPs.append(triNP) #triNP.show() continue # create special collision entities for horizontal planes so that balls can fall on one horizontal plane and bounce on it for triangleIndex, triangle in enumerate(horizontalPlaneTriangles): #print(triangleIndex) #for triangle in triangles: #print(triangle) tri = CollisionPolygon( Point3(triangle[0][0], triangle[0][1], triangle[0][2]), Point3(triangle[1][0], triangle[1][1], triangle[1][2]), Point3(triangle[2][0], triangle[2][1], triangle[2][2])) triNP = render.attachNewNode( CollisionNode('ground_' + str(triangleIndex))) triNP.node().setIntoCollideMask(BitMask32.bit(2)) triNP.node().addSolid(tri) self.triNPs.append(triNP) #triNP.show() continue # tri = CollisionPolygon(Point3(-1, 4, -1), Point3(2, 4, -1), Point3(2, 4, 2)) # triNP = render.attachNewNode(CollisionNode('tri')) # triNP.node().setIntoCollideMask(BitMask32.bit(0)) # triNP.node().addSolid(tri) # triNP.show() #self.planeScene.node().setIntoCollideMask(BitMask32.bit(0)) # roomRootNP = self.planeScene # roomRootNP.flattenLight() # mesh = BulletTriangleMesh() # polygons = roomRootNP.findAllMatches("**/+GeomNode") # # p0 = Point3(-10, 4, -10) # # p1 = Point3(-10, 4, 10) # # p2 = Point3(10, 4, 10) # # p3 = Point3(10, 4, -10) # # mesh.addTriangle(p0, p1, p2) # # mesh.addTriangle(p1, p2, p3) # print(polygons) # for polygon in polygons: # geom_node = polygon.node() # #geom_node.reparentTo(self.render) # #print(geom_node.getNumGeoms()) # ts = geom_node.getTransform() # #print(ts) # for geom in geom_node.getGeoms(): # mesh.addGeom(geom, ts) # continue # continue # #self.scene = roomRootNP # shape = BulletTriangleMeshShape(mesh, dynamic=False) # #shape = BulletPlaneShape(Vec3(0, 0, 1), 1) # room = BulletRigidBodyNode('scene') # room.addShape(shape) # #room.setLinearDamping(0.0) # #room.setFriction(0.0) # print(shape) # room.setDeactivationEnabled(False) # roomNP = render.attachNewNode(room) # roomNP.setPos(0, 0, 0) # roomNP.node().setIntoCollideMask(BitMask32.bit(0)) # self.world = BulletWorld() # self.world.setGravity(Vec3(0, 0, 0)) # self.world.attachRigidBody(roomNP.node()) #room.setRestitution(1) #self.roomNP = self.scene # create the cue self.cueRoot = render.attachNewNode("cueRoot") self.cue = loader.loadModel("models/cue_center.egg") self.cue.setScale(self.cueLength * 3, self.cueLength * 3, self.cueLength) self.cue.reparentTo(self.cueRoot) self.cuePos = (10, 0, 0) self.pickerNode = CollisionNode('mouseRay') # Attach that node to the camera since the ray will need to be positioned # relative to it self.pickerNP = camera.attachNewNode(self.pickerNode) # Everything to be picked will use bit 1. This way if we were doing other # collision we could separate it self.pickerNode.setFromCollideMask(BitMask32.bit(2)) self.pickerNode.setIntoCollideMask(BitMask32.allOff()) self.pickerRay = CollisionRay() # Make our ray # Add it to the collision node self.pickerNode.addSolid(self.pickerRay) # Register the ray as something that can cause collisions self.cTrav.addCollider(self.pickerNP, self.cHandler) self.accept("mouse1", self.hit) # left-click grabs a piece # create holes self.holeLength = 0.06 holePos, holeHpr = self.planeInfo.getHolePos() self.holeRoot = render.attachNewNode("holeRoot") #self.hole = loader.loadModel("models/hole_horizontal_center.egg") self.hole = loader.loadModel("models/hole_color.egg") #self.hole = loader.loadModel("models/billiards_hole_center.egg") self.hole.setScale(self.holeLength, self.holeLength, self.holeLength) self.hole.reparentTo(self.holeRoot) self.hole.setTwoSided(True) self.holeRoot.setPos(holePos[0], holePos[1], holePos[2]) self.holeRoot.setHpr(holeHpr[0], holeHpr[1], holeHpr[2]) #tex = loader.loadTexture('models/Black_Hole.jpg') #self.hole.setTexture(tex, 1) self.holeRoot.hide() ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 0.5) self.holeTube = self.hole.attachNewNode(CollisionNode('hole')) self.holeTube.node().addSolid(ct) self.holeTube.node().setFromCollideMask(BitMask32.allOff()) self.holeTube.node().setIntoCollideMask(BitMask32.bit(4)) #self.holeTube.show() # create portals inPortalPos, inPortalHpr, outPortalPos, outPortalHpr, self.portalNormal = self.planeInfo.getPortalPos( ) self.portalLength = 0.06 self.inPortalRoot = render.attachNewNode("inPortalRoot") self.inPortal = loader.loadModel("models/portal_2_center.egg") self.inPortal.setScale(self.portalLength, self.portalLength, self.portalLength) self.inPortal.reparentTo(self.inPortalRoot) self.inPortalRoot.setPos(inPortalPos[0], inPortalPos[1], inPortalPos[2]) self.inPortalRoot.setHpr(inPortalHpr[0], inPortalHpr[1], inPortalHpr[2]) self.inPortalRoot.hide() ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1) self.inPortalTube = self.inPortal.attachNewNode( CollisionNode('portal_in')) self.inPortalTube.node().addSolid(ct) self.inPortalTube.node().setFromCollideMask(BitMask32.allOff()) self.inPortalTube.node().setIntoCollideMask(BitMask32.bit(3)) #self.inPortalTube.hide() self.outPortalRoot = render.attachNewNode("outPortalRoot") self.outPortal = loader.loadModel("models/portal_2_center.egg") self.outPortal.setScale(self.portalLength, self.portalLength, self.portalLength) self.outPortal.reparentTo(self.outPortalRoot) self.outPortalRoot.setPos(outPortalPos[0], outPortalPos[1], outPortalPos[2]) self.outPortalRoot.setHpr(outPortalHpr[0], outPortalHpr[1], outPortalHpr[2]) self.outPortalRoot.hide() ct = CollisionTube(0, 0, 0, 0, 0.001, 0, 1) self.outPortalTube = self.outPortal.attachNewNode( CollisionNode('portal_out')) self.outPortalTube.node().addSolid(ct) self.outPortalTube.node().setFromCollideMask(BitMask32.allOff()) self.outPortalTube.node().setIntoCollideMask(BitMask32.bit(3)) #self.outPortalTube.hide() #self.inPortalTube.show() #self.outPortalTube.show() #self.holeTube.show() #self.cTrav.addCollider(self.holeTube, self.cHandler) # create background image background_image = loader.loadTexture('dump/' + str(self.sceneIndex) + '_image.png') cm = CardMaker('background') cm.setHas3dUvs(True) info = np.load('dump/' + str(self.sceneIndex) + '_info.npy') #self.camera = getCameraFromInfo(self.info) depth = 10.0 sizeU = info[2] / info[0] * depth sizeV = info[6] / info[5] * depth cm.setFrame(Point3(-sizeU, depth, -sizeV), Point3(sizeU, depth, -sizeV), Point3(sizeU, depth, sizeV), Point3(-sizeU, depth, sizeV)) self.card = self.render.attachNewNode(cm.generate()) self.card.setTransparency(True) self.card.setTexture(background_image) self.card.hide() self.ballGroundMap = {} self.ballBouncing = np.full(len(self.balls), 3) self.started = False self.start() #self.hitIndex = -1 self.showing = 'parts' self.showingProgress = 0 partsScene = PartsScene(self.sceneIndex) self.planeNPs, self.planeCenters = partsScene.generateEggModel() return
def __init__(self, name='NONAME', id=None): NetEnt.__init__(self, id) self.node = NetNodePath(PandaNode('A Character')) self.node.setTag('ID', str(self.id)) if not id: self.spawn() self.node.reparentTo(render) CharacterPool.add(self) self.xVelocity = 0 self.yVelocity = 0 self.vertVelocity = None self.duck = False self.deltaT = 0 self.sprite = Sprite2d('resources/origsprite.png', rows=3, cols=8, rowPerFace=(0, 1, 2, 1)) self.sprite.createAnim('walk', (1, 0, 2, 0)) self.sprite.createAnim('kick', (5, 6, 7, 6, 5)) self.sprite.node.reparentTo(self.node) # set up character's name label self.nameNode = NodePath(TextNode('Char Name')) self.nameNode.node().setText(name) self.nameNode.node().setAlign(TextNode.ACenter) self.nameNode.node().setCardColor(0.2, 0.2, 0.2, 0.5) self.nameNode.node().setCardAsMargin(0, 0, 0, 0) self.nameNode.node().setCardDecal(True) self.nameNode.setZ(1.7) self.nameNode.setScale(0.2) self.nameNode.setBillboardAxis() self.nameNode.reparentTo(self.node) # collision self.collisionHandler = CollisionHandlerQueue() # set up 'from' collision - for detecting char hitting things self.fromCollider = self.node.attachNewNode( CollisionNode('fromCollider')) self.fromCollider.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -1)) self.fromCollider.node().setIntoCollideMask(BITMASK_EMPTY) self.fromCollider.node().setFromCollideMask(BITMASK_TERRAIN) if SHOW_COLLISIONS: self.fromCollider.show() Character.collisionTraverser.addCollider(self.fromCollider, self.collisionHandler) # set up 'into' collision - for detecting things hitting char self.intoCollider = self.node.attachNewNode( CollisionNode('intoCollider')) self.intoCollider.node().addSolid( CollisionTube(0, 0, 0.5, 0, 0, 1, 0.5)) self.intoCollider.node().setIntoCollideMask(BITMASK_CHARACTER) self.intoCollider.node().setFromCollideMask(BITMASK_EMPTY) if SHOW_COLLISIONS: self.intoCollider.show() self.oldPosition = self.node.getPos() self.collisionZ = self.node.getZ() # set up weapons self.sinceShoot = 10 # speculated client history - used for input prediction self.posHistory = []
class PartyCog(FSM): notify = directNotify.newCategory('PartyCog') HpTextGenerator = TextNode('HpTextGenerator') hpText = None height = 7 def __init__(self, parentNode, id, bounceSpeed=3, bounceHeight=1, rotateSpeed=1, heightShift=1, xMoveSpeed=0, xMoveDistance=0, bounceOffset=0): self.id = id FSM.__init__(self, 'PartyCogFSM-%d' % self.id) self.showFacingStatus = False self.xMoveSpeed = xMoveSpeed self.xMoveDistance = xMoveDistance self.heightShift = heightShift self.bounceSpeed = bounceSpeed self.bounceHeight = bounceHeight self.rotateSpeed = rotateSpeed self.parentNode = parentNode self.bounceOffset = bounceOffset self.hitInterval = None self.kaboomTrack = None self.resetRollIval = None self.netTimeSentToStartByHit = 0 self.load() self.request('Down') return def load(self): self.root = NodePath('PartyCog-%d' % self.id) self.root.reparentTo(self.parentNode) path = 'phase_13/models/parties/cogPinata_' self.actor = Actor( path + 'actor', { 'idle': path + 'idle_anim', 'down': path + 'down_anim', 'up': path + 'up_anim', 'bodyHitBack': path + 'bodyHitBack_anim', 'bodyHitFront': path + 'bodyHitFront_anim', 'headHitBack': path + 'headHitBack_anim', 'headHitFront': path + 'headHitFront_anim' }) self.actor.reparentTo(self.root) self.temp_transform = Mat4() self.head_locator = self.actor.attachNewNode('temphead') self.bodyColl = CollisionTube(0, 0, 1, 0, 0, 5.75, 0.75) self.bodyColl.setTangible(1) self.bodyCollNode = CollisionNode('PartyCog-%d-Body-Collision' % self.id) self.bodyCollNode.setCollideMask(ToontownGlobals.PieBitmask) self.bodyCollNode.addSolid(self.bodyColl) self.bodyCollNodePath = self.root.attachNewNode(self.bodyCollNode) self.headColl = CollisionTube(0, 0, 3, 0, 0, 3.0, 1.5) self.headColl.setTangible(1) self.headCollNode = CollisionNode('PartyCog-%d-Head-Collision' % self.id) self.headCollNode.setCollideMask(ToontownGlobals.PieBitmask) self.headCollNode.addSolid(self.headColl) self.headCollNodePath = self.root.attachNewNode(self.headCollNode) self.arm1Coll = CollisionSphere(1.65, 0, 3.95, 1.0) self.arm1Coll.setTangible(1) self.arm1CollNode = CollisionNode('PartyCog-%d-Arm1-Collision' % self.id) self.arm1CollNode.setCollideMask(ToontownGlobals.PieBitmask) self.arm1CollNode.addSolid(self.arm1Coll) self.arm1CollNodePath = self.root.attachNewNode(self.arm1CollNode) self.arm2Coll = CollisionSphere(-1.65, 0, 3.45, 1.0) self.arm2Coll.setTangible(1) self.arm2CollNode = CollisionNode('PartyCog-%d-Arm2-Collision' % self.id) self.arm2CollNode.setCollideMask(ToontownGlobals.PieBitmask) self.arm2CollNode.addSolid(self.arm2Coll) self.arm2CollNodePath = self.root.attachNewNode(self.arm2CollNode) splatName = 'splat-creampie' self.splat = globalPropPool.getProp(splatName) self.splat.setBillboardPointEye() self.splatType = globalPropPool.getPropType(splatName) self.pieHitSound = globalBattleSoundCache.getSound( 'AA_wholepie_only.ogg') self.upSound = globalBattleSoundCache.getSound('AV_jump_to_side.ogg') self.hole = loader.loadModel('phase_13/models/parties/cogPinataHole') self.hole.setTransparency(True) self.hole.setP(-90.0) self.hole.setScale(3) self.hole.setBin('ground', 3) self.hole.reparentTo(self.parentNode) def unload(self): self.request('Off') self.clearHitInterval() if self.hole is not None: self.hole.removeNode() self.hole = None if self.actor is not None: self.actor.cleanup() self.actor.removeNode() self.actor = None if self.root is not None: self.root.removeNode() self.root = None if self.kaboomTrack is not None and self.kaboomTrack.isPlaying(): self.kaboomTrack.finish() self.kaboomTrack = None if self.resetRollIval is not None and self.resetRollIval.isPlaying(): self.resetRollIval.finish() self.resetRollIval = None if self.hitInterval is not None and self.hitInterval.isPlaying(): self.hitInterval.finish() self.hitInterval = None del self.upSound del self.pieHitSound return def enterStatic(self): pass def exitStatic(self): pass def enterActive(self, startTime): self.root.setR(0.0) updateTask = Task.Task(self.updateTask) updateTask.startTime = startTime taskMgr.add(updateTask, 'PartyCog.update-%d' % self.id) def exitActive(self): taskMgr.remove('PartyCog.update-%d' % self.id) taskMgr.remove('PartyCog.bounceTask-%d' % self.id) self.clearHitInterval() self.resetRollIval = self.root.hprInterval(0.5, Point3( self.root.getH(), 0.0, 0.0), blendType='easeInOut') self.resetRollIval.start() self.actor.stop() def enterDown(self): if self.oldState == 'Off': downAnimControl = self.actor.getAnimControl('down') self.actor.pose('down', downAnimControl.getNumFrames() - 1) return self.clearHitInterval() startScale = self.hole.getScale() endScale = Point3(5, 5, 5) self.hitInterval = Sequence( LerpFunc(self.setAlongSpline, duration=1.0, fromData=self.currentT, toData=0.0), LerpScaleInterval(self.hole, duration=0.175, scale=endScale, startScale=startScale, blendType='easeIn'), Parallel( SoundInterval(self.upSound, volume=0.6, node=self.actor, cutOff=PartyGlobals.PARTY_COG_CUTOFF), ActorInterval(self.actor, 'down', loop=0)), LerpScaleInterval(self.hole, duration=0.175, scale=Point3(3, 3, 3), startScale=endScale, blendType='easeOut')) self.hitInterval.start() def exitDown(self): self.root.setR(0.0) self.root.setH(0.0) self.targetDistance = 0.0 self.targetFacing = 0.0 self.currentT = 0.0 self.setAlongSpline(0.0) self.clearHitInterval() startScale = self.hole.getScale() endScale = Point3(5, 5, 5) self.hitInterval = Sequence( LerpScaleInterval(self.hole, duration=0.175, scale=endScale, startScale=startScale, blendType='easeIn'), Parallel( SoundInterval(self.upSound, volume=0.6, node=self.actor, cutOff=PartyGlobals.PARTY_COG_CUTOFF), ActorInterval(self.actor, 'up', loop=0)), Func(self.actor.loop, 'idle'), LerpScaleInterval(self.hole, duration=0.175, scale=Point3(3, 3, 3), startScale=endScale, blendType='easeOut')) self.hitInterval.start() def filterDown(self, request, args): if request == 'Down': return None else: return self.defaultFilter(request, args) return None def setEndPoints(self, start, end, amplitude=1.7): self.sinAmplitude = amplitude self.sinPeriod = (end.getX() - start.getX()) / 2 self.sinDisplacement = start.getY() self.startPoint = start self.endPoint = end self.currentT = 0.0 self.targetDistance = 0.0 self.currentFacing = 0.0 self.targetFacing = 0.0 self.setAlongSpline(self.currentT) self.hole.setPos(self.root.getPos()) self.hole.setZ(0.02) def rockBackAndForth(self, task): t = task.startTime + task.time angle = math.sin(t) * 20.0 self.root.setR(angle) return task.cont def updateDistance(self, distance): self.targetDistance = clamp(distance, -1.0, 1.0) def updateTask(self, task): self.rockBackAndForth(task) if self.targetDistance > self.currentT: self.currentT += min(0.01, self.targetDistance - self.currentT) self.setAlongSpline(self.currentT) elif self.targetDistance < self.currentT: self.currentT += max(-0.01, self.targetDistance - self.currentT) self.setAlongSpline(self.currentT) if self.currentT < 0.0: self.targetFacing = -90.0 elif self.currentT > 0.0: self.targetFacing = 90.0 else: self.targetFacing = 0.0 if self.targetFacing > self.currentFacing: self.currentFacing += min(10, self.targetFacing - self.currentFacing) elif self.targetFacing < self.currentFacing: self.currentFacing += max(-10, self.targetFacing - self.currentFacing) self.root.setH(self.currentFacing) return task.cont def setAlongSpline(self, t): t = t + 1.0 dist = (self.endPoint.getX() - self.startPoint.getX()) / 2.0 x = self.startPoint.getX() + t * dist y = self.startPoint.getY() - math.sin( t * 2 * math.pi) * self.sinAmplitude self.root.setPos(x, y, 0) def startBounce(self): taskMgr.add(self.bounce, 'PartyCog.bounceTask-%d' % self.id) def bounce(self, task): self.root.setZ( math.sin((self.bounceOffset + task.time) * self.bounceSpeed) * self.bounceHeight + self.heightShift) return task.cont def setPos(self, position): self.root.setPos(position) def respondToPieHit(self, timestamp, position, hot=False, direction=1.0): if self.netTimeSentToStartByHit < timestamp: self.__showSplat(position, direction, hot) if self.netTimeSentToStartByHit < timestamp: self.netTimeSentToStartByHit = timestamp else: self.notify.debug( 'respondToPieHit self.netTimeSentToStartByHit = %s' % self.netTimeSentToStartByHit) def clearHitInterval(self): if self.hitInterval is not None and self.hitInterval.isPlaying(): self.hitInterval.clearToInitial() return def __showSplat(self, position, direction, hot=False): if self.kaboomTrack is not None and self.kaboomTrack.isPlaying(): self.kaboomTrack.finish() self.clearHitInterval() splatName = 'splat-creampie' self.splat = globalPropPool.getProp(splatName) self.splat.setBillboardPointEye() self.splat.reparentTo(render) self.splat.setPos(self.root, position) self.splat.setAlphaScale(1.0) if not direction == 1.0: self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[0]) if self.currentFacing > 0.0: facing = 'HitFront' else: facing = 'HitBack' else: self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[1]) if self.currentFacing > 0.0: facing = 'HitBack' else: facing = 'HitFront' if hot: targetscale = 0.75 part = 'head' else: targetscale = 0.5 part = 'body' def setSplatAlpha(amount): self.splat.setAlphaScale(amount) self.hitInterval = Sequence( ActorInterval(self.actor, part + facing, loop=0), Func(self.actor.loop, 'idle')) self.hitInterval.start() self.kaboomTrack = Parallel( SoundInterval(self.pieHitSound, volume=1.0, node=self.actor, cutOff=PartyGlobals.PARTY_COG_CUTOFF), Sequence( Func(self.splat.showThrough), Parallel( Sequence( LerpScaleInterval(self.splat, duration=0.175, scale=targetscale, startScale=Point3(0.1, 0.1, 0.1), blendType='easeOut'), Wait(0.175)), Sequence( Wait(0.1), LerpFunc(setSplatAlpha, duration=1.0, fromData=1.0, toData=0.0, blendType='easeOut'))), Func(self.splat.cleanup), Func(self.splat.removeNode))) self.kaboomTrack.start() return def showHitScore(self, number, scale=1): if number <= 0: return if self.hpText: self.hideHitScore() self.HpTextGenerator.setFont(ToontownGlobals.getSignFont()) if number < 0: self.HpTextGenerator.setText(str(number)) else: self.HpTextGenerator.setText('+' + str(number)) self.HpTextGenerator.clearShadow() self.HpTextGenerator.setAlign(TextNode.ACenter) r = 1 g = 1 b = 0 a = 1 self.HpTextGenerator.setTextColor(r, g, b, a) self.hpTextNode = self.HpTextGenerator.generate() self.hpText = render.attachNewNode(self.hpTextNode) self.hpText.setScale(scale) self.hpText.setBillboardPointEye() self.hpText.setBin('fixed', 100) self.hpText.setPos(self.root, 0, 0, self.height / 2) seq = Sequence( self.hpText.posInterval( 0.25, Point3(self.root.getX(render), self.root.getY(render), self.root.getZ(render) + self.height + 1.0), blendType='easeOut'), Wait(0.25), self.hpText.colorInterval(0.1, Vec4(r, g, b, 0)), Func(self.hideHitScore)) seq.start() def hideHitScore(self): if self.hpText: taskMgr.remove('PartyCogHpText' + str(self.id)) self.hpText.removeNode() self.hpText = None return def getHeadLocation(self): self.actor.getJoints(jointName='head')[0].getNetTransform( self.temp_transform) self.head_locator.setMat(self.temp_transform) return self.head_locator.getZ(self.root)
def __init__(self): ShowBase.__init__(self) self.disableMouse() properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.exitFunc = self.cleanup mainLight = DirectionalLight("main light") self.mainLightNodePath = render.attachNewNode(mainLight) self.mainLightNodePath.setHpr(45, -45, 0) render.setLight(self.mainLightNodePath) ambientLight = AmbientLight("ambient light") ambientLight.setColor(Vec4(0.2, 0.2, 0.2, 1)) self.ambientLightNodePath = render.attachNewNode(ambientLight) render.setLight(self.ambientLightNodePath) render.setShaderAuto() self.environment = loader.loadModel("Models/Misc/environment") self.environment.reparentTo(render) self.camera.setPos(0, 0, 32) self.camera.setP(-90) self.keyMap = { "up": False, "down": False, "left": False, "right": False, "shoot": False } self.accept("w", self.updateKeyMap, ["up", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.updateKeyMap, ["shoot", True]) self.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) self.pusher = CollisionHandlerPusher() self.cTrav = CollisionTraverser() self.pusher.setHorizontal(True) self.pusher.add_in_pattern("%fn-into-%in") self.accept("trapEnemy-into-wall", self.stopTrap) self.accept("trapEnemy-into-trapEnemy", self.stopTrap) self.accept("trapEnemy-into-player", self.trapHitsSomething) self.accept("trapEnemy-into-walkingEnemy", self.trapHitsSomething) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) wallSolid = CollisionTube(-8.0, 0, 0, 8.0, 0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(-8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(8.0) wallSolid = CollisionTube(0, -8.0, 0, 0, 8.0, 0, 0.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setX(-8.0) self.updateTask = taskMgr.add(self.update, "update") self.player = None self.enemies = [] self.trapEnemies = [] self.deadEnemies = [] self.spawnPoints = [] numPointsPerWall = 5 for i in range(numPointsPerWall): coord = 7.0 / numPointsPerWall + 0.5 self.spawnPoints.append(Vec3(-7.0, coord, 0)) self.spawnPoints.append(Vec3(7.0, coord, 0)) self.spawnPoints.append(Vec3(coord, -7.0, 0)) self.spawnPoints.append(Vec3(coord, 7.0, 0)) self.initialSpawnInterval = 1.0 self.minimumSpawnInterval = 0.2 self.spawnInterval = self.initialSpawnInterval self.spawnTimer = self.spawnInterval self.maxEnemies = 2 self.maximumMaxEnemies = 20 self.numTrapsPerSide = 2 self.difficultyInterval = 5.0 self.difficultyTimer = self.difficultyInterval self.enemySpawnSound = loader.loadSfx("Sounds/enemySpawn.ogg") self.gameOverScreen = DirectDialog(frameSize=(-0.7, 0.7, -0.7, 0.7), fadeScreen=0.4, relief=DGG.FLAT, frameTexture="UI/stoneFrame.png") self.gameOverScreen.hide() self.font = loader.loadFont("Fonts/Wbxkomik.ttf") buttonImages = (loader.loadTexture("UI/UIButton.png"), loader.loadTexture("UI/UIButtonPressed.png"), loader.loadTexture("UI/UIButtonHighlighted.png"), loader.loadTexture("UI/UIButtonDisabled.png")) label = DirectLabel(text="Game Over!", parent=self.gameOverScreen, scale=0.1, pos=(0, 0, 0.2), text_font=self.font, relief=None) self.finalScoreLabel = DirectLabel(text="", parent=self.gameOverScreen, scale=0.07, pos=(0, 0, 0), text_font=self.font, relief=None) btn = DirectButton(text="Restart", command=self.startGame, pos=(-0.3, 0, -0.2), parent=self.gameOverScreen, scale=0.07, text_font=self.font, clickSound=loader.loadSfx("Sounds/UIClick.ogg"), frameTexture=buttonImages, frameSize=(-4, 4, -1, 1), text_scale=0.75, relief=DGG.FLAT, text_pos=(0, -0.2)) btn.setTransparency(True) btn = DirectButton(text="Quit", command=self.quit, pos=(0.3, 0, -0.2), parent=self.gameOverScreen, scale=0.07, text_font=self.font, clickSound=loader.loadSfx("Sounds/UIClick.ogg"), frameTexture=buttonImages, frameSize=(-4, 4, -1, 1), text_scale=0.75, relief=DGG.FLAT, text_pos=(0, -0.2)) btn.setTransparency(True) self.titleMenuBackdrop = DirectFrame(frameColor=(0, 0, 0, 1), frameSize=(-1, 1, -1, 1), parent=render2d) self.titleMenu = DirectFrame(frameColor=(1, 1, 1, 0)) title = DirectLabel(text="Panda-chan", scale=0.1, pos=(0, 0, 0.9), parent=self.titleMenu, relief=None, text_font=self.font, text_fg=(1, 1, 1, 1)) title2 = DirectLabel(text="and the", scale=0.07, pos=(0, 0, 0.79), parent=self.titleMenu, text_font=self.font, frameColor=(0.5, 0.5, 0.5, 1)) title3 = DirectLabel(text="Endless Horde", scale=0.125, pos=(0, 0, 0.65), parent=self.titleMenu, relief=None, text_font=self.font, text_fg=(1, 1, 1, 1)) btn = DirectButton(text="Start Game", command=self.startGame, pos=(0, 0, 0.2), parent=self.titleMenu, scale=0.1, text_font=self.font, clickSound=loader.loadSfx("Sounds/UIClick.ogg"), frameTexture=buttonImages, frameSize=(-4, 4, -1, 1), text_scale=0.75, relief=DGG.FLAT, text_pos=(0, -0.2)) btn.setTransparency(True) btn = DirectButton(text="Quit", command=self.quit, pos=(0, 0, -0.2), parent=self.titleMenu, scale=0.1, text_font=self.font, clickSound=loader.loadSfx("Sounds/UIClick.ogg"), frameTexture=buttonImages, frameSize=(-4, 4, -1, 1), text_scale=0.75, relief=DGG.FLAT, text_pos=(0, -0.2)) btn.setTransparency(True) music = loader.loadMusic("Music/Defending-the-Princess-Haunted.ogg") music.setLoop(True) music.setVolume(0.075) music.play()
class CogdoMazeDrop(NodePath, DirectObject): def __init__(self, game, id, x, y): NodePath.__init__(self, 'dropNode%s' % id) self.game = game self.id = id self.reparentTo(hidden) self.setPos(x, y, 0) shadow = loader.loadModel('phase_3/models/props/square_drop_shadow') shadow.setZ(0.2) shadow.setBin('ground', 10) shadow.setColor(1, 1, 1, 1) shadow.reparentTo(self) self.shadow = shadow drop = CogdoUtil.loadMazeModel('cabinetSmFalling') roll = random.randint(-15, 15) drop.setHpr(0, 0, roll) drop.setZ(Globals.DropHeight) self.collTube = CollisionTube(0, 0, 0, 0, 0, 4, Globals.DropCollisionRadius) self.collTube.setTangible(0) name = Globals.DropCollisionName self.collNode = CollisionNode(name) self.collNode.addSolid(self.collTube) self.collNodePath = drop.attachNewNode(self.collNode) self.collNodePath.hide() self.collNodePath.setTag('isFalling', str('True')) drop.reparentTo(self) self.drop = drop self._dropSfx = base.cogdoGameAudioMgr.createSfxIval('drop', volume=0.6) def disableCollisionDamage(self): self.collTube.setTangible(1) self.collTube.setRadius(Globals.DroppedCollisionRadius) self.collNode.setIntoCollideMask(ToontownGlobals.WallBitmask) self.collNodePath.setTag('isFalling', str('False')) def getDropIval(self): shadow = self.shadow drop = self.drop id = self.id hangTime = Globals.ShadowTime dropTime = Globals.DropTime dropHeight = Globals.DropHeight targetShadowScale = 0.5 targetShadowAlpha = 0.4 shadowScaleIval = LerpScaleInterval(shadow, dropTime, targetShadowScale, startScale=0) shadowAlphaIval = LerpColorScaleInterval(shadow, hangTime, Point4(1, 1, 1, targetShadowAlpha), startColorScale=Point4(1, 1, 1, 0)) shadowIval = Parallel(shadowScaleIval, shadowAlphaIval) startPos = Point3(0, 0, dropHeight) drop.setPos(startPos) dropIval = LerpPosInterval(drop, dropTime, Point3(0, 0, 0), startPos=startPos, blendType='easeIn') dropSoundIval = self._dropSfx dropSoundIval.node = self self.drop.setTransparency(1) def _setRandScale(t): self.drop.setScale(self, 1 - random.random() / 16, 1 - random.random() / 16, 1 - random.random() / 4) scaleChange = 0.4 + random.random() / 4 dropShakeSeq = Sequence(LerpScaleInterval(self.drop, 0.25, Vec3(1.0 + scaleChange, 1.0 + scaleChange / 2, 1.0 - scaleChange), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.25, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), Func(self.disableCollisionDamage), LerpScaleInterval(self.drop, 0.2, Vec3(1.0 + scaleChange / 8, 1.0 + scaleChange / 8, 1.0 - scaleChange / 8), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.2, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.15, Vec3(1.0 + scaleChange / 16, 1.0 + scaleChange / 16, 1.0 - scaleChange / 16), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.15, Vec3(1.0, 1.0, 1.0), blendType='easeInOut'), LerpScaleInterval(self.drop, 0.1, Vec3(1.0 + scaleChange / 16, 1.0 + scaleChange / 8, 1.0 - scaleChange / 16), blendType='easeInOut'), LerpColorScaleInterval(self.drop, Globals.DropFadeTime, Vec4(1.0, 1.0, 1.0, 0.0))) ival = Sequence(Func(self.reparentTo, render), Parallel(Sequence(WaitInterval(hangTime), dropIval), shadowIval), Parallel(Func(self.game.dropHit, self, id), dropSoundIval, dropShakeSeq), Func(self.game.cleanupDrop, id), name='drop%s' % id) self.ival = ival return ival def destroy(self): self.ival.pause() self.ival = None self._dropSfx.pause() self._dropSfx = None self.collTube = None self.collNode = None self.collNodePath.removeNode() self.collNodePath = None self.removeNode() return
def wallColliders(self): ''' Creates and postions colliders that correspond to the walls of the game map. ''' # walls wallSolid = CollisionTube(-7.0, 39, -2, 7, 39, -2, 1.2) #wallSolid = CollisionBox(Point3(-5,64,-4), Point3(2.5, 2.5, 0.25)) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) #wall.setY(8.0) #wall.show() wallSolid = CollisionTube(-2.0, 61, -2, 7, 61, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(-7.0, 30, -2, -7, 61, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(7.0, 40, -2, 7, 61, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(-38, -1, -2, -38, 124, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(38, -1, -2, 38, 124, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(-38, 124, -2, 38, 124, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(-38, -1, -2, 38, -1, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(-38, 101, -2, 0, 101, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(1, 101, -2, 1, 114, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(22.5, 62, -2, 22.5, 93, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0) #wall.show() wallSolid = CollisionTube(8, 92.5, -2, 22.5, 92.5, -2, 1.2) wallNode = CollisionNode("wall") wallNode.addSolid(wallSolid) wall = render.attachNewNode(wallNode) wall.setY(8.0)