class GameApp(ShowBase): def __init__(self): ShowBase.__init__(self) pman.shim.init(self) #props = WindowProperties() #props.setCursorHidden(True) #props.setMouseMode(WindowProperties.M_relative) #base.win.requestProperties(props) base.disableMouse() self.mouse = [0, 0] self.setFrameRateMeter(True) self.win.setClearColor((0, 0, 0, 1)) self.cTrav = CollisionTraverser() self.cTrav.setRespectPrevTransform(True) self.delay = [0, 5] base.win.display_regions[1].dimensions = (0, 1, 0.25, 1) render.setShaderAuto() self.music = None self.shuffleSong() self.mode = "edit" self.defineKeys() self.hud = Hud(self) self.road = RoadMan(self) self.road.enableEditing() self.spawn() self.taskMgr.add(self.update) def defineKeys(self): self.keys = {} keys = ( # Key Name ("arrow_left", "left"), ("arrow_right", "right"), ("arrow_up", "forward"), ("arrow_down", "backward"), ("page_up", "up"), ("page_down", "down"), ("space", "jump"), ("tab", "mode"), ("`", "help"), ("delete", "delete"), ("s", "save"), ("l", "load"), ("n", "clear_map"), ("/", "create_map"), (".", "next_map"), (",", "prev_map"), ("c", "color"), ("+", "add"), ("-", "sub"), ("f", "fueldrain"), ("g", "gravity"), ("h", "o2drain"), ("9", "n_shape"), ("7", "p_shape"), ("6", "c_left"), ("4", "c_right"), ("8", "c_up"), ("2", "c_down"), ("c", "copy"), ("a", "analyze"), ("escape", "quit"), ) for key in keys: # 2 = first down, 1 = hold down, 0 = not down self.accept(key[0], self.setKey, [key[1], 2]) self.accept(key[0] + "-up", self.setKey, [key[1], 0]) self.keys[key[1]] = 0 self.accept('shift-q', sys.exit) # Force exit def update(self, task): self.road.skysphere.setH(self.road.skysphere.getH() + 0.1) if self.keys["quit"]: sys.exit() if self.keys["analyze"] == 2: render.analyze() render.ls() if self.mode == "game": ship = self.ship if self.keys["forward"]: ship.accelerate() elif self.keys["backward"]: ship.decelerate() if self.keys["left"]: ship.goLeft() elif self.keys["right"]: ship.goRight() else: ship.steer = 0 if self.keys["jump"]: ship.jumpUp() self.ship.update() camY = -6 + self.ship.node.getY() + (self.ship.speed * 5) base.camLens.setFov(60 + (self.ship.speed * 150)) if self.keys["mode"] == 2: self.mode = "edit" self.ship.audio["engine"].stop() self.road.enableEditing() elif self.mode == "edit": self.delay[0] += 1 t = False if self.delay[0] > self.delay[1]: road = self.road if self.keys["forward"]: road.move("f") t = True if self.keys["backward"]: road.move("b") t = True if self.keys["left"]: road.move("l") t = True if self.keys["right"]: road.move("r") t = True if self.keys["up"]: road.move("u") t = True if self.keys["down"]: road.move("d") t = True if self.keys["copy"]: road.clone() t = True if self.keys["jump"]: road.place() t = True if self.keys["delete"]: road.remove() t = True if self.keys["save"] == 2: road.saveMap() if self.keys["load"] == 2: road.loadMap() if self.keys["clear_map"] == 2: road.clearMap() if self.keys["next_map"] == 2: road.nextMap() if self.keys["prev_map"] == 2: road.prevMap() if self.keys["create_map"] == 2: road.newMap() if self.keys["n_shape"] == 2: road.shape("n") if self.keys["p_shape"] == 2: road.shape("p") if self.keys["c_up"]: road.moveCol("u") t = True if self.keys["c_down"]: road.moveCol("d") t = True if self.keys["c_left"]: road.moveCol("l") t = True if self.keys["c_right"]: road.moveCol("r") t = True if self.keys["gravity"]: if self.keys["add"]: self.road.setGravity(1) if self.keys["sub"]: self.road.setGravity(-1) t = True if self.keys["fueldrain"]: if self.keys["add"]: self.road.setFuelDrain(1) if self.keys["sub"]: self.road.setFuelDrain(-1) t = True if self.keys["o2drain"]: if self.keys["add"]: self.road.setO2Drain(1) if self.keys["sub"]: self.road.setO2Drain(-1) t = True if self.keys["mode"] == 2: self.mode = "game" self.road.disableEditing() self.ship.respawn() if self.keys["help"] == 2: self.road.toggleHelp() if t: self.delay[0] = 0 camY = -6 + self.road.select.getY() base.camLens.setFov(90) base.cam.setPos(4.001, camY, 1.7) self.updateKeys() return task.cont def setKey(self, key, pos): self.keys[key] = pos def updateKeys(self): for key in self.keys: if self.keys[key] == 2: self.keys[key] = 1 def spawn(self): self.camLens.setFar(100) base.camLens.setNear(0.1) base.camLens.setFov(120) base.cam.setPos(0.01, 0, 1.5) model = loader.loadModel("assets/models/vehicle.bam") self.ship = Ship(self, model) self.ship.node.reparentTo(render) self.ship.node.setPos(4, 0, 1) def shuffleSong(self): if self.music: vol = self.music.getVolume() self.music.stop() else: vol = 0.03 songs = ("assets/audio/ogg/road1.ogg", "assets/audio/ogg/road8.ogg", "assets/audio/ogg/road3.ogg") self.music = loader.loadSfx(choice(songs)) self.music.setVolume(vol) self.music.setLoop(True) self.music.play()
class SmartCamera: UPDATE_TASK_NAME = "update_smartcamera" notify = directNotify.newCategory("SmartCamera") OTSIndex = 0 def __init__(self): self.cTrav = CollisionTraverser('cam_traverser') base.pushCTrav(self.cTrav) self.cTrav.setRespectPrevTransform(1) self.default_pos = None self.parent = None self.initialized = False self.started = False self.camFloorRayNode = None self.ccRay2 = None self.ccRay2Node = None self.ccRay2NodePath = None self.ccRay2BitMask = None self.ccRay2MoveNodePath = None self.camFloorCollisionBroadcaster = None self.pointA = Point3(0) self.pointB = Point3(0) self.floorLineStart = Point3(0) self.camRadiusPoint = Point3(0) self.notify.debug("SmartCamera initialized!") def lerpCameraFov(self, fov, time): taskMgr.remove('cam-fov-lerp-play') oldFov = base.camLens.getHfov() if abs(fov - oldFov) > 0.1: def setCamFov(fov): base.camLens.setMinFov(fov / (4. / 3.)) self.camLerpInterval = LerpFunctionInterval(setCamFov, fromData=oldFov, toData=fov, duration=time, name='cam-fov-lerp') self.camLerpInterval.start() def setCameraFov(self, fov): self.fov = fov if not (self.isPageDown or self.isPageUp): base.camLens.setMinFov(self.fov / (4. / 3.)) def initCameraPositions(self): camHeight = max(base.localAvatar.getHeight(), 3.0) nrCamHeight = base.localAvatar.getHeight() heightScaleFactor = camHeight * 0.3333333333 defLookAt = Point3(0.0, 1.5, camHeight) self.firstPersonCamPos = Point3(0.0, 0.7, nrCamHeight * 5.0) scXoffset = 3.0 scPosition = (Point3(scXoffset - 1, -10.0, camHeight + 5.0), Point3(scXoffset, 2.0, camHeight)) self.cameraPositions = [ (Point3(0.0, -9.0 * heightScaleFactor, camHeight), defLookAt, Point3(0.0, camHeight, camHeight * 4.0), Point3(0.0, camHeight, camHeight * -1.0), 0), (Point3(0.0, 0.7, camHeight), defLookAt, Point3(0.0, camHeight, camHeight * 1.33), Point3(0.0, camHeight, camHeight * 0.66), 1), (Point3(0.0, -24.0 * heightScaleFactor, camHeight + 4.0), defLookAt, Point3(0.0, 1.5, camHeight * 4.0), Point3(0.0, 1.5, camHeight * -1.0), 0), (Point3(0.0, -12.0 * heightScaleFactor, camHeight + 4.0), defLookAt, Point3(0.0, 1.5, camHeight * 4.0), Point3(0.0, 1.5, camHeight * -1.0), 0) ] gta = base.config.GetBool("want-gta-controls", False) if not gta: # Insert the two front facing camera angles. self.cameraPositions.insert( 2, (Point3(5.7 * heightScaleFactor, 7.65 * heightScaleFactor, camHeight + 2.0), Point3(0.0, 1.0, camHeight), Point3(0.0, 1.0, camHeight * 4.0), Point3(0.0, 1.0, camHeight * -1.0), 0)) self.cameraPositions.insert( 3, (Point3(0.0, 8.65 * heightScaleFactor, camHeight), Point3(0.0, 1.0, camHeight), Point3(0.0, 1.0, camHeight * 4.0), Point3(0.0, 1.0, camHeight * -1.0), 0)) else: # Insert an over the shoulder camera angle. self.cameraPositions.insert( self.OTSIndex, (Point3(1.0, -4.25 * heightScaleFactor, camHeight), Point3(1.0, 1.5, camHeight), Point3(0.0, camHeight, camHeight * 4.0), Point3(0.0, camHeight, camHeight * -1.0), 0)) def pageUp(self): if not base.localAvatarReachable() or ( base.localAvatarReachable() and not base.localAvatar.avatarMovementEnabled): return if not self.isPageUp: self.isPageDown = 0 self.isPageUp = 1 self.lerpCameraFov(70, 0.6) self.setCameraPositionByIndex(self.cameraIndex) else: self.clearPageUpDown() def pageDown(self): if not base.localAvatarReachable() or ( base.localAvatarReachable() and not base.localAvatar.avatarMovementEnabled): return if not self.isPageDown: self.isPageUp = 0 self.isPageDown = 1 self.lerpCameraFov(70, 0.6) self.setCameraPositionByIndex(self.cameraIndex) else: self.clearPageUpDown() def clearPageUpDown(self): if self.isPageDown or self.isPageUp: self.lerpCameraFov(self.fov, 0.6) self.isPageDown = 0 self.isPageUp = 0 self.setCameraPositionByIndex(self.cameraIndex) def nextCameraPos(self, forward): if not base.localAvatarReachable() or ( base.localAvatarReachable() and not base.localAvatar.avatarMovementEnabled): return self.__cameraHasBeenMoved = 1 if forward: self.cameraIndex += 1 if self.cameraIndex > len(self.cameraPositions) - 1: self.cameraIndex = 0 else: self.cameraIndex -= 1 if self.cameraIndex < 0: self.cameraIndex = len(self.cameraPositions) - 1 self.setCameraPositionByIndex(self.cameraIndex) def setCameraPositionByIndex(self, index): self.notify.debug('switching to camera position %s' % index) self.cameraIndex = index self.setCameraSettings(self.cameraPositions[index]) def isOverTheShoulder(self): return self.cameraIndex == self.OTSIndex def setCameraSettings(self, camSettings): base.localAvatar.hideCrosshair() #if self.isOverTheShoulder() and base.localAvatar.avatarMovementEnabled: # base.localAvatar.showCrosshair() # spine = base.localAvatar.find("**/def_cageA") # if spine.isEmpty(): # base.localAvatar.controlJoint(None, "torso", "def_cageA") #else: # base.localAvatar.hideCrosshair() # spine = base.localAvatar.find("**/def_spineA") # if not spine.isEmpty(): # spine.detachNode() # base.localAvatar.releaseJoint("torso", "def_cageA") self.setIdealCameraPos(camSettings[0]) if self.isPageUp and self.isPageDown or not self.isPageUp and not self.isPageDown: self.__cameraHasBeenMoved = 1 self.setLookAtPoint(camSettings[1]) elif self.isPageUp: self.__cameraHasBeenMoved = 1 self.setLookAtPoint(camSettings[2]) elif self.isPageDown: self.__cameraHasBeenMoved = 1 self.setLookAtPoint(camSettings[3]) else: self.notify.error('This case should be impossible.') self.__disableSmartCam = camSettings[4] if self.__disableSmartCam: self.putCameraFloorRayOnAvatar() self.cameraZOffset = 0.0 def set_default_pos(self, pos): self.default_pos = pos #self.notify.debug("default camera position set as (%s, %s, %s)" % (x, y, z)) def get_default_pos(self): return self.default_pos def set_parent(self, parent): self.parent = parent def get_parent(self): return self.parent def getVisibilityPoint(self): return Point3(0.0, 0.0, self.getIdealCameraPos()[2]) def setLookAtPoint(self, la): self.__curLookAt = Point3(la) def getLookAtPoint(self): return Point3(self.__curLookAt) def setIdealCameraPos(self, pos): self.__idealCameraPos = Point3(pos) self.updateSmartCameraCollisionLineSegment() def getIdealCameraPos(self): return Point3(self.__idealCameraPos) def getPushedCameraPos(self): ideal = self.getIdealCameraPos() return ideal + (ideal.normalized() * 0.25) def getCompromiseCameraPos(self): if self.__idealCameraObstructed == 0: compromisePos = self.getIdealCameraPos() else: visPnt = self.getVisibilityPoint() idealPos = self.getIdealCameraPos() distance = Vec3(idealPos - visPnt).length() ratio = self.closestObstructionDistance / distance compromisePos = idealPos * ratio + visPnt * (1 - ratio) if not base.localAvatar.battleControls: # Lift the camera up in classic controls. # In third person battle controls, we want to just move the camera closer to the player. liftMult = max(0.0, 1.0 - ratio * ratio) compromisePos = Point3( compromisePos[0], compromisePos[1], compromisePos[2] + base.localAvatar.getHeight() * 0.4 * liftMult) if base.localAvatarReachable() and not base.localAvatar.battleControls: compromisePos.setZ(compromisePos[2] + self.cameraZOffset) return compromisePos def updateSmartCameraCollisionLineSegment(self): pointB = self.getPushedCameraPos() pointA = self.getVisibilityPoint() vectorAB = Vec3(pointB - pointA) lengthAB = vectorAB.length() if lengthAB > 0.001: self.pointA = pointA self.pointB = pointB def initializeSmartCamera(self): self.__idealCameraObstructed = 0 self.closestObstructionDistance = 0.0 self.cameraIndex = 0 self.cameraPositions = [] self.auxCameraPositions = [] self.cameraZOffset = 0.0 self.setGeom(render) self.__onLevelGround = 0 self.__camCollCanMove = 0 self.__disableSmartCam = 0 self.initializeSmartCameraCollisions() self._smartCamEnabled = False self.isPageUp = 0 self.isPageDown = 0 self.fov = CIGlobals.DefaultCameraFov def enterFirstPerson(self): self.stop_smartcamera() if hasattr(self.get_parent(), 'toon_head'): head = self.get_parent().toon_head camera.reparentTo(head) camera.setPos(0, -0.35, 0) camera.setHpr(0, 0, 0) def exitFirstPerson(self): self.initialize_smartcamera() self.initialize_smartcamera_collisions() self.start_smartcamera() def putCameraFloorRayOnAvatar(self): self.floorLineStart = Point3(0, 0, 5) def putCameraFloorRayOnCamera(self): self.floorLineStart = self.getIdealCameraPos() + (0, 0, 10) def recalcCameraSphere(self): nearPlaneDist = base.camLens.getNear() hFov = base.camLens.getHfov() vFov = base.camLens.getVfov() hOff = nearPlaneDist * math.tan(deg2Rad(hFov / 2.0)) vOff = nearPlaneDist * math.tan(deg2Rad(vFov / 2.0)) camPnts = [ Point3(hOff, nearPlaneDist, vOff), Point3(-hOff, nearPlaneDist, vOff), Point3(hOff, nearPlaneDist, -vOff), Point3(-hOff, nearPlaneDist, -vOff), Point3(0.0, 0.0, 0.0) ] avgPnt = Point3(0.0, 0.0, 0.0) for camPnt in camPnts: avgPnt = avgPnt + camPnt avgPnt = avgPnt / len(camPnts) sphereRadius = 0.0 for camPnt in camPnts: dist = Vec3(camPnt - avgPnt).length() if dist > sphereRadius: sphereRadius = dist avgPnt = Point3(avgPnt) self.camRadiusPoint = avgPnt def setGeom(self, geom): self.__geom = geom def initializeSmartCameraCollisions(self): if self.initialized: return self.initialized = True def deleteSmartCameraCollisions(self): self.initialized = False return def startUpdateSmartCamera(self): if self.started: return self.__floorDetected = 0 self.__cameraHasBeenMoved = 1 self.recalcCameraSphere() self.__instantaneousCamPos = camera.getPos() self.__disableSmartCam = 0 self.__lastPosWrtRender = camera.getPos(render) + 1 self.__lastHprWrtRender = camera.getHpr(render) + 1 self.updateSmartCameraCollisionLineSegment() taskName = base.localAvatar.taskName('updateSmartCamera') taskMgr.remove(taskName) taskMgr.add(self.updateSmartCamera, taskName, priority=47) self.started = True def stopUpdateSmartCamera(self): taskName = base.localAvatar.taskName('updateSmartCamera') taskMgr.remove(taskName) camera.setPos(self.getIdealCameraPos()) self.started = False def updateSmartCamera(self, task): if base.localAvatarReachable( ) and base.localAvatar.battleControls and base.localAvatar.isFirstPerson( ): return Task.cont if not self.__camCollCanMove and not self.__cameraHasBeenMoved: if self.__lastPosWrtRender == camera.getPos(render): if self.__lastHprWrtRender == camera.getHpr(render): return Task.cont self.__cameraHasBeenMoved = 0 self.__lastPosWrtRender = camera.getPos(render) self.__lastHprWrtRender = camera.getHpr(render) self.__idealCameraObstructed = 0 self.updateSmartCameraCollisionLineSegment() if not self.__disableSmartCam: pointA = render.getRelativePoint(camera.getParent(), self.pointA) pointB = render.getRelativePoint(camera.getParent(), self.pointB) mask = CIGlobals.WallGroup | CIGlobals.CameraGroup if base.localAvatarReachable(): if base.localAvatar.battleControls: mask |= (CIGlobals.FloorGroup | CIGlobals.StreetVisGroup) result = PhysicsUtils.rayTestClosestNotMe( base.localAvatar, pointA, pointB, mask) if result: self.handleCameraObstruction(result) if not self.__onLevelGround: self.handleCameraFloorInteraction() if not self.__idealCameraObstructed: self.nudgeCamera() return Task.cont def positionCameraWithPusher(self, pos, lookAt): camera.setPos(pos) #self.ccPusherTrav.traverse(self.__geom) camera.lookAt(lookAt) def nudgeCamera(self): CLOSE_ENOUGH = 0.1 curCamPos = self.__instantaneousCamPos curCamHpr = camera.getHpr() targetCamPos = self.getCompromiseCameraPos() targetCamLookAt = self.getLookAtPoint() posDone = 0 if Vec3(curCamPos - targetCamPos).length() <= CLOSE_ENOUGH: camera.setPos(targetCamPos) posDone = 1 camera.setPos(targetCamPos) camera.lookAt(targetCamLookAt) targetCamHpr = camera.getHpr() hprDone = 0 if Vec3(curCamHpr - targetCamHpr).length() <= CLOSE_ENOUGH: hprDone = 1 if posDone and hprDone: return lerpRatio = 0.15 lerpRatio = 1 - pow(1 - lerpRatio, globalClock.getDt() * 30.0) self.__instantaneousCamPos = targetCamPos * lerpRatio + curCamPos * ( 1 - lerpRatio) if self.__disableSmartCam or not self.__idealCameraObstructed: newHpr = targetCamHpr * lerpRatio + curCamHpr * (1 - lerpRatio) else: newHpr = targetCamHpr camera.setPos(self.__instantaneousCamPos) camera.setHpr(newHpr) def popCameraToDest(self): newCamPos = self.getCompromiseCameraPos() newCamLookAt = self.getLookAtPoint() self.positionCameraWithPusher(newCamPos, newCamLookAt) self.__instantaneousCamPos = camera.getPos() def handleCameraObstruction(self, camObstrCollisionEntry): # Convert world space hit position to avatar space. collisionPoint = camera.getParent().getRelativePoint( render, camObstrCollisionEntry.getHitPos()) collisionVec = Vec3(collisionPoint - self.pointA) pushVec = Vec3(self.getIdealCameraPos() - self.getPushedCameraPos()) distance = collisionVec.length() - pushVec.length() self.__idealCameraObstructed = 1 self.closestObstructionDistance = distance self.popCameraToDest() def handleCameraFloorInteraction(self): if self.__onLevelGround or not base.localAvatarReachable() or ( base.localAvatarReachable() and base.localAvatar.battleControls): return self.putCameraFloorRayOnCamera() pointA = render.getRelativePoint(camera.getParent(), self.floorLineStart) pointB = pointA + (Vec3.down() * 1000) result = PhysicsUtils.rayTestClosestNotMe(base.localAvatar, pointA, pointB, CIGlobals.FloorGroup) if not result: return camObstrCollisionEntry = result camHeightFromFloor = (camera.getRelativePoint( render, camObstrCollisionEntry.getHitPos())).getZ() heightOfFloorUnderCamera = (camera.getPos()[2] - CIGlobals.FloorOffset) + camHeightFromFloor self.cameraZOffset = camera.getPos()[2] + camHeightFromFloor if self.cameraZOffset < 0: self.cameraZOffset = self.cameraZOffset * 0.33333333329999998 camHeight = max(base.localAvatar.getHeight(), 3.0) if self.cameraZOffset < -(camHeight * 0.5): if self.cameraZOffset < -camHeight: self.cameraZOffset = 0.0 else: self.cameraZOffset = -(camHeight * 0.5) if self.__floorDetected == 0: self.__floorDetected = 1 self.popCameraToDest()
class RoamingRalphDemo(ShowBase): def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) self.orbCollisionHandler = CollisionHandlerQueue() self.cTrav = CollisionTraverser() self.cTrav.setRespectPrevTransform(True) #hbPath = NodePath() utilsKristina2.setUpKeys(self) utilsKristina2.loadModels(self) utilsKristina2.setUpLighting(self) utilsKristina2.setUpFloatingSpheres(self) utilsKristina2.setUpRalphsShot(self) utilsKristina2.setUpCamera(self) utilsKristina2.setUpCollisionSpheres(self) self.healthTxt = utilsKristina2.addInstructions(.06,"Health: 100") self.orbTxt = utilsKristina2.addInstructions(.18,"Orbs: 0") self.vec = LVector3(0,1,0)#vector for pawns shot # Create a frame #frame = DirectFrame(text = "main", scale = 0.001) # Add button #bar = DirectWaitBar(text = "", value = 50, pos = (0,.4,.4)) #bar.reparent(render) # Game state variables self.isMoving = False self.jumping = False self.vz = 0 self.numOrbs = 0 self.healthCount = 100 #self.shotList = [] #self.sphere = CollisionBox((self.ralph.getX() + -10,self.ralph.getY(),self.ralph.getZ()),10,10,10) self.sphere = CollisionSphere(0,-5,4,3) self.sphere3 = CollisionSphere(0,5,5,3) self.sphere4 = CollisionSphere(-4,0,5,2) self.sphere5 = CollisionSphere(4,0,5,2) self.sphere2 = CollisionSphere(0,0,3,2) self.cnodePath = self.ralph.attachNewNode((CollisionNode("ralphColNode"))) self.cnodePath2 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck"))) self.cnodePath3 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck2"))) self.cnodePath4 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck3"))) self.cnodePath5 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck4"))) self.cnodePath.node().addSolid(self.sphere2) self.cnodePath2.node().addSolid(self.sphere) self.cnodePath3.node().addSolid(self.sphere3) self.cnodePath4.node().addSolid(self.sphere4) self.cnodePath5.node().addSolid(self.sphere5) #self.cnodePath.node().addSolid(self.sphere2) self.cnodePath.show() #self.cnodePath2.show() #self.cnodePath3.show() #self.cnodePath4.show() #self.cnodePath5.show() self.cTrav.addCollider(self.cnodePath2, self.orbCollisionHandler) self.cTrav.addCollider(self.cnodePath3, self.orbCollisionHandler) self.cTrav.addCollider(self.cnodePath4, self.orbCollisionHandler) self.cTrav.addCollider(self.cnodePath5, self.orbCollisionHandler) self.pusher = CollisionHandlerPusher() self.pusher.addCollider(self.cnodePath, self.ralph) #self.cTrav.addCollider(self.cnodePath, self.ralphCollisionHandler) self.cTrav.addCollider(self.cnodePath, self.pusher) self.chrisLastShotTime = globalClock.getFrameTime() self.chrisTimer = globalClock.getDt() #def __init__(self, pos,showbase, colPathName, dir, length): self.chrisList = [utilsKristina2.chris((15,0,0.5),self,"chrisColPath0","X",6), utilsKristina2.chris((18,29,0.5),self,"chrisColPath1","X",6), utilsKristina2.chris((-6,67,0.5),self,"chrisColPath2","X",6), utilsKristina2.chris((-41,72,0.5),self,"chrisColPath7","X",6)] #,utilsKristina2.chris((-42,106,0.5),self,"chrisColPath3","X",6)]#, utilsKristina2.chris((-62,108,0.5),self,"chrisColPath4","X",6), #utilsKristina2.chris((-74,70,0.5),self,"chrisColPath5","y",6)] #def _init_(self,showbase,pos,color,speed,radius): self.orbList = [utilsKristina2.orb(self,(0,0,2),(0,0,1,1),20,4)] self.donutList = [utilsKristina2.donut(self,(0,0,2),40,3)] self.cameraCollided = False self.ralphSpeed = 60 self.ralphHit = False self.ralphRedTime = 0 self.ralphLife=True taskMgr.add(self.move, "moveTask") taskMgr.add(self.moveChris,"moveChrisTask") # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value def startEnemyThread(self): showbase = self class enemyThread(threading.Thread): def run(self): dt = globalClock.getDt() for chris in showbase.chrisList: chris.moveChris(dt,showbase,showbase.chrisList) def moveChris(self,task): dt = globalClock.getDt() for chris in self.chrisList: chris.moveChris(dt,self,self.chrisList) return task.cont # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # Get the time that elapsed since last frame. We multiply this with # the desired speed in order to find out with which distance to move # in order to achieve that desired speed. dt = globalClock.getDt() #utilsKristina2.moveChris(self,dt) #self.chris2.moveChris(dt,self) #self.startEnemyThread() if globalClock.getFrameTime()- self.ralphRedTime > .3 and self.ralphHit == True: self.ralph.clearColor() self.ralphHit = False # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. if self.keyMap["cam-left"]: self.camera.setZ(self.camera, -20 * dt) if self.keyMap["cam-right"]: self.camera.setZ(self.camera, +20 * dt) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if self.keyMap["left"]: self.ralph.setH(self.ralph.getH() + 75 * dt) #self.camera.setX(self.camera, +15.5 * dt) if self.keyMap["right"]: self.ralph.setH(self.ralph.getH() - 75 * dt) #self.camera.setX(self.camera, -15.5 * dt) if self.keyMap["forward"]: self.ralph.setFluidY(self.ralph, -1*self.ralphSpeed * dt) #self.camera.setY(self.camera, -35 * dt) if self.keyMap["back"]: self.ralph.setFluidY(self.ralph, self.ralphSpeed * dt) #self.camera.setY(self.camera, 35 * dt) if self.keyMap["space"]: if self.jumping is False: #self.ralph.setZ(self.ralph.getZ() + 100 * dt) self.jumping = True self.vz = 8 if self.keyMap["c"] or self.keyMap["enter"]: if self.keyMap["c"]: self.keyMap["c"]=False if self.keyMap["enter"]: self.keyMap["enter"] = False self.shotList[self.shotCount].lpivot.setPos(self.ralph.getPos()) self.shotList[self.shotCount].lpivot.setZ(self.ralph.getZ() + .5) self.shotList[self.shotCount].lpivot.setX(self.ralph.getX() - .25) print self.ralph.getPos() #self.shotList.append(rShot) #self.lightpivot3.setPos(self.ralph.getPos()) #self.lightpivot3.setZ(self.ralph.getZ() + .5) #self.lightpivot3.setX(self.ralph.getX() - .25) #self.myShot.setHpr(self.ralph.getHpr()) #parent to ralph #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,-1,0)) #self.myShotVec = vec node = NodePath("tmp") node.setHpr(self.ralph.getHpr()) vec = render.getRelativeVector(node,(0,-1,0)) self.shotList[self.shotCount].vec = vec self.shotCount = (self.shotCount + 1) % 10 for rs in self.shotList: rs.lpivot.setPos(rs.lpivot.getPos() + rs.vec * dt * 25 ) #if shot is too far stop updating if self.jumping is True: self.vz = self.vz - 16* dt self.ralph.setZ(self.ralph.getZ() + self.vz * dt ) if self.ralph.getZ() < 0: self.ralph.setZ(0) self.jumping = False else: if self.ralph.getZ() < 0.25: self.ralph.setZ(0.25) elif self.ralph.getZ() > 0.25: self.ralph.setZ(self.ralph.getZ() -7 * dt) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["space"] or self.keyMap["forward"] or self.keyMap["back"]: if self.isMoving is False: self.ralph.loop("run") self.isMoving = True else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False # update pawns shot or set up new shot after it reaches a certain distance node = NodePath("tmp") node.setHpr(self.pawn.getHpr()) vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0)) self.shot.setPos(self.shot.getPos() + self.vec * dt * 10 ) if self.shot.getY() < -15 or self.shot.getY() > 30 or self.shot.getX() < 5 or self.shot.getX() > 15: self.shot.setPos(self.pawn.getPos() + (0,0,0)) self.vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0)) self.vec = render.getRelativeVector(node,(random.random() * random.randrange(-1,2),random.random() + 1,0)) # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. #self.camera.lookAt(self.floater) camvec = self.ralph.getPos() - self.camera.getPos() #camvec = Vec3(0,camvec.getY(),0) camdist = camvec.length() x = self.camera.getZ() camvec.normalize() #if camdist > 6.0: # self.camera.setPos(self.camera.getPos() + camvec * (camdist - 6)) #if camdist < 6.0: # self.camera.setPos(self.camera.getPos() - camvec * (6 - camdist)) # Normally, we would have to call traverse() to check for collisions. # However, the class ShowBase that we inherit from has a task to do # this for us, if we assign a CollisionTraverser to self.cTrav. #self.cTrav.traverse(render) # Adjust camera so it stays at same height if self.cameraCollided == False: if self.camera.getZ() < self.ralph.getZ() + 1 or self.camera.getZ() > self.ralph.getZ() + 1: self.camera.setZ(self.ralph.getZ() + 1) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.camera.lookAt(self.floater) entries = list(self.orbCollisionHandler.getEntries()) if(len(entries) > 0): #self.lightpivot.reparentTo(NodePath()) orbCollected = False self.cameraCollided = False self.ralphSpeed = 65 for entry in self.orbCollisionHandler.getEntries(): #print(entry) fromColNp = entry.getFromNodePath() toColNp = entry.getIntoNodePath() if fromColNp.getName() == "orbColPath" and toColNp.getName() == "ralphColNode": if orbCollected == False: fromColNp.getParent().reparentTo(NodePath()) self.orbTxt.destroy() self.numOrbs += 1 str1 = "Orbs: " + str(self.numOrbs) self.orbTxt = utilsKristina2.addInstructions(.18, str1) orbCollected = True elif toColNp.getName() == "orbColPath" and fromColNp.getName() == "ralphColNode": if orbCollected == False: toColNp.getParent().reparentTo(NodePath()) self.orbTxt.destroy() self.numOrbs += 1 str1 = "Orbs: " + str(self.numOrbs) self.orbTxt = utilsKristina2.addInstructions(.18, str1) orbCollected = True elif toColNp.getName() == "ralphOrbColPath" and (fromColNp.getName()[:-1] == "chrisColPath" or fromColNp.getName()[:-2] == "chrisColPath"): toColNp.getParent().setZ(20) for chriss in self.chrisList: if chriss.chrisColName == fromColNp.getName(): chris = chriss break chris.chrisHealth = chris.chrisHealth - 1 chris.chris.setColor(1,0,0,1) chris.chrisHit = True chris.chrisRedTime = globalClock.getFrameTime() #print chris.chrisRedTime if chris.chrisHealth < 0: fromColNp.getParent().removeNode() chris.chrisAlive = False chris.chrisShot.setZ(26) elif (toColNp.getName()[:-1] == "chrisColPath" or toColNp.getName()[:-2] == "chrisColPath") and fromColNp.getName() == "ralphOrbColPath": fromColNp.getParent().setZ(20) for chriss in self.chrisList: if chriss.chrisColName == toColNp.getName(): chris = chriss break chris.chrisHealth = chris.chrisHealth - 1 chris.chris.setColor(1,0,0,1) chris.chrisHit = True chris.chrisRedTime = globalClock.getFrameTime() #print chris.chrisRedTime if chris.chrisHealth < 0: toColNp.getParent().removeNode() chris.chrisAlive = False chris.chrisShot.setZ(26) elif toColNp.getName() == "enemyOrbColPath" and fromColNp.getName() == "ralphColNode": toColNp.getParent().setZ(26) self.healthTxt.destroy() self.healthCount -= 3 str1 = "Health: " + str(self.healthCount) self.healthTxt = utilsKristina2.addInstructions(.06, str1) self.ralphHit = True self.ralph.setColor((1,0,0,1)) self.ralphRedTime = globalClock.getFrameTime() if self.healthCount <=0: sys.exit() elif toColNp.getName() == "ralphColNode" and fromColNp.getName() == "enemyOrbColPath": fromColNp.getParent().setZ(26) self.healthTxt.destroy() self.healthCount -= 3 str1 = "Health: " + str(self.healthCount) self.healthTxt = utilsKristina2.addInstructions(.06, str1) self.ralphHit = True self.ralph.setColor((1,0,0,1)) self.ralphRedTime = globalClock.getFrameTime() if self.healthCount <=0: sys.exit() elif fromColNp.getName() == "ralphOrbColPath" and toColNp.getName() == "allinclusive": fromColNp.getParent().setZ(50) elif toColNp.getName() == "ralphOrbColPath" and fromColNp.getName() == "allinclusive": toColNp.getParent().setZ(50) elif fromColNp.getName() == "enemyOrbWallCheck" and toColNp.getName() == "allinclusive": fromColNp.getParent().setZ(50) #print toColNp.getName() elif toColNp.getName() == "enemyOrbWallCheck" and fromColNp.getName() == "allinclusive": toColNp.getParent().setZ(50) #print fromColNp.getName() elif fromColNp.getName() == "ralphWallCheck" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,-1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 25 elif toColNp.getName() == "ralphWallCheck" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,-1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #print "wtf" #toColNp.getParent().setZ(26) self.ralphSpeed = 25 elif fromColNp.getName() == "ralphWallCheck2" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 25 elif toColNp.getName() == "ralphWallCheck2" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #self.camera.setPos(self.ralph.getPos()) #self.cameraCollided = True self.ralphSpeed = 25 elif fromColNp.getName() == "ralphWallCheck3" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(-1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 25 print "3" elif toColNp.getName() == "ralphWallCheck3" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(-1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #self.camera.setPos(self.ralph.getPos()) #self.cameraCollided = True self.ralphSpeed = 25 print "3" elif fromColNp.getName() == "ralphWallCheck4" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 25 print "4" elif toColNp.getName() == "ralphWallCheck4" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #self.camera.setPos(self.ralph.getPos()) #self.cameraCollided = True self.ralphSpeed = 25 print "4" return task.cont
class Moving(ShowBase): def __init__(self): ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = {"left": 0, "right": 0, "forward": 0, "back": 0, "up": 0} # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("EggMod/SandPlan.egg") self.environ.reparentTo(render) self.environ.setScale(20) StartPos = LVector3(0, 0, 0) self.movint = loader.loadModel("EggMod/HailPar.egg") self.movint.reparentTo(render) self.movint.setScale(2) self.movint.setPos(StartPos + (0, 0, 0.5)) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["back", True]) self.accept("f", self.setKey, ["up", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["back", False]) self.accept("f-up", self.setKey, ["up", False]) self.mopan = Pmango() self.alin = LinearEulerIntegrator() self.mopan.attachLinearIntegrator(self.alin) self.arin = AngularEulerIntegrator() self.mopan.attachAngularIntegrator(self.arin) taskMgr.add(self.move, "moveTask") self.cTrav = CollisionTraverser() #base.cTrav.setRespectPrevTransform(True) self.actMove = NodePath("ActMove") self.actMove.reparentTo(render) self.actMove.setPos(0, 0, 190) self.an = ActorNode("BMova") self.anp = self.actMove.attachNewNode(self.an) self.mopan.attachPhysicalNode(self.an) self.movint.reparentTo(self.actMove) self.anp.node().getPhysicsObject().setMass(1) #self.an.getPhysicsObject().setTerminalVelocity(1.0) self.dvi = 0 self.grava = ForceNode('GravAll') self.grar = render.attachNewNode(self.grava) self.grdi = LinearVectorForce(0.0, -0.0, -8.0) #self.grdi.setMassDependent(1) self.grava.addForce( self.grdi) #Forces have to be added to force nodes and to # a physics manager self.mopan.addLinearForce(self.grdi) self.BMoveBalance = CollisionSphere(0, 0, -7.0, 1) self.BMoveBalanceNode = CollisionNode('BMove') self.BMoveBalanceNode.addSolid(self.BMoveBalance) #self.BMABalance = CollisionSphere(0, 0, -7.0, 1) #self.BMABalanceNode = CollisionNode('BMAove') #self.BMABalanceNode.addSolid(self.BMABalance) self.BMoveBalancePath = self.actMove.attachNewNode( self.BMoveBalanceNode) #self.BMAoveBalancePath=self.anp.attachNewNode(self.BMABalanceNode) #self.BMAoveBalancePath.setPos(0,0,-8) self.BMAoveBalancePath = self.BMoveBalancePath.copyTo(self.anp) self.BMAoveBalancePath.setPos(0, 0, -5) self.BMoveBalancePath.setPos( self.actMove.getRelativePoint(self.BMoveBalancePath, self.BMoveBalancePath.getPos())) self.DinGro = PhysicsCollisionHandler() self.DinGro.setStaticFrictionCoef(1) self.DinGro.setDynamicFrictionCoef(2) self.DinGro.setAlmostStationarySpeed(0.1) self.DinGro.addCollider( self.BMAoveBalancePath, self.anp) #Colliders use nodepaths for collisions instead of nodes self.cTrav.addCollider(self.BMAoveBalancePath, self.DinGro) self.DinGro.addCollider(self.BMoveBalancePath, self.anp) self.cTrav.addCollider(self.BMoveBalancePath, self.DinGro) # Uncomment this line to see the collision rays self.BMoveBalancePath.show() self.BMAoveBalancePath.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) render.setLight(render.attachNewNode(directionalLight)) self.calrun = 0 self.upcal = None self.anp.setPos(0, 0, 0) # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): # Get the time that elapsed since last frame. We multiply this with # the desired speed in order to find out with which distance to move # in order to achieve that desired speed. dt = globalClock.getDt() self.dvi += dt self.anr = self.an.getPhysicsObject() self.cTrav.setRespectPrevTransform(True) print(self.anr.getVelocity()) #self.anr.setVelocity(0,0,0) self.mopan.doPhysics(dt) if dt <= .2: self.actMove.setPos(self.actMove, self.anp.getPos()) self.anp.setPos(0, 0, 0.0) #self.anr.setVelocity(0,0,-1) #self.anp.setPos(0,0,0.0) if self.keyMap["left"]: self.actMove.setH(self.actMove.getH() + 200 * dt) if self.keyMap["right"]: self.actMove.setH(self.actMove.getH() - 200 * dt) if self.keyMap["forward"]: self.actMove.setFluidY(self.actMove, -25 * dt) if self.keyMap["back"]: self.actMove.setFluidY(self.actMove, 25 * dt) if self.keyMap["up"]: self.actMove.setFluidZ(self.actMove, 25 * dt) # Normally, we would have to call traverse() to check for collisions. # However, the class ShowBase that we inherit from has a task to do # this for us, if we assign a CollisionTraverser to self.cTrav. #self.cTrav.traverse(render) return task.cont
class SmartCamera: UPDATE_TASK_NAME = 'update_smartcamera' notify = directNotify.newCategory('SmartCamera') def __init__(self): self.cTrav = CollisionTraverser('cam_traverser') base.pushCTrav(self.cTrav) self.cTrav.setRespectPrevTransform(1) self.default_pos = None self.parent = None self.initialized = False self.started = False self.camFloorRayNode = None self.ccRay2 = None self.ccRay2Node = None self.ccRay2NodePath = None self.ccRay2BitMask = None self.ccRay2MoveNodePath = None self.camFloorCollisionBroadcaster = None self.notify.debug('SmartCamera initialized!') return def lerpCameraFov(self, fov, time): taskMgr.remove('cam-fov-lerp-play') oldFov = base.camLens.getHfov() if abs(fov - oldFov) > 0.1: def setCamFov(fov): base.camLens.setMinFov(fov / (4.0 / 3.0)) self.camLerpInterval = LerpFunctionInterval(setCamFov, fromData=oldFov, toData=fov, duration=time, name='cam-fov-lerp') self.camLerpInterval.start() def setCameraFov(self, fov): self.fov = fov if not (self.isPageDown or self.isPageUp): base.camLens.setMinFov(self.fov / (4.0 / 3.0)) def initCameraPositions(self): camHeight = max(base.localAvatar.getHeight(), 3.0) nrCamHeight = base.localAvatar.getHeight() heightScaleFactor = camHeight * 0.3333333333 defLookAt = Point3(0.0, 1.5, camHeight) self.firstPersonCamPos = Point3(0.0, 0.7, nrCamHeight * 5.0) scXoffset = 3.0 scPosition = (Point3(scXoffset - 1, -10.0, camHeight + 5.0), Point3(scXoffset, 2.0, camHeight)) self.cameraPositions = [ (Point3(0.0, -9.0 * heightScaleFactor, camHeight), defLookAt, Point3(0.0, camHeight, camHeight * 4.0), Point3(0.0, camHeight, camHeight * -1.0), 0), ( Point3(0.0, 0.7, camHeight), defLookAt, Point3(0.0, camHeight, camHeight * 1.33), Point3(0.0, camHeight, camHeight * 0.66), 1), ( Point3(5.7 * heightScaleFactor, 7.65 * heightScaleFactor, camHeight + 2.0), Point3(0.0, 1.0, camHeight), Point3(0.0, 1.0, camHeight * 4.0), Point3(0.0, 1.0, camHeight * -1.0), 0), ( Point3(0.0, 8.65 * heightScaleFactor, camHeight), Point3(0.0, 1.0, camHeight), Point3(0.0, 1.0, camHeight * 4.0), Point3(0.0, 1.0, camHeight * -1.0), 0), ( Point3(0.0, -24.0 * heightScaleFactor, camHeight + 4.0), defLookAt, Point3(0.0, 1.5, camHeight * 4.0), Point3(0.0, 1.5, camHeight * -1.0), 0), ( Point3(0.0, -12.0 * heightScaleFactor, camHeight + 4.0), defLookAt, Point3(0.0, 1.5, camHeight * 4.0), Point3(0.0, 1.5, camHeight * -1.0), 0)] def pageUp(self): if not base.localAvatar.avatarMovementEnabled: return if not self.isPageUp: self.isPageDown = 0 self.isPageUp = 1 self.lerpCameraFov(70, 0.6) self.setCameraPositionByIndex(self.cameraIndex) else: self.clearPageUpDown() def pageDown(self): if not base.localAvatar.avatarMovementEnabled: return if not self.isPageDown: self.isPageUp = 0 self.isPageDown = 1 self.lerpCameraFov(70, 0.6) self.setCameraPositionByIndex(self.cameraIndex) else: self.clearPageUpDown() def clearPageUpDown(self): if self.isPageDown or self.isPageUp: self.lerpCameraFov(self.fov, 0.6) self.isPageDown = 0 self.isPageUp = 0 self.setCameraPositionByIndex(self.cameraIndex) def nextCameraPos(self, forward): if not base.localAvatar.avatarMovementEnabled: return self.__cameraHasBeenMoved = 1 if forward: self.cameraIndex += 1 if self.cameraIndex > len(self.cameraPositions) - 1: self.cameraIndex = 0 else: self.cameraIndex -= 1 if self.cameraIndex < 0: self.cameraIndex = len(self.cameraPositions) - 1 self.setCameraPositionByIndex(self.cameraIndex) def setCameraPositionByIndex(self, index): self.notify.debug('switching to camera position %s' % index) self.setCameraSettings(self.cameraPositions[index]) def setCameraSettings(self, camSettings): self.setIdealCameraPos(camSettings[0]) if self.isPageUp and self.isPageDown or not self.isPageUp and not self.isPageDown: self.__cameraHasBeenMoved = 1 self.setLookAtPoint(camSettings[1]) else: if self.isPageUp: self.__cameraHasBeenMoved = 1 self.setLookAtPoint(camSettings[2]) else: if self.isPageDown: self.__cameraHasBeenMoved = 1 self.setLookAtPoint(camSettings[3]) else: self.notify.error('This case should be impossible.') self.__disableSmartCam = camSettings[4] if self.__disableSmartCam: self.putCameraFloorRayOnAvatar() self.cameraZOffset = 0.0 def set_default_pos(self, pos): self.default_pos = pos def get_default_pos(self): return self.default_pos def set_parent(self, parent): self.parent = parent def get_parent(self): return self.parent def getVisibilityPoint(self): return Point3(0.0, 0.0, base.localAvatar.getHeight()) def setLookAtPoint(self, la): self.__curLookAt = Point3(la) def getLookAtPoint(self): return Point3(self.__curLookAt) def setIdealCameraPos(self, pos): self.__idealCameraPos = Point3(pos) self.updateSmartCameraCollisionLineSegment() def getIdealCameraPos(self): return Point3(self.__idealCameraPos) def getCompromiseCameraPos(self): if self.__idealCameraObstructed == 0: compromisePos = self.getIdealCameraPos() else: visPnt = self.getVisibilityPoint() idealPos = self.getIdealCameraPos() distance = Vec3(idealPos - visPnt).length() ratio = self.closestObstructionDistance / distance compromisePos = idealPos * ratio + visPnt * (1 - ratio) liftMult = 1.0 - ratio * ratio compromisePos = Point3(compromisePos[0], compromisePos[1], compromisePos[2] + base.localAvatar.getHeight() * 0.4 * liftMult) compromisePos.setZ(compromisePos[2] + self.cameraZOffset) return compromisePos def updateSmartCameraCollisionLineSegment(self): pointB = self.getIdealCameraPos() pointA = self.getVisibilityPoint() vectorAB = Vec3(pointB - pointA) lengthAB = vectorAB.length() if lengthAB > 0.001: self.ccLine.setPointA(pointA) self.ccLine.setPointB(pointB) def initializeSmartCamera(self): self.__idealCameraObstructed = 0 self.closestObstructionDistance = 0.0 self.cameraIndex = 0 self.cameraPositions = [] self.auxCameraPositions = [] self.cameraZOffset = 0.0 self.setGeom(render) self.__onLevelGround = 0 self.__camCollCanMove = 0 self.__disableSmartCam = 0 self.initializeSmartCameraCollisions() self._smartCamEnabled = False self.isPageUp = 0 self.isPageDown = 0 self.fov = CIGlobals.DefaultCameraFov def enterFirstPerson(self): self.stop_smartcamera() if hasattr(self.get_parent(), 'toon_head'): head = self.get_parent().toon_head camera.reparentTo(head) camera.setPos(0, -0.35, 0) camera.setHpr(0, 0, 0) def exitFirstPerson(self): self.initialize_smartcamera() self.initialize_smartcamera_collisions() self.start_smartcamera() def putCameraFloorRayOnAvatar(self): self.camFloorRayNode.setPos(base.localAvatar, 0, 0, 5) def putCameraFloorRayOnCamera(self): self.camFloorRayNode.setPos(self.ccSphereNodePath, 0, 0, 0) def recalcCameraSphere(self): nearPlaneDist = base.camLens.getNear() hFov = base.camLens.getHfov() vFov = base.camLens.getVfov() hOff = nearPlaneDist * math.tan(deg2Rad(hFov / 2.0)) vOff = nearPlaneDist * math.tan(deg2Rad(vFov / 2.0)) camPnts = [Point3(hOff, nearPlaneDist, vOff), Point3(-hOff, nearPlaneDist, vOff), Point3(hOff, nearPlaneDist, -vOff), Point3(-hOff, nearPlaneDist, -vOff), Point3(0.0, 0.0, 0.0)] avgPnt = Point3(0.0, 0.0, 0.0) for camPnt in camPnts: avgPnt = avgPnt + camPnt avgPnt = avgPnt / len(camPnts) sphereRadius = 0.0 for camPnt in camPnts: dist = Vec3(camPnt - avgPnt).length() if dist > sphereRadius: sphereRadius = dist avgPnt = Point3(avgPnt) self.ccSphereNodePath.setPos(avgPnt) self.ccSphereNodePath2.setPos(avgPnt) self.ccSphere.setRadius(sphereRadius) def setGeom(self, geom): self.__geom = geom def initializeSmartCameraCollisions(self): if self.initialized: return self.ccTrav = CollisionTraverser('LocalAvatar.ccTrav') self.ccLine = CollisionSegment(0.0, 0.0, 0.0, 1.0, 0.0, 0.0) self.ccLineNode = CollisionNode('ccLineNode') self.ccLineNode.addSolid(self.ccLine) self.ccLineNodePath = base.localAvatar.attachNewNode(self.ccLineNode) self.ccLineBitMask = CIGlobals.CameraBitmask self.ccLineNode.setFromCollideMask(self.ccLineBitMask) self.ccLineNode.setIntoCollideMask(BitMask32.allOff()) self.camCollisionQueue = CollisionHandlerQueue() self.ccTrav.addCollider(self.ccLineNodePath, self.camCollisionQueue) self.ccSphere = CollisionSphere(0, 0, 0, 1) self.ccSphereNode = CollisionNode('ccSphereNode') self.ccSphereNode.addSolid(self.ccSphere) self.ccSphereNodePath = base.camera.attachNewNode(self.ccSphereNode) self.ccSphereNode.setFromCollideMask(CIGlobals.CameraBitmask) self.ccSphereNode.setIntoCollideMask(BitMask32.allOff()) self.camPusher = CollisionHandlerPusher() self.camPusher.addCollider(self.ccSphereNodePath, base.camera) self.camPusher.setCenter(base.localAvatar) self.ccPusherTrav = CollisionTraverser('LocalAvatar.ccPusherTrav') self.ccSphere2 = self.ccSphere self.ccSphereNode2 = CollisionNode('ccSphereNode2') self.ccSphereNode2.addSolid(self.ccSphere2) self.ccSphereNodePath2 = base.camera.attachNewNode(self.ccSphereNode2) self.ccSphereNode2.setFromCollideMask(CIGlobals.CameraBitmask) self.ccSphereNode2.setIntoCollideMask(BitMask32.allOff()) self.camPusher2 = CollisionHandlerPusher() self.ccPusherTrav.addCollider(self.ccSphereNodePath2, self.camPusher2) self.camPusher2.addCollider(self.ccSphereNodePath2, base.camera) self.camPusher2.setCenter(base.localAvatar) self.camFloorRayNode = base.localAvatar.attachNewNode('camFloorRayNode') self.ccRay = CollisionRay(0.0, 0.0, 0.0, 0.0, 0.0, -1.0) self.ccRayNode = CollisionNode('ccRayNode') self.ccRayNode.addSolid(self.ccRay) self.ccRayNodePath = self.camFloorRayNode.attachNewNode(self.ccRayNode) self.ccRayBitMask = CIGlobals.FloorBitmask self.ccRayNode.setFromCollideMask(self.ccRayBitMask) self.ccRayNode.setIntoCollideMask(BitMask32.allOff()) self.ccTravFloor = CollisionTraverser('LocalAvatar.ccTravFloor') self.camFloorCollisionQueue = CollisionHandlerQueue() self.ccTravFloor.addCollider(self.ccRayNodePath, self.camFloorCollisionQueue) self.ccTravOnFloor = CollisionTraverser('LocalAvatar.ccTravOnFloor') self.ccRay2 = CollisionRay(0.0, 0.0, 0.0, 0.0, 0.0, -1.0) self.ccRay2Node = CollisionNode('ccRay2Node') self.ccRay2Node.addSolid(self.ccRay2) self.ccRay2NodePath = self.camFloorRayNode.attachNewNode(self.ccRay2Node) self.ccRay2BitMask = CIGlobals.FloorBitmask self.ccRay2Node.setFromCollideMask(self.ccRay2BitMask) self.ccRay2Node.setIntoCollideMask(BitMask32.allOff()) self.ccRay2MoveNodePath = hidden.attachNewNode('ccRay2MoveNode') self.camFloorCollisionBroadcaster = CollisionHandlerFloor() self.camFloorCollisionBroadcaster.setInPattern('on-floor') self.camFloorCollisionBroadcaster.setOutPattern('off-floor') self.camFloorCollisionBroadcaster.addCollider(self.ccRay2NodePath, self.ccRay2MoveNodePath) self.cTrav.addCollider(self.ccRay2NodePath, self.camFloorCollisionBroadcaster) self.initialized = True def deleteSmartCameraCollisions(self): del self.ccTrav del self.ccLine del self.ccLineNode self.ccLineNodePath.removeNode() del self.ccLineNodePath del self.camCollisionQueue del self.ccRay del self.ccRayNode self.ccRayNodePath.removeNode() del self.ccRayNodePath del self.ccRay2 del self.ccRay2Node self.ccRay2NodePath.removeNode() del self.ccRay2NodePath self.ccRay2MoveNodePath.removeNode() del self.ccRay2MoveNodePath del self.ccTravOnFloor del self.ccTravFloor del self.camFloorCollisionQueue del self.camFloorCollisionBroadcaster del self.ccSphere del self.ccSphereNode self.ccSphereNodePath.removeNode() del self.ccSphereNodePath del self.camPusher del self.ccPusherTrav del self.ccSphere2 del self.ccSphereNode2 self.ccSphereNodePath2.removeNode() del self.ccSphereNodePath2 del self.camPusher2 self.initialized = False def startUpdateSmartCamera(self): if self.started: return self.__floorDetected = 0 self.__cameraHasBeenMoved = 1 self.recalcCameraSphere() self.__instantaneousCamPos = camera.getPos() self.cTrav.addCollider(self.ccSphereNodePath, self.camPusher) self.ccTravOnFloor.addCollider(self.ccRay2NodePath, self.camFloorCollisionBroadcaster) self.__disableSmartCam = 0 self.__lastPosWrtRender = camera.getPos(render) + 1 self.__lastHprWrtRender = camera.getHpr(render) + 1 taskName = base.localAvatar.taskName('updateSmartCamera') taskMgr.remove(taskName) taskMgr.add(self.updateSmartCamera, taskName, priority=47) self.started = True def stopUpdateSmartCamera(self): self.cTrav.removeCollider(self.ccSphereNodePath) self.ccTravOnFloor.removeCollider(self.ccRay2NodePath) taskName = base.localAvatar.taskName('updateSmartCamera') taskMgr.remove(taskName) camera.setPos(self.getIdealCameraPos()) self.started = False def updateSmartCamera(self, task): if not self.__camCollCanMove and not self.__cameraHasBeenMoved: if self.__lastPosWrtRender == camera.getPos(render): if self.__lastHprWrtRender == camera.getHpr(render): return Task.cont self.__cameraHasBeenMoved = 0 self.__lastPosWrtRender = camera.getPos(render) self.__lastHprWrtRender = camera.getHpr(render) self.__idealCameraObstructed = 0 if not self.__disableSmartCam: self.ccTrav.traverse(self.__geom) if self.camCollisionQueue.getNumEntries() > 0: try: self.camCollisionQueue.sortEntries() self.handleCameraObstruction(self.camCollisionQueue.getEntry(0)) except AssertionError: pass if not self.__onLevelGround: self.handleCameraFloorInteraction() if not self.__idealCameraObstructed: self.nudgeCamera() if not self.__disableSmartCam: self.ccPusherTrav.traverse(self.__geom) self.putCameraFloorRayOnCamera() self.ccTravOnFloor.traverse(self.__geom) return Task.cont def positionCameraWithPusher(self, pos, lookAt): camera.setPos(pos) self.ccPusherTrav.traverse(self.__geom) camera.lookAt(lookAt) def nudgeCamera(self): CLOSE_ENOUGH = 0.1 curCamPos = self.__instantaneousCamPos curCamHpr = camera.getHpr() targetCamPos = self.getCompromiseCameraPos() targetCamLookAt = self.getLookAtPoint() posDone = 0 if Vec3(curCamPos - targetCamPos).length() <= CLOSE_ENOUGH: camera.setPos(targetCamPos) posDone = 1 camera.setPos(targetCamPos) camera.lookAt(targetCamLookAt) targetCamHpr = camera.getHpr() hprDone = 0 if Vec3(curCamHpr - targetCamHpr).length() <= CLOSE_ENOUGH: hprDone = 1 if posDone and hprDone: return lerpRatio = 0.15 lerpRatio = 1 - pow(1 - lerpRatio, globalClock.getDt() * 30.0) self.__instantaneousCamPos = targetCamPos * lerpRatio + curCamPos * (1 - lerpRatio) if self.__disableSmartCam or not self.__idealCameraObstructed: newHpr = targetCamHpr * lerpRatio + curCamHpr * (1 - lerpRatio) else: newHpr = targetCamHpr camera.setPos(self.__instantaneousCamPos) camera.setHpr(newHpr) def popCameraToDest(self): newCamPos = self.getCompromiseCameraPos() newCamLookAt = self.getLookAtPoint() self.positionCameraWithPusher(newCamPos, newCamLookAt) self.__instantaneousCamPos = camera.getPos() def handleCameraObstruction(self, camObstrCollisionEntry): collisionPoint = camObstrCollisionEntry.getSurfacePoint(self.ccLineNodePath) collisionVec = Vec3(collisionPoint - self.ccLine.getPointA()) distance = collisionVec.length() self.__idealCameraObstructed = 1 self.closestObstructionDistance = distance self.popCameraToDest() def handleCameraFloorInteraction(self): self.putCameraFloorRayOnCamera() self.ccTravFloor.traverse(self.__geom) if self.__onLevelGround: return if self.camFloorCollisionQueue.getNumEntries() == 0: return self.camFloorCollisionQueue.sortEntries() camObstrCollisionEntry = self.camFloorCollisionQueue.getEntry(0) camHeightFromFloor = camObstrCollisionEntry.getSurfacePoint(self.ccRayNodePath)[2] self.cameraZOffset = camera.getPos()[2] + camHeightFromFloor if self.cameraZOffset < 0: self.cameraZOffset = 0 if self.__floorDetected == 0: self.__floorDetected = 1 self.popCameraToDest()
class PositionExaminer(DirectObject, NodePath): def __init__(self): try: self.__initialized return except: self.__initialized = 1 NodePath.__init__(self, hidden.attachNewNode('PositionExaminer')) self.cRay = CollisionRay(0.0, 0.0, 6.0, 0.0, 0.0, -1.0) self.cRayNode = CollisionNode('cRayNode') self.cRayNode.addSolid(self.cRay) self.cRayNodePath = self.attachNewNode(self.cRayNode) self.cRayNodePath.hide() self.cRayBitMask = CIGlobals.FloorBitmask self.cRayNode.setFromCollideMask(self.cRayBitMask) self.cRayNode.setIntoCollideMask(BitMask32.allOff()) self.cSphere = CollisionSphere(0.0, 0.0, 0.0, 1.5) self.cSphereNode = CollisionNode('cSphereNode') self.cSphereNode.addSolid(self.cSphere) self.cSphereNodePath = self.attachNewNode(self.cSphereNode) self.cSphereNodePath.hide() self.cSphereBitMask = CIGlobals.WallBitmask self.cSphereNode.setFromCollideMask(self.cSphereBitMask) self.cSphereNode.setIntoCollideMask(BitMask32.allOff()) self.ccLine = CollisionSegment(0.0, 0.0, 0.0, 1.0, 0.0, 0.0) self.ccLineNode = CollisionNode('ccLineNode') self.ccLineNode.addSolid(self.ccLine) self.ccLineNodePath = self.attachNewNode(self.ccLineNode) self.ccLineNodePath.hide() self.ccLineBitMask = CIGlobals.CameraBitmask self.ccLineNode.setFromCollideMask(self.ccLineBitMask) self.ccLineNode.setIntoCollideMask(BitMask32.allOff()) self.cRayTrav = CollisionTraverser('PositionExaminer.cRayTrav') self.cRayTrav.setRespectPrevTransform(False) self.cRayQueue = CollisionHandlerQueue() self.cRayTrav.addCollider(self.cRayNodePath, self.cRayQueue) self.cSphereTrav = CollisionTraverser('PositionExaminer.cSphereTrav') self.cSphereTrav.setRespectPrevTransform(False) self.cSphereQueue = CollisionHandlerQueue() self.cSphereTrav.addCollider(self.cSphereNodePath, self.cSphereQueue) self.ccLineTrav = CollisionTraverser('PositionExaminer.ccLineTrav') self.ccLineTrav.setRespectPrevTransform(False) self.ccLineQueue = CollisionHandlerQueue() self.ccLineTrav.addCollider(self.ccLineNodePath, self.ccLineQueue) def delete(self): del self.cRay del self.cRayNode self.cRayNodePath.removeNode() del self.cRayNodePath del self.cSphere del self.cSphereNode self.cSphereNodePath.removeNode() del self.cSphereNodePath del self.ccLine del self.ccLineNode self.ccLineNodePath.removeNode() del self.ccLineNodePath del self.cRayTrav del self.cRayQueue del self.cSphereTrav del self.cSphereQueue del self.ccLineTrav del self.ccLineQueue def consider(self, node, pos, eyeHeight): self.reparentTo(node) self.setPos(pos) result = None self.cRayTrav.traverse(render) if self.cRayQueue.getNumEntries() != 0: self.cRayQueue.sortEntries() floorPoint = self.cRayQueue.getEntry(0).getSurfacePoint(self.cRayNodePath) if abs(floorPoint[2]) <= 4.0: pos += floorPoint self.setPos(pos) self.cSphereTrav.traverse(render) if self.cSphereQueue.getNumEntries() == 0: self.ccLine.setPointA(0, 0, eyeHeight) self.ccLine.setPointB(-pos[0], -pos[1], eyeHeight) self.ccLineTrav.traverse(render) if self.ccLineQueue.getNumEntries() == 0: result = pos self.reparentTo(hidden) self.cRayQueue.clearEntries() self.cSphereQueue.clearEntries() self.ccLineQueue.clearEntries() return result
class RoamingRalphDemo(ShowBase): def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) self.orbCollisionHandler = CollisionHandlerQueue() self.cTrav = CollisionTraverser() self.cTrav.setRespectPrevTransform(True) self.startgame = False self.sound=loader.loadSfx("models/0614.ogg") self.sound2=loader.loadSfx("models/01-main-theme.mp3") self.sound2.play() status=self.sound2.status() #hbPath = NodePath() utils.setUpKeys(self) utils.loadModels(self) utils.setUpLighting(self) #utils.setUpFloatingSpheres(self) utils.setUpRalphsShot(self) utils.setUpCamera(self) utils.setUpCollisionSpheres(self) self.healthTxt = utils.addInstructions(.06,"Health: 100") self.orbTxt = utils.addInstructions(.18,"Orbs: 0") self.hitsTxt = utils.addInstructions(.28,"Enemy Hits: 0") self.strHealthStatus = str(self.healthTxt) # Create a frame frame = DirectFrame(text = "main", scale = 0.001) # Add button self.flagstartbutton = 0 self.imageObject = OnscreenImage(image = 'models/instapage.jpg', pos = (0, 0, 0), scale=1.1) self.imageObject2 = OnscreenImage(image = 'models/gap.jpg', pos = (-2.15, 0, 0), scale=1.1) self.imageObject3 = OnscreenImage(image = 'models/gap.jpg', pos = (2.15, 0, 0), scale=1.1) self.helpOn = DirectButton(text = ("Start", "on/off", "Start", "disabled"), scale=.10, pos=(-1.1,0,-.9), command=utils.buttonClickedOn, extraArgs=[self, self.imageObject,self.imageObject2,self.imageObject3, self.flagstartbutton]) #helpOff = DirectButton(text = ("helpOff", "on/off", "helpOff", "disabled"), scale=.10, pos=(-0.5,0,-1), command=utils.buttonClickedOff, extraArgs=[self, self.imageObject, self.buttonflag]) # mytimer = DirectLabel() # mytimer.reparentTo(render) # mytimer.setY(7) #Create 4 buttons #print self.strHealthStatus #incBar(100) self.vec = LVector3(0,1,0)#vector for pawns shot # Create a frame #frame = DirectFrame(text = "main", scale = 0.001) # Add button #bar = DirectWaitBar(text = "", value = 50, pos = (0,.4,.4)) #bar.reparent(render) # Game state variables self.isMoving = False self.jumping = False self.vz = 0 self.numOrbs = 0 self.healthCount = 100 self.enemyhits = 0 #self.shotList = [] #self.sphere = CollisionBox((self.ralph.getX() + -10,self.ralph.getY(),self.ralph.getZ()),10,10,10) self.ralphBox1 = CollisionBox((0,2.5,3.5),1.5,0.5,1.5) cnodepath = self.ralph.attachNewNode((CollisionNode("ralphColNode"))) cnodepath.node().addSolid(self.ralphBox1) cnodepath.node().addSolid(CollisionBox((0,-2.5,3.5),1.5,0.5,1.5)) cnodepath.node().addSolid(CollisionBox((2.5,0,3.5),0.5,1.5,1.5)) cnodepath.node().addSolid(CollisionBox((-2.5,0,3.5),0.5,1.5,1.5)) #cnodepath.show() #self.cTrav.addCollider(cnodepath, self.orbCollisionHandler) self.sphere = CollisionSphere(0,-5,4,3) self.sphere3 = CollisionSphere(0,5,5,3) self.sphere4 = CollisionSphere(-4,0,5,2) self.sphere5 = CollisionSphere(4,0,5,2) self.sphere2 = CollisionSphere(0,0,3,2) self.cnodePath = self.ralph.attachNewNode((CollisionNode("ralphColNode"))) self.cnodePath2 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck"))) self.cnodePath3 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck2"))) self.cnodePath4 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck3"))) self.cnodePath5 = self.ralph.attachNewNode((CollisionNode("ralphWallCheck4"))) self.cnodePath.node().addSolid(self.sphere2) self.cnodePath2.node().addSolid(self.sphere) self.cnodePath3.node().addSolid(self.sphere3) self.cnodePath4.node().addSolid(self.sphere4) self.cnodePath5.node().addSolid(self.sphere5) #self.cnodePath.node().addSolid(self.sphere2) #self.cnodePath.show()#ralph pusher #self.cnodePath2.show() #self.cnodePath3.show() #self.cnodePath4.show() #self.cnodePath5.show() self.cTrav.addCollider(self.cnodePath2, self.orbCollisionHandler) self.cTrav.addCollider(self.cnodePath3, self.orbCollisionHandler) self.cTrav.addCollider(self.cnodePath4, self.orbCollisionHandler) self.cTrav.addCollider(self.cnodePath5, self.orbCollisionHandler) self.pusher = CollisionHandlerPusher() self.pusher.addCollider(self.cnodePath, self.ralph) #self.cTrav.addCollider(self.cnodePath, self.ralphCollisionHandler) self.cTrav.addCollider(self.cnodePath, self.pusher) self.chrisLastShotTime = globalClock.getFrameTime() self.chrisTimer = globalClock.getDt() #def __init__(self, pos,showbase, colPathName, dir, length): self.chrisList = [utils.cheken((-249,419,0),self,"chrisColPath0","X",5), #earthroom utils.chris((-404,343,2),self,"chrisColPath1","X",5), #yellowroom utils.fetus((-141,-69,1),self,"chrisColPath2","X",5), #lightblueroom utils.cheken((-277,356,0),self,"chrisColPath3","Y",5), #between earth and y utils.rose((-102,-5,1),self,"chrisColPath4","Y",5), #between r and lb utils.cheken((-133,83,0),self,"chrisColPath5","Y",5), #blue hall utils.fetus((-246,280,1),self,"chrisColPath6","X",5), #earth hall utils.cheken((-330,241,0),self,"chrisColPath7","X",5), #yellow hall utils.chris((-60,110,2),self,"chrisColPath8","Y",5), #red hall cheken z 0 utils.fetus((-75,52,1),self, "chrisColPath9", "X", 5), utils.cheken((-75,141,0),self, "chrisColPath10", "X", 5), utils.rose((-302,202,1),self,"chrisColPath11","X",5), utils.chris((-303,304,2),self,"chrisColPath12","Y",5) ] #rose z = 1 #cheken z = 0 #chris z = 2 #fetus z = 1 #def _init_(self,showbase,pos,color,speed,radius): self.orbList = [utils.orb(self,( 18, 29,2.5),(1,0,0,1),20,2.5), #first red utils.orb(self,( -249, 419,2.5),(1,1,1,1),20,2.5),#earthroom utils.orb(self,( -404, 343,2.5),(1,1,0,1),20,2.5), #yellowroom utils.orb(self,( -141, -69,2.5),(0,0,1,1),20,2.5),#light blue room utils.orb(self,( -277, 356,2.5),(1,1,0,1),20,2.5), #between y and earth utils.orb(self,( -102, -5,2.5),(0,0,1,1),20,2.5), #between red and lb utils.orb(self,( -135, 22,2.5),(0,0,1,1),20,2.5), #lb hall utils.orb(self,( -248, 329,2.5),(1,1,1,1),20,2.5), #earthhall utils.orb(self,( -330, 241,2.5),(1,1,0,1),20,2.5), #yellow hall utils.orb(self,( -60, 110,2.5),(1,0,0,1),20,2.5) #red hall ] self.donutList = [utils.donut(self, (0,0,1),20, 2.5), utils.donut(self,( -330, 250,2.5),20,2.5), #yellow hall utils.donut(self,( -141, -80,2.5),20,2.5),#light blue room utils.donut(self,( -249, 430,2.5),20,2.5),#earthroom utils.donut(self,( -102, -10,2.5),20,2.5), #between red and lb ] self.cameraCollided = False self.ralphSpeed = 60 self.ralphHit = False self.ralphRedTime = 0 self.textTime = -1 self.textTime2 = -1 self.textTime3 = -1 self.mTextPath = utils.addInstructions2(.44,"") self.mTextPath2 = utils.addInstructions2(.55,"") self.winText2 = utils.addInstructions2(.55, "") self.timerText = utils.addInstructions4(.26,"0:00") self.introText = utils.addInstructions2(.55,"") self.minutes = 4 self.seconds = 0 self.timerTime = globalClock.getFrameTime() taskMgr.add(self.move, "moveTask") taskMgr.add(self.moveChris,"moveChrisTask") taskMgr.add(self.timerTask,"timerTask") #taskMgr.add(self.timerTask, "timerTask") # Records the state of the arrow keys def setKey(self, key, value): self.keyMap[key] = value def clickResponse(): pass #startgame=1; def timerTask(self,task): if self.startgame == False: return task.cont dt = globalClock.getFrameTime() if dt - self.timerTime > 1: self.seconds -= 1 if self.seconds == -1: self.seconds = 59 self.minutes -=1 self.timerText.destroy() if self.seconds < 10: str1 = "0" + str(self.minutes) + ":0" + str(self.seconds) else: str1 = "0" + str(self.minutes) + ":" + str(self.seconds) self.timerText = utils.addInstructions4(.26,str1) self.timerTime = globalClock.getFrameTime() - ((dt - self.timerTime) - 1) if self.minutes == 0 and self.seconds == 0: self.startgame = False #utils.addInstructions3(.45,"You Lose") self.imageObject2 = OnscreenImage(image = 'models/gameover.jpg', pos = (0, 0, 0), scale=1.1) self.imageObject2 = OnscreenImage(image = 'models/gap.jpg', pos = (-2.15, 0, 0), scale=1.1) self.imageObject3 = OnscreenImage(image = 'models/gap.jpg', pos = (2.15, 0, 0), scale=1.1) return task.cont def moveChris(self,task): if self.startgame == False: return task.cont else: dt = globalClock.getDt() self.gianteye.setH(self.gianteye.getH() + 100 * dt) for chris in self.chrisList: chris.moveChris(dt,self,self.chrisList) return task.cont # Accepts arrow keys to move either the player or the menu cursor, # Also deals with grid checking and collision detection def move(self, task): if self.sound2.status() != self.sound2.PLAYING: self.sound2.play() if self.startgame == False: return task.cont else: # Get the time that elapsed since last frame. We multiply this with # the desired speed in order to find out with which distance to move # in order to achieve that desired speed. dt = globalClock.getDt() dt2 = globalClock.getFrameTime() #utils.moveChris(self,dt) #self.chris2.moveChris(dt,self) #self.startEnemyThread() if dt2 - self.textTime > 2 and self.textTime != -1: self.textTime = -1; self.mTextPath.destroy() if dt2 - self.textTime2 > 2 and self.textTime2 != -1: self.textTime2 = -1; self.mTextPath2.destroy() if dt2 - self.textTime3 > 5 and self.textTime3 != -1: self.textTime3 = -1; self.introText.destroy() if globalClock.getFrameTime()- self.ralphRedTime > .3 and self.ralphHit == True: self.ralph.clearColor() self.ralphHit = False # If the camera-left key is pressed, move camera left. # If the camera-right key is pressed, move camera right. if self.keyMap["cam-left"]: self.camera.setZ(self.camera, -20 * dt) if self.keyMap["cam-right"]: self.camera.setZ(self.camera, +20 * dt) # save ralph's initial position so that we can restore it, # in case he falls off the map or runs into something. startpos = self.ralph.getPos() # If a move-key is pressed, move ralph in the specified direction. if self.keyMap["left"]: self.ralph.setH(self.ralph.getH() + 75 * dt) #self.camera.setX(self.camera, +15.5 * dt) if self.keyMap["right"]: self.ralph.setH(self.ralph.getH() - 75 * dt) #self.camera.setX(self.camera, -15.5 * dt) if self.keyMap["forward"]:#-1 self.ralph.setFluidY(self.ralph, -1*self.ralphSpeed * dt) #self.camera.setY(self.camera, -35 * dt) if self.keyMap["back"]: self.ralph.setFluidY(self.ralph, self.ralphSpeed * dt) #self.camera.setY(self.camera, 35 * dt) if self.keyMap["space"]: if self.jumping is False: #self.ralph.setZ(self.ralph.getZ() + 100 * dt) self.jumping = True self.vz = 8 if self.keyMap["enter"]: self.keyMap["enter"] = False self.sound.play() self.shotList[self.shotCount].lpivot.setPos(self.ralph.getPos()) self.shotList[self.shotCount].lpivot.setZ(self.ralph.getZ() + .5) self.shotList[self.shotCount].lpivot.setX(self.ralph.getX() - .25) print self.ralph.getPos() #self.shotList.append(rShot) #self.lightpivot3.setPos(self.ralph.getPos()) #self.lightpivot3.setZ(self.ralph.getZ() + .5) #self.lightpivot3.setX(self.ralph.getX() - .25) #self.myShot.setHpr(self.ralph.getHpr()) #parent to ralph #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,-1,0)) #self.myShotVec = vec node = NodePath("tmp") node.setHpr(self.ralph.getHpr()) vec = render.getRelativeVector(node,(0,-1,0)) self.shotList[self.shotCount].vec = vec self.shotCount = (self.shotCount + 1) % 10 else: self.sound.stop() for rs in self.shotList: rs.lpivot.setPos(rs.lpivot.getPos() + rs.vec * dt * 25 ) #if shot is too far stop updating if self.jumping is True: self.vz = self.vz - 16* dt self.ralph.setZ(self.ralph.getZ() + self.vz * dt ) if self.ralph.getZ() < 0: self.ralph.setZ(0) self.jumping = False else: if self.ralph.getZ() < 0.25: self.ralph.setZ(0.25) elif self.ralph.getZ() > 0.25: self.ralph.setZ(self.ralph.getZ() -7 * dt) # If ralph is moving, loop the run animation. # If he is standing still, stop the animation. if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["space"] or self.keyMap["forward"] or self.keyMap["back"]: if self.isMoving is False: self.ralph.loop("run") self.isMoving = True else: if self.isMoving: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False # update pawns shot or set up new shot after it reaches a certain distance node = NodePath("tmp") node.setHpr(self.pawn.getHpr()) vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0)) self.shot.setPos(self.shot.getPos() + self.vec * dt * 10 ) if self.shot.getY() < -15 or self.shot.getY() > 30 or self.shot.getX() < 5 or self.shot.getX() > 15: self.shot.setPos(self.pawn.getPos() + (0,0,0)) self.vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0)) self.vec = render.getRelativeVector(node,(random.random() * random.randrange(-1,2),random.random() + 1,0)) # If the camera is too far from ralph, move it closer. # If the camera is too close to ralph, move it farther. #self.camera.lookAt(self.floater) camvec = self.ralph.getPos() - self.camera.getPos() #camvec = Vec3(0,camvec.getY(),0) camdist = camvec.length() x = self.camera.getZ() camvec.normalize() #if camdist > 6.0: # self.camera.setPos(self.camera.getPos() + camvec * (camdist - 6)) #if camdist < 6.0: # self.camera.setPos(self.camera.getPos() - camvec * (6 - camdist)) # Normally, we would have to call traverse() to check for collisions. # However, the class ShowBase that we inherit from has a task to do # this for us, if we assign a CollisionTraverser to self.cTrav. #self.cTrav.traverse(render) # Adjust camera so it stays at same height if self.cameraCollided == False: if self.camera.getZ() < self.ralph.getZ() + 1 or self.camera.getZ() > self.ralph.getZ() + 1: self.camera.setZ(self.ralph.getZ() + 1) # The camera should look in ralph's direction, # but it should also try to stay horizontal, so look at # a floater which hovers above ralph's head. self.camera.lookAt(self.floater) entries = list(self.orbCollisionHandler.getEntries()) if(len(entries) > 0): #self.lightpivot.reparentTo(NodePath()) orbCollected = False self.cameraCollided = False self.ralphSpeed = 85 ralphHit = False for entry in self.orbCollisionHandler.getEntries(): #print(entry) fromColNp = entry.getFromNodePath() toColNp = entry.getIntoNodePath() if fromColNp.getName() == "orbColPath" and toColNp.getName() == "ralphColNode": if orbCollected == False: fromColNp.getParent().reparentTo(NodePath()) self.orbTxt.destroy() self.numOrbs += 1 str1 = "Orbs: " + str(self.numOrbs) self.orbTxt = utils.addInstructions(.18, str1) orbCollected = True elif toColNp.getName() == "orbColPath" and fromColNp.getName() == "ralphColNode": if orbCollected == False: toColNp.getParent().reparentTo(NodePath()) self.orbTxt.destroy() self.numOrbs += 1 str1 = "Orbs: " + str(self.numOrbs) self.orbTxt = utils.addInstructions(.18, str1) orbCollected = True elif fromColNp.getName() == "donutCollisionNode" and toColNp.getName() == "ralphColNode": fromColNp.getParent().reparentTo(NodePath()) self.healthCount += 15 if(self.healthCount > 100): self.healthCount = 100 self.healthTxt.destroy() str1 = "Health: " + str(self.healthCount) self.healthTxt = utils.addInstructions(.06, str1) elif toColNp.getName() == "donutCollisionNode" and fromColNp.getName() == "ralphColNode": toColNp.getParent().reparentTo(NodePath()) self.healthCount += 15 if(self.healthCount > 100): self.healthCount = 100 self.healthTxt.destroy() str1 = "Health: " + str(self.healthCount) self.healthTxt = utils.addInstructions(.06, str1) elif toColNp.getName() == "ralphOrbColPath" and (fromColNp.getName()[:-1] == "chrisColPath" or fromColNp.getName()[:-2] == "chrisColPath"): toColNp.getParent().setZ(20) for chriss in self.chrisList: if chriss.chrisColName == fromColNp.getName(): chris = chriss break chris.chrisHealth = chris.chrisHealth - 1 chris.chris.setColor(1,0,0,1) chris.chrisHit = True chris.chrisRedTime = globalClock.getFrameTime() #print chris.chrisRedTime if chris.chrisHealth < 0 and chris.chrisAlive == True: fromColNp.getParent().removeNode() chris.chrisAlive = False self.hitsTxt.destroy() self.enemyhits += 1 str1 = "Enemy Hits: " + str(self.enemyhits) self.hitsTxt = utils.addInstructions(.28, str1) chris.chrisShot.setZ(26) elif (toColNp.getName()[:-1] == "chrisColPath" or toColNp.getName()[:-2] == "chrisColPath") and fromColNp.getName() == "ralphOrbColPath": fromColNp.getParent().setZ(20) for chriss in self.chrisList: if chriss.chrisColName == toColNp.getName(): chris = chriss break chris.chrisHealth = chris.chrisHealth - 1 chris.chris.setColor(1,0,0,1) chris.chrisHit = True chris.chrisRedTime = globalClock.getFrameTime() #print chris.chrisRedTime if chris.chrisHealth < 0 and chris.chrisAlive == True: toColNp.getParent().removeNode() chris.chrisAlive = False self.hitsTxt.destroy() self.enemyhits += 1 str1 = "Enemy Hits: " + str(self.enemyhits) self.hitsTxt = utils.addInstructions(.28, str1) chris.chrisShot.setZ(26) elif toColNp.getName() == "enemyOrbColPath" and fromColNp.getName() == "ralphColNode": if ralphHit == False: toColNp.getParent().setZ(26) self.healthTxt.destroy() self.healthCount -= 5 str1 = "Health: " + str(self.healthCount) self.healthTxt = utils.addInstructions(.06, str1) self.ralphHit = True self.ralph.setColor((1,0,0,1)) self.ralphRedTime = globalClock.getFrameTime() if self.healthCount <= 0: self.startgame = False #utils.addInstructions3(.45,"You Lose") self.imageObject2 = OnscreenImage(image = 'models/gameover.jpg', pos = (0, 0, 0), scale=1.1) self.imageObject2 = OnscreenImage(image = 'models/gap.jpg', pos = (-2.15, 0, 0), scale=1.1) self.imageObject3 = OnscreenImage(image = 'models/gap.jpg', pos = (2.15, 0, 0), scale=1.1) elif toColNp.getName() == "ralphColNode" and fromColNp.getName() == "enemyOrbColPath": fromColNp.getParent().setZ(26) if ralphHit == False: self.healthTxt.destroy() self.healthCount -= 5 str1 = "Health: " + str(self.healthCount) self.healthTxt = utils.addInstructions(.06, str1) self.ralphHit = True self.ralph.setColor((1,0,0,1)) self.ralphRedTime = globalClock.getFrameTime() ralphHit = True if self.healthCount <= 0: self.startgame = False #utils.addInstructions3(.45,"You Lose") self.imageObject2 = OnscreenImage(image = 'models/gameover.jpg', pos = (0, 0, 0), scale=1.1) self.imageObject2 = OnscreenImage(image = 'models/gap.jpg', pos = (-2.15, 0, 0), scale=1.1) self.imageObject3 = OnscreenImage(image = 'models/gap.jpg', pos = (2.15, 0, 0), scale=1.1) elif toColNp.getName() == "ralphColNode" and fromColNp.getName() == "portalColPath": if self.numOrbs < 3 and self.enemyhits < 4: self.mTextPath.destroy() self.mTextPath = utils.addInstructions2(.30, "Not enough orbs.") self.textTime = globalClock.getFrameTime() self.mTextPath2.destroy() self.mTextPath2 = utils.addInstructions2(.45, "Not enough kills.") self.textTime2 = globalClock.getFrameTime() elif self.numOrbs < 3: self.mTextPath.destroy() self.mTextPath = utils.addInstructions2(.30, "Not enough orbs.") self.textTime = globalClock.getFrameTime() elif self.enemyhits < 4: self.mTextPath2.destroy() self.mTextPath2 = utils.addInstructions2(.45, "Not enough kills.") self.textTime2 = globalClock.getFrameTime() else: self.winText = utils.addInstructions3(.45, "You Win") self.startgame = False #self.ralph.setPos(-196, 177, 3) if self.isMoving == True: self.ralph.stop() self.ralph.pose("walk", 5) self.isMoving = False elif fromColNp.getName() == "ralphOrbColPath" and toColNp.getName() == "allinclusive": fromColNp.getParent().setZ(50) elif toColNp.getName() == "ralphOrbColPath" and fromColNp.getName() == "allinclusive": toColNp.getParent().setZ(50) elif fromColNp.getName() == "enemyOrbWallCheck" and toColNp.getName() == "allinclusive": fromColNp.getParent().setZ(50) #print toColNp.getName() elif toColNp.getName() == "enemyOrbWallCheck" and fromColNp.getName() == "allinclusive": toColNp.getParent().setZ(50) #print fromColNp.getName() elif fromColNp.getName() == "ralphWallCheck" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,-1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 60 elif toColNp.getName() == "ralphWallCheck" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,-1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #print "wtf" #toColNp.getParent().setZ(26) self.ralphSpeed = 60 elif fromColNp.getName() == "ralphWallCheck2" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 60 elif toColNp.getName() == "ralphWallCheck2" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(0,1,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #self.camera.setPos(self.ralph.getPos()) #self.cameraCollided = True self.ralphSpeed = 60 elif fromColNp.getName() == "ralphWallCheck3" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(-1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 60 elif toColNp.getName() == "ralphWallCheck3" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(-1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #self.camera.setPos(self.ralph.getPos()) #self.cameraCollided = True self.ralphSpeed = 60 elif fromColNp.getName() == "ralphWallCheck4" and toColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #fromColNp.getParent().setZ(26) self.ralphSpeed = 60 elif toColNp.getName() == "ralphWallCheck4" and fromColNp.getName() == "allinclusive": #node = NodePath("tmp") #node.setHpr(self.ralph.getHpr()) #vec = render.getRelativeVector(node,(1,0,0)) #self.ralph.setPos(self.ralph.getPos()-vec) #self.camera.setPos(self.ralph.getPos()) #self.cameraCollided = True self.ralphSpeed = 60 utils.updateHealthBar(self.healthCount, self.bar) #utils.turnofstartbutton(self.flagstartbutton) #if self.flagstartbutton ==1: # self.helpOn.destory() return task.cont
class MetalSlender(ShowBase): VERSION=0.1 GRAVITY = 9.81 def __init__(self): ShowBase.__init__(self) self.initVideo() self.initGame() def initVideo(self): self.render.setShaderAuto() #TODO: Not working self.render.setAntialias(AntialiasAttrib.MMultisample) self.props = WindowProperties() # self.props.setFullscreen(True) # self.props.setSize(1920, 1080) self.props.setSize(1280, 720) self.props.setCursorHidden(False) self.props.setMouseMode(self.props.M_absolute) self.win.requestProperties(self.props) self.win.movePointer(0, 100, 100) def initGame(self): self.paused = False self.initTimer = True self.time = 0 self.gameOver = True # self.setFrameRateMeter(True) self.taskMgr.add(self.menuDisplay, "menuDisplay") self.mainMenu = MainMenu(self) self.introSound = self.loader.loadSfx('assets/sounds/intro.mp3') self.introSound.setLoop(True) self.introSound.play() #TODO: Refactor environment into a class that inherits from nodepath def setupEnvironment(self): self.setBackgroundColor(0,0,0) self.setupLighting() self.setupFog() self.setupSkydome() self.setupPhysics() def setupFog(self): self.fog = Fog("fog") self.fog.setColor(FOG_COLOR) self.fog.setExpDensity(FOG_EXP_DENSITY) self.render.setFog(self.fog) def setupSkydome(self): self.skydome = self.loader.loadModel(EGG_SKYDOME) self.skydome.setBin('background', 0) self.skydome.setDepthWrite(False) self.skydome.reparentTo(self.cam) self.skydome.setCompass() self.skydome.setLight(self.shadeless) self.skydome.setScale(20) def setupLighting(self): alight = AmbientLight("AmbientLight") alight.setColor(AMBIENT_LIGHT) self.amblight = self.render.attachNewNode(alight) self.render.setLight(self.amblight) alight = AmbientLight("ShadelessLight") alight.setColor((1.0, 1.0, 1.0, 1.0)) self.shadeless = self.render.attachNewNode(alight) def setupPhysics(self): self.cTrav = CollisionTraverser() plane = self.render.attachNewNode(CollisionNode('WorldBottom')) plane.node().addSolid(CollisionPlane(Plane(0, 0, 1, 30))) plane.node().setIntoCollideMask(CollisionMask.SCENE) #TODO: Set the scenario's into collide mask to a special value def loadScenario(self): self.rooms = [] self.rooms.append(Room(self, self.render, "LCG" , "assets/chicken/lcg" )) self.rooms.append(Room(self, self.render, "Bloco H" , "assets/chicken/blocoh" )) self.rooms.append(Room(self, self.render, "Bloco H2" , "assets/chicken/blocoh2")) self.rooms.append(Room(self, self.render, "Collision", "assets/chicken/collision" )) self.rooms[-1].root.setCollideMask(CollisionMask.SCENE) def addCommands(self): self.accept('escape', self.userExit) self.accept('g', self.endGame) self.accept('i', self.actionKeys, ['i']) self.accept('p', self.pauseGame) self.accept('z', self.restartGame) self.cTrav.setRespectPrevTransform(True) def addTasks(self): self.taskMgr.add(self.camctrl.update, "camera/control") self.taskMgr.add(self.player.updateAll, "player/update") self.taskMgr.add(self.hud.update, 'hud') self.taskMgr.add(self.player.flashlight.updatePower, 'player/flashlight/update') self.taskMgr.add(self.AIUpdate,"AIUpdate") self.taskMgr.add(self.camctrl.update, "camera/control") self.taskMgr.add(self.checkGoal, 'CheckGoal') def actionKeys(self, key): if key == 'i': self.player.fear = min(self.player.fear + 0.1, 1.0) def AIUpdate(self,task): pass hasAttacked = [] for enemy in self.enemies: attack = enemy.update() hasAttacked.append(attack) for i in hasAttacked: if (i == True): self.player.hurt()#TODO:The enemy itself should hurt the player #attack self.AIworld.update() if (self.player.isDead()): for enemy in self.enemies: enemy.stop() self.endGame() return task.done return task.cont def newGame(self): self.setupEnvironment() self.AIworld = AIWorld(self.render) self.introSound.stop() #TODO: Play creepy sound initialSound = loader.loadSfx('assets/sounds/enemies/nazgul_scream.mp3') initialSound.play() self.enemies = [] self.items = [] self.keys = [] #TODO: Many things are only done once the game is started # Load the scene. self.loadScenario() self.player = Player(self, self.render, 'Player', pos=Vec3(6, 1.44, -1.5)) self.actions = ActionManager(self, self.player, self.rooms) self.em = EventManager(self, self.player, self.actions, self.rooms) self.em.start() for enemy in self.enemies: enemy.getHooded().addIntruder(self.player) enemy.start() self.hud = HUD(self, self.player) self.controls = PlayerControls(self.player, self.actions) self.camctrl = CameraControls(self, self.player) self.props.setCursorHidden(True) self.win.requestProperties(self.props) self.mainMenu.hideNewGame() self.addTasks() self.addCommands() # self.cTrav = None def pauseGame(self): if (self.paused == True): self.props.setCursorHidden(True) self.win.requestProperties(self.props) self.mainMenu.hidePauseGame() self.paused = False self.events.start() self.taskMgr.add(self.player.updateAll, "player/update") self.taskMgr.add(self.hud.update, 'hud') self.taskMgr.add(self.player.flashlight.updatePower, 'player/flashlight/update') self.taskMgr.add(self.AIUpdate,"AIUpdate") self.taskMgr.add(self.camctrl.update, "camera/control") self.taskMgr.add(self.checkGoal, 'CheckGoal') self.accept('p', self.pauseGame) else: self.events.stop() self.ignore('p') self.player.pause() self.taskMgr.remove("camera/control") self.taskMgr.remove("player/update") self.taskMgr.remove('hud') self.player.resetLast() self.taskMgr.remove('player/flashlight/update') self.taskMgr.remove("AIUpdate") self.taskMgr.remove('CheckGoal') self.props.setCursorHidden(False) self.win.requestProperties(self.props) self.mainMenu.showPauseGame() self.paused = True def restartGame(self): self.events.stop() self.taskMgr.remove("camera/control") self.taskMgr.remove("player/update") self.taskMgr.remove('hud') self.taskMgr.remove('player/flashlight/update') self.taskMgr.remove("AIUpdate") self.taskMgr.remove('CheckGoal') self.cleanResources() self.props.setCursorHidden(False) self.win.requestProperties(self.props) self.initGame() def cleanResources(self): self.AIworld = None del self.enemies [:] del self.rooms [:] self.enemies = None self.rooms = None self.player = None self.actions = None self.events = None self.mainMenu = None self.fog = None self.skydome.removeNode() self.amblight.removeNode() self.shadeless.removeNode() self.target1.removeNode() self.target2.removeNode() self.banana.removeNode() self.skydome = None self.amblight = None self.shadeless = None self.target1 = None self.target2 = None self.banana = None self.hud = None self.camctrl = None self.controls = None self.cTrav.clearColliders() gc.collect() self.taskMgr.add(self.player.updateAll, "player/update") self.taskMgr.add(self.player.flashlight.updatePower, 'player/flashlight/update') self.taskMgr.add(self.AIUpdate,"AIUpdate") self.taskMgr.add(self.camctrl.update, "camera/control") self.taskMgr.add(self.playerUpdate, "playerUpdate") self.taskMgr.add(self.checkGoal, 'CheckGoal') def endGame(self): self.hud.hide() if (self.gameOver): self.image = OnscreenImage(image="assets/images/GameOver.png", pos = (0, 0, 0), parent=base.render2d, scale=(1,1,1)) else: self.image = OnscreenImage(image="assets/images/to-be-continued.jpg", pos = (0, 0, 0), parent=base.render2d, scale=(1,1,1)) self.startTimer(3) self.taskMgr.remove("camera/control") def menuDisplay(self, task): if (self.initTimer == False): hasFinished = self.timer() if (hasFinished): self.resetTimer() self.image.hide() self.props.setCursorHidden(False) self.props.setMouseMode(self.props.M_absolute) self.win.requestProperties(self.props) self.mainMenu.showNewGame() return task.cont def timer(self): currentTime = time.time() diff = currentTime - self.time if (diff > self.interval): self.resetTimer() return True else: return False def resetTimer(self): self.initTimer = True def startTimer(self, interval): if (self.initTimer == True): self.interval = interval self.initTimer = False self.time = time.time() def playerUpdate(self, task): reached = self.checkGoal() if (reached): # self.player.die() self.endGame() return task.done someKey = False for key in self.actions.keys: if (key.wasPicked()): someKey = True self.hud.setKey(someKey) return task.cont def checkGoal(self, task): close = not self.goal.isEmpty() and self.player.getNodePath().getDistance(self.goal) < 2 hasKey = 'goal' in [key.lock for key in self.player.inventory] if (close and hasKey): self.gameOver = False self.endGame() return task.cont
class Game(ShowBase): def __init__(self): ShowBase.__init__(self) #globalClock.setMode(ClockObject.M_limited) #globalClock.setFrameRate(60) self.disableMouse() Common.initialise() Common.framework = self properties = WindowProperties() properties.setSize(1000, 750) self.win.requestProperties(properties) self.exitFunc = self.cleanup render.setShaderAuto() self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False, "activateItem" : False, "invLeft" : False, "invRight" : 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.accept("wheel_up", self.onMouseWheel, [1]) self.accept("wheel_down", self.onMouseWheel, [-1]) self.accept("space-up", self.interact) self.accept("1", self.selectWeapon, [0]) self.accept("2", self.selectWeapon, [1]) self.accept("f", self.toggleFrameRateMeter) self.showFrameRateMeter = False self.pusher = CollisionHandlerPusher() self.traverser = CollisionTraverser() self.traverser.setRespectPrevTransform(True) self.pusher.setHorizontal(True) self.pusher.add_in_pattern("%fn-into-%in") self.pusher.add_in_pattern("%fn-into") self.pusher.add_again_pattern("%fn-again-into") #self.accept("trapEnemy-into-wall", self.stopTrap) self.accept("projectile-into", self.projectileImpact) self.accept("projectile-again-into", self.projectileImpact) self.accept("playerWallCollider-into-item", self.itemCollected) self.accept("playerWallCollider-into-trigger", self.triggerActivated) self.updateTask = taskMgr.add(self.update, "update") self.player = None self.currentLevel = None self.gameOverScreen = DirectDialog(frameSize = (-0.7, 0.7, -0.7, 0.7), fadeScreen = 0.4, relief = DGG.FLAT) self.gameOverScreen.hide() 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, 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, frameSize = (-4, 4, -1, 1), text_scale = 0.75, relief = DGG.FLAT, text_pos = (0, -0.2)) btn.setTransparency(True) render.setShaderAuto() self.startGame() def toggleFrameRateMeter(self): self.showFrameRateMeter = not self.showFrameRateMeter self.setFrameRateMeter(self.showFrameRateMeter) def startGame(self): self.gameOverScreen.hide() self.cleanup() self.player = Player() self.currentLevel = Level("testLevel") def selectWeapon(self, index): if self.player is not None: self.player.setCurrentWeapon(index) def interact(self): if self.player is not None: self.player.interact() def onMouseWheel(self, dir): if self.player is not None: self.player.scrollWeapons(dir) def updateKeyMap(self, controlName, controlState, callback = None): self.keyMap[controlName] = controlState if callback is not None: callback(controlName, controlState) def update(self, task): dt = globalClock.getDt() if self.currentLevel is not None: self.currentLevel.update(self.player, self.keyMap, dt) if self.player is not None and self.player.health <= 0: if self.gameOverScreen.isHidden(): self.gameOverScreen.show() #self.finalScoreLabel["text"] = "Final score: " + str(self.player.score) #self.finalScoreLabel.setText() self.traverser.traverse(render) if self.player is not None and self.player.health > 0: self.player.postTraversalUpdate(dt) return Task.cont def projectileImpact(self, entry): fromNP = entry.getFromNodePath() proj = fromNP.getPythonTag(TAG_OWNER) intoNP = entry.getIntoNodePath() if intoNP.hasPythonTag(TAG_OWNER): intoObj = intoNP.getPythonTag(TAG_OWNER) proj.impact(intoObj) else: proj.impact(None) def itemCollected(self, entry): fromNP = entry.getFromNodePath() player = fromNP.getPythonTag(TAG_OWNER) intoNP = entry.getIntoNodePath() item = intoNP.getPythonTag(TAG_OWNER) item.collected(player) def triggerActivated(self, entry): intoNP = entry.getIntoNodePath() trigger = intoNP.getPythonTag(TAG_OWNER) if self.currentLevel is not None: self.currentLevel.triggerActivated(trigger) def cleanup(self): if self.currentLevel is not None: self.currentLevel.cleanup() self.currentLevel = None if self.player is not None: self.player.cleanup() self.player = None def quit(self): self.cleanup() base.userExit()
class Section2(): def __init__(self, showBase): self.showBase = showBase Common.initialise() Common.framework = self showBase.render.setShaderAuto() self.keyMap = { "up" : False, "down" : False, "left" : False, "right" : False, "shoot" : False, "shootSecondary" : False } showBase.accept("w", self.updateKeyMap, ["up", True]) showBase.accept("w-up", self.updateKeyMap, ["up", False]) showBase.accept("s", self.updateKeyMap, ["down", True]) showBase.accept("s-up", self.updateKeyMap, ["down", False]) showBase.accept("mouse1", self.updateKeyMap, ["shoot", True]) showBase.accept("mouse1-up", self.updateKeyMap, ["shoot", False]) showBase.accept("mouse3", self.updateKeyMap, ["shootSecondary", True]) showBase.accept("mouse3-up", self.updateKeyMap, ["shootSecondary", False]) showBase.accept("\\", self.toggleFriction) self.pusher = CollisionHandlerPusher() self.traverser = CollisionTraverser() self.traverser.setRespectPrevTransform(True) self.pusher.add_in_pattern("%fn-into-%in") self.pusher.add_in_pattern("%fn-into") self.pusher.add_again_pattern("%fn-again-into") showBase.accept("projectile-into", self.projectileImpact) showBase.accept("projectile-again-into", self.projectileImpact) showBase.accept("player-into", self.gameObjectPhysicalImpact) showBase.accept("enemy-into", self.gameObjectPhysicalImpact) self.updateTask = showBase.taskMgr.add(self.update, "update") self.player = None self.currentLevel = None def toggleFriction(self): Common.useFriction = not Common.useFriction def startGame(self, shipSpec): self.cleanupLevel() self.player = Player(shipSpec) self.currentLevel = Level("spaceLevel") def updateKeyMap(self, controlName, controlState, callback = None): self.keyMap[controlName] = controlState if callback is not None: callback(controlName, controlState) def update(self, task): dt = globalClock.getDt() if self.currentLevel is not None: self.currentLevel.update(self.player, self.keyMap, dt) if self.player is not None and self.player.health <= 0: self.showBase.gameOver() return Task.done self.traverser.traverse(self.showBase.render) if self.player is not None and self.player.health > 0: self.player.postTraversalUpdate(dt) return Task.cont def projectileImpact(self, entry): fromNP = entry.getFromNodePath() proj = fromNP.getPythonTag(TAG_OWNER) intoNP = entry.getIntoNodePath() if intoNP.hasPythonTag(TAG_OWNER): intoObj = intoNP.getPythonTag(TAG_OWNER) proj.impact(intoObj) else: proj.impact(None) def gameObjectPhysicalImpact(self, entry): fromNP = entry.getFromNodePath() if fromNP.hasPythonTag(TAG_OWNER): fromNP.getPythonTag(TAG_OWNER).physicalImpact(entry.getSurfaceNormal(self.showBase.render)) def triggerActivated(self, entry): intoNP = entry.getIntoNodePath() trigger = intoNP.getPythonTag(TAG_OWNER) if self.currentLevel is not None: self.currentLevel.triggerActivated(trigger) def cleanupLevel(self): if self.currentLevel is not None: self.currentLevel.cleanup() self.currentLevel = None if self.player is not None: self.player.cleanup() self.player = None def cleanup(self): self.showBase.ignore("w") self.showBase.ignore("w-up") self.showBase.ignore("s") self.showBase.ignore("s-up") self.showBase.ignore("mouse1") self.showBase.ignore("mouse1-up") self.showBase.ignore("mouse3") self.showBase.ignore("mouse3-up") self.showBase.ignore("\\") self.showBase.ignore("projectile-into") self.showBase.ignore("projectile-again-into") self.showBase.ignore("player-into") self.showBase.ignore("enemy-into") self.cleanupLevel() self.showBase.taskMgr.remove(self.updateTask) self.showBase = None self.updateTask = None