Пример #1
0
 def enterPlay(self):
     self.notify.debug('enterPlay')
     self.startGameWalk()
     self.spawnUpdateSuitsTask()
     self.accept('control', self.controlKeyPressed)
     self.pieHandler = CollisionHandlerEvent()
     self.pieHandler.setInPattern('pieHit-%fn')
Пример #2
0
 def setupTire(self, avId, index):
     tireNp, tireBody, tireOdeGeom = self.createTire(index)
     self.tireDict[avId] = {
         'tireNodePath': tireNp,
         'tireBody': tireBody,
         'tireOdeGeom': tireOdeGeom
     }
     if avId <= 0:
         tireBlocker = tireNp.find('**/tireblockermesh')
         if not tireBlocker.isEmpty():
             tireBlocker.hide()
     if avId == self.localAvId:
         tireNp = self.tireDict[avId]['tireNodePath']
         self.treasureSphereName = 'treasureCollider'
         self.treasureCollSphere = CollisionSphere(
             0, 0, 0, IceGameGlobals.TireRadius)
         self.treasureCollSphere.setTangible(0)
         self.treasureCollNode = CollisionNode(self.treasureSphereName)
         self.treasureCollNode.setFromCollideMask(
             ToontownGlobals.PieBitmask)
         self.treasureCollNode.addSolid(self.treasureCollSphere)
         self.treasureCollNodePath = tireNp.attachNewNode(
             self.treasureCollNode)
         self.treasureHandler = CollisionHandlerEvent()
         self.treasureHandler.addInPattern('%fn-intoTreasure')
         base.cTrav.addCollider(self.treasureCollNodePath,
                                self.treasureHandler)
         eventName = '%s-intoTreasure' % self.treasureCollNodePath.getName()
         self.notify.debug('eventName = %s' % eventName)
         self.accept(eventName, self.toonHitSomething)
Пример #3
0
    def __init__(self):
        ShowBase.__init__(self)

        # Override defaults
        self.disableMouse()
        self.setBackgroundColor(VBase3(160, 200, 150) / 255.0)
        self.setFrameRateMeter(True)

        # Lights
        dlight = DirectionalLight("dlight")
        dlnp = self.render.attachNewNode(dlight)
        dlnp.setHpr(180.0, -70.0, 0)
        self.render.setLight(dlnp)

        alight = AmbientLight("alight")
        alnp = self.render.attachNewNode(alight)
        alight.setColor(VBase4(0.4, 0.4, 0.4, 1))
        self.render.setLight(alnp)

        # Collision traverser
        self.cTrav = CollisionTraverser("collisionTraverser")
        #self.cTrav.showCollisions(self.render)

        # Collision handlers
        self.carCollisionHandler = CollisionHandlerEvent()
        self.carCollisionHandler.addInPattern("%fn-into-%in")

        # Camera controls
        self.cameraController = CameraController(self, 400, math.pi / 4.0,
                                                 math.pi / 4.0)
        #self.cameraController = CameraController(self, 300, -math.pi, math.pi / 4.0)

        # Load the track
        #self.track = self.loader.loadModel("models/trackMotegi")
        self.track = self.loader.loadModel("models/trackValencia")
        checkpointsCollision = self.track.find("checkpoints").node()
        checkpointsCollision.setIntoCollideMask(BitMask32(0xF0))
        self.numCheckpoints = checkpointsCollision.getNumSolids()
        self.track.reparentTo(self.render)

        # Load the car
        #self.car = KeyboardCar(self)
        self.car = NeuralNetworkCar(self)
        self.cameraController.follow(self.car.getNodePath())
        #self.cameraController.setTarget(self.car.getNodePath())

        # Reposition the car
        #self.car.getNodePath().setH(180.0)

        # Register car collisions with track
        self.cTrav.addCollider(self.car.carCollider, self.carCollisionHandler)
        self.accept("carCollider-into-trackCollision", self.car.onCrash)
        self.accept("carCollider-into-checkpoints", self.car.onCheckpoint)

        # State logger
        self.loggingActive = False
        self.log = []
        self.accept("l", self.toggleStateLogger)
Пример #4
0
    def getSprayTrack(self, origin, target, scaleUp, hold, scaleDown, horizScale = 1.0, vertScale = 1.0):
        base.localAvatar.stop(self.toonAnim)
        self.lastFrame = self.avatar.getCurrentFrame(self.toonAnim)
        track = Sequence()
        sprayProp = loader.loadModel(GagGlobals.SPRAY_MDL)
        sprayProp.setTwoSided(1)
        sprayScale = hidden.attachNewNode('spray-parent')
        sprayRot = hidden.attachNewNode('spray-rotate')
        sprayRot.setColor(GagGlobals.WATER_SPRAY_COLOR)
        sprayRot.setTransparency(1)
        collNode = CollisionNode('Collision')
        spraySphere = CollisionSphere(0, 0, 0, 1)
        spraySphere.setTangible(0)
        collNode.addSolid(spraySphere)
        collNode.setCollideMask(CIGlobals.WallBitmask)
        sprayNP = sprayRot.attachNewNode(collNode)
        sprayNP.setY(1)
        self.sprayNP = sprayNP
        event = CollisionHandlerEvent()
        event.set_in_pattern('%fn-into')
        event.set_out_pattern('%fn-out')
        base.cTrav.add_collider(sprayNP, event)
        self.avatar.acceptOnce(sprayNP.node().getName() + '-into', self.onCollision)

        def showSpray(sprayScale, sprayProp, origin, target):
            objects = [sprayRot, sprayScale, sprayProp]
            for item in objects:
                index = objects.index(item)
                if index == 0:
                    item.reparentTo(self.sprayJoint)
                    item.setPos(self.sprayJoint.getPos(render))
                    item.setHpr(self.sprayJoint.getHpr(render))
                    item.setP(0)
                else:
                    item.reparentTo(objects[index - 1])
                item.clearMat()

        track.append(Func(showSpray, sprayScale, sprayProp, origin, target))
        self.spray = sprayRot

        def calcTargetScale():
            distance = Vec3(target - origin).length()
            yScale = distance / GagGlobals.SPRAY_LEN
            targetScale = Point3(yScale * horizScale, yScale, yScale * vertScale)
            return targetScale

        track.append(Parallel(LerpScaleInterval(sprayScale, scaleUp, calcTargetScale, startScale=GagGlobals.PNT3NEAR0), sprayNP.posInterval(0.25, self.spray.getPos(render) + Point3(0, 50, 0), startPos=self.spray.getPos(render) + Point3(0, 5, 0))))
        track.append(Wait(hold))
        track.append(Func(self.handleMiss))
        track.append(LerpScaleInterval(sprayScale, 0.75, GagGlobals.PNT3NEAR0))

        def hideSpray():
            (lambda prop: prop.removeNode(), [sprayProp, sprayRot, sprayScale])

        track.append(Func(hideSpray))
        track.append(Func(self.completeSquirt))
        return track
Пример #5
0
    def __init__(self):
        #--Collision Handler------------------------------------------------------
        self.collHandler = CollisionHandlerEvent()
        self.collHandler.addInPattern('%fn-into-%in')
        base.cTrav = CollisionTraverser('world traverser')

        #--Mouse Control----------------------------------------------------------
        base.disableMouse()
        self.properties = WindowProperties()
        self.properties.setCursorHidden(True)
        base.win.requestProperties(self.properties)

        #--Register Hud Elements--------------------------------------------------
        self.instruction1 = self.addInstruction("[click] to Shoot", 2)
        self.instruction2 = self.addInstruction("[a] to accelerate", 1)
        self.instruction3 = self.addInstruction("[esc] to quit", 0)

        self.scoreHud = self.addHudElement("", 0)
        self.accuracy = self.addHudElement("", 1)
        self.speedHud = self.addHudElement("", 2)

        self.bigHud = OnscreenText(text="",
                                   style=1,
                                   fg=(1, 1, 1, 1),
                                   pos=(0, 0),
                                   align=TextNode.ACenter,
                                   scale=.1)

        #--Load Objects and Models------------------------------------------------
        self.ship = Ship(self.collHandler)
        self.loadSkyBox()
        game.camera.reparentTo(self.ship.getModel())

        #--Start Game-------------------------------------------------------------
        self.asteroids = []
        self.resetGame()

        #--Controls --------------------------------------------------------------
        self.keysDown = {'a': 0}

        self.controlTask = taskMgr.add(self.gameLoop, "game-control-task")
        self.controlTask.lastTime = 0

        self.accept("escape", sys.exit, [0])
        self.accept("a", self.keyDown, ['a'])
        self.accept("a-up", self.keyUp, ['a'])
        self.accept("mouse1", self.shoot)
        self.accept("space", self.shoot)
        self.accept("resetgame", self.gameOver)

        if (DEBUG_CONTROLS):
            self.accept("0", self.ship.stop)
            self.accept("9", self.ship.getModel().setHpr, [0, 0, 0])

        #--Register CollisionEvent Handlers---------------------------------------
        self.accept('asteroid-into-bullet', self.bulletAsteroidCollision)
Пример #6
0
    def __init__(self):
        super().__init__(self)
        self.scene = self.loader.loadModel("./models/world.egg")
        self.scene.reparentTo(self.render)

        base.cTrav = CollisionTraverser()
        self.collisionHandlerEvent = CollisionHandlerEvent()
        base.enableParticles()

        #base.messenger.toggleVerbose()

        #self.collisionHandlerEvent.addInPattern('from-%in')
        self.collisionHandlerEvent.addInPattern('into-%in')
        self.collisionHandlerEvent.addOutPattern('outof-%in')

        self.player = self.scene.find("player")
        self.enemy = self.scene.find("enemy1")
        self.player.setPythonTag("ObjectController",
                                 Player(self.player, collisionMask=0x4))
        self.building_enemy = self.scene.find("building_enemy")

        #self.player.setPos(self.scene, 0,0,5)
        self.camera.setPos(self.render, 0, -50, 100)
        self.taskMgr.add(self.update, "update")

        self.accept('into-collision_enemy', self.crash)
        self.accept('into-collision_player', self.crash)
        self.accept('into-collision_plane', self.crash)

        base.cTrav.addCollider(self.scene.find("player/collision**"),
                               self.collisionHandlerEvent)
        base.cTrav.addCollider(self.scene.find("enemy1/collision**"),
                               self.collisionHandlerEvent)
        base.cTrav.addCollider(self.scene.find("basePlane/collision**"),
                               self.collisionHandlerEvent)

        #base.cTrav.showCollisions(self.render)

        InputManager.initWith(self, [
            InputManager.arrowUp, InputManager.arrowDown,
            InputManager.arrowRight, InputManager.arrowLeft, InputManager.keyS,
            InputManager.keyA, InputManager.space, InputManager.keyX,
            InputManager.keyV
        ])

        self.rails = self.scene.attachNewNode("rails")
        self.rails.setPos(self.scene, 0, 0, 0)
        self.rails_y = 0
        self.player.reparentTo(self.rails)

        self.player.setPos(self.rails, 0, 20, 0)

        #self.createStaticEnemy(self.building_enemy ,  -100 ,500, 0 )
        self.createStaticEnemy(self.building_enemy, 200, 850, 0)
        self.createStaticEnemy(self.building_enemy, -100, 1000, 0)
        self.createDynamicEnemy(self.enemy, -80, 500, 20, -200, 500, 20)
Пример #7
0
    def __init__(self, showbase, usersData, gameData):
        DirectObject.__init__(self)

        self.showbase = showbase
        self.usersData = usersData
        self.gameData = gameData

        random.seed(self.gameData.randSeed)

        # Initialize the collision traverser.
        self.cTrav = CollisionTraverser()

        # Initialize the handler.
        self.collHandEvent = CollisionHandlerEvent()
        self.collHandEvent.addInPattern('into-%in')

        self.world = World(showbase)

        self.ambientLight = showbase.render.attachNewNode(
            AmbientLight("ambientLight"))
        # Set the color of the ambient light
        self.ambientLight.node().setColor((.1, .1, .1, 1))
        # add the newly created light to the lightAttrib
        # showbase.render.setLight(self.ambientLight)

        self.spotlight = None

        numberOfPlayers = len(self.usersData)
        for index, user in enumerate(self.usersData):
            user.centipede = Centipede(showbase, index, numberOfPlayers,
                                       self.addToCollisions)
            if user.thisPlayer:
                self.centipede = user.centipede
                self.centipede.attachRing(showbase)

                self.spotlight = self.centipede.head.attachNewNode(
                    PointLight("playerSpotlight"))
                self.spotlight.setPos(LVector3(0, 0, 8))
                # Now we create a spotlight. Spotlights light objects in a given cone
                # They are good for simulating things like flashlights
                self.spotlight.node().setAttenuation(
                    LVector3(.025, 0.0005, 0.0001))
                self.spotlight.node().setColor((0.35, 0.35, .35, 1))
                self.spotlight.node().setSpecularColor((0.01, 0.01, 0.01, 1))

                showbase.render.setLight(self.spotlight)

        self.perPixelEnabled = True
        self.shadowsEnabled = True
        #if self.spotlight:
        #    self.spotlight.node().setShadowCaster(True, 512, 512)
        showbase.render.setShaderAuto()

        self.foods = []
        for i in range(self.gameData.maxFoods):
            self.foods.append(Food(self.showbase, i, self.addToCollisions))
Пример #8
0
 def __init__(self, model = "cube_nocol", texture = "lava", pos = (0,0,0), scale = (1,1,1), cubetype = "A"):
     super(LavaCube, self).__init__(model, texture, pos, scale)
     cn = CollisionNode('lava')
     cn.setFromCollideMask(COLLISIONMASKS['lava'])
     cn.setIntoCollideMask(BitMask32.allOff())
     np = self.node.attachNewNode(cn)
     cn.addSolid(CollisionSphere(0,0,0,1.1))
     h = CollisionHandlerEvent()
     h.addInPattern('%fn-into-%in')
     h.addOutPattern('%fn-outof-%in')
     base.cTrav.addCollider(np, h)
 def getFlyBallBubble(self):
     if self.__flyBallBubble == None:
         bubble = CollisionSphere(0, 0, 0, GolfGlobals.GOLF_BALL_RADIUS)
         node = CollisionNode('flyBallBubble')
         node.addSolid(bubble)
         node.setFromCollideMask(ToontownGlobals.PieBitmask | ToontownGlobals.CameraBitmask | ToontownGlobals.FloorBitmask)
         node.setIntoCollideMask(BitMask32.allOff())
         self.__flyBallBubble = NodePath(node)
         self.flyBallHandler = CollisionHandlerEvent()
         self.flyBallHandler.addInPattern('flyBallHit-%d' % self.index)
     return self.__flyBallBubble
Пример #10
0
 def buildCollisions(self):
     pieSphere = CollisionSphere(0, 0, 0, 1)
     pieSensor = CollisionNode('turretGagSensor' + str(id(self)))
     pieSensor.addSolid(pieSphere)
     pieNP = self.gag.attachNewNode(pieSensor)
     pieNP.setCollideMask(BitMask32(0))
     pieNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.addCollider(pieNP, event)
Пример #11
0
 def buildCollisions(self):
     gagSph = CollisionSphere(0, 0, 0, 2)
     gagSensor = CollisionNode('gagSensor')
     gagSensor.addSolid(gagSph)
     sensorNP = self.gag.attachNewNode(gagSensor)
     sensorNP.setCollideMask(BitMask32(0))
     sensorNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.addCollider(sensorNP, event)
     self.avatar.acceptOnce('gagSensor-into', self.onCollision)
Пример #12
0
 def buildCollisions(self, entity):
     pieSphere = CollisionSphere(0, 0, 0, 1)
     pieSensor = CollisionNode('gagSensor')
     pieSensor.addSolid(pieSphere)
     pieNP = entity.attachNewNode(pieSensor)
     pieNP.setCollideMask(BitMask32(0))
     pieNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.add_collider(pieNP, event)
     self.avatar.acceptOnce('gagSensor-into', self.onCollision)
Пример #13
0
    def __init__(self):
        # start Panda3d
        base = ShowBase()
        # CollisionTraverser instance must be attached to base,
        # and must be called cTrav
        base.cTrav = CollisionTraverser()
        self.cHand = CollisionHandlerEvent()
        self.cHand.addInPattern('into-%in')
        
        # load smiley, which we will control
        # notice this is a little trickery. If we parent everything except smiley
        # to the camera, and the player is controlling the camera, then everything 
        # stays fixed in the same place relative to the camera, and when the camera
        # moves, the player is given the illusion that he is moving smiley, rather than 
        # the camera and the rest of the scene.
        self.smiley = base.loader.loadModel('smiley')
        self.smiley.reparentTo(render)
        self.smiley.setName('Smiley')
        
        # Setup a collision solid for this model. Our initCollisionSphere method returns
        # the cNodepath and the string representing it. We will use the cNodepath for 
        # adding to the traverser, and the string to accept it for event handling.
        #sColl = self.initCollisionSphere(self.smiley)
        sColl = self.initCollisionSphere(self.smiley, True)
        print 'smiley', sColl[0]
        print 'smiley', sColl[1]

        # Add this object to the traverser.
        base.cTrav.addCollider(sColl[0], self.cHand)

        # load frowney
        self.frowney = base.loader.loadModel('frowney')
        self.frowney.setName('Frowney')
        self.frowney.reparentTo(camera)
        
        # Setup a collision solid for this model.
        fColl = self.initCollisionSphere(self.frowney, True)
        #print 'frowney', fColl[0]
        #print 'frowney', fColl[1]
        
        # Add this object to the traverser.
        base.cTrav.addCollider(fColl[0], self.cHand)

        # Accept the events sent by the collisions.
        # smiley is the object we are 'moving', so by convention
        # it is the from object.
        # If we instead put smiley as the into object here,
        # it would work fine, but then smiley would disappear
        # when we collided them.
        self.accept('into-' + fColl[1], self.collide)        

        # set the initial positions of smiley and frowney
        self.set_initial_positions()
Пример #14
0
    def __init__(self):
        """Setup this app."""
        ShowBase.__init__(self)

        #Setup window
        wnd_props = WindowProperties()
        wnd_props.set_title("Neo Impressive Title")
        #wnd_props.set_origin(0, 0)
        wnd_props.set_size(1024, 768)
        self.win.request_properties(wnd_props)

        self.set_background_color(0, .5, 1, 1)

        #Init GUI sub-system
        self.gui = GUI(self)
        self.gui.run()

        #Init app state
        self.state = APP_STATE_LOGO
        self.logo_delay = 600

        #Start title music
        self.title_music = loader.loadMusic("./data/sounds/title.ogg")
        self.title_music.set_loop(True)
        self.title_music.play()

        #Setup collision detection
        self.cTrav = CollisionTraverser()

        self.portal_handler = CollisionHandlerEvent()
        self.portal_handler.add_in_pattern("%fn-entered-%in")

        #Init other sub-systems
        self.cam_mgr = CameraManager()
        self.world_mgr = WorldManager()

        #Setup lighting
        self.ambient = AmbientLight("Ambient Light")
        self.ambient.set_color(Vec4(.5, .5, .5, 1))
        self.ambient_np = self.render.attach_new_node(self.ambient)
        self.render.set_light(self.ambient_np)

        self.sun = DirectionalLight("Sun")
        self.sun_np = self.render.attach_new_node(self.sun)
        self.sun_np.set_p(-135)
        self.render.set_light(self.sun_np)

        #Setup auto-shaders
        self.render.set_shader_auto()

        #Debug stats
        #self.messenger.toggle_verbose()
        PStatClient.connect()
Пример #15
0
 def setupFloorEventSphere(self, avatarNodePath, bitmask, avatarRadius):
     cSphere = CollisionSphere(0.0, 0.0, 0.0, 0.75)
     cSphereNode = CollisionNode('Flyer.cFloorEventSphere')
     cSphereNode.addSolid(cSphere)
     cSphereNodePath = avatarNodePath.attachNewNode(cSphereNode)
     cSphereNode.setFromCollideMask(bitmask)
     cSphereNode.setIntoCollideMask(BitMask32.allOff())
     self.floorCollisionEvent = CollisionHandlerEvent()
     self.floorCollisionEvent.addInPattern('%fn-enter-%in')
     self.floorCollisionEvent.addAgainPattern('%fn-again-%in')
     self.floorCollisionEvent.addOutPattern('%fn-exit-%in')
     base.cTrav.addCollider(cSphereNodePath, self.floorCollisionEvent)
     self.cFloorEventSphereNodePath = cSphereNodePath
 def __initCollisions(self):
     collSphere = CollisionSphere(0, 0, 0, Globals.PlayerCollisionRadius)
     collSphere.setTangible(0)
     self.mazeCollisionName = Globals.LocalPlayerCollisionName
     collNode = CollisionNode(self.mazeCollisionName)
     collNode.addSolid(collSphere)
     collNodePath = self.toon.attachNewNode(collNode)
     collNodePath.hide()
     handler = CollisionHandlerEvent()
     handler.addInPattern('%fn-into-%in')
     base.cTrav.addCollider(collNodePath, handler)
     self.handler = handler
     self._collNodePath = collNodePath
Пример #17
0
 def setupEventSphere(self, bitmask, avatarRadius):
     self.avatarRadius = avatarRadius
     cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75,
                               self.avatarRadius * 1.04)
     cSphere.setTangible(0)
     cSphereNode = CollisionNode('Flyer.cEventSphereNode')
     cSphereNode.addSolid(cSphere)
     cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode)
     cSphereNode.setFromCollideMask(bitmask)
     cSphereNode.setIntoCollideMask(BitMask32.allOff())
     self.event = CollisionHandlerEvent()
     self.event.addInPattern('enter%in')
     self.event.addOutPattern('exit%in')
     self.cEventSphereNodePath = cSphereNodePath
Пример #18
0
    def set_controls(self):
        """Configure common game controls.

        Configure major keys, collisions system
        and controls to manipulate characters.
        """
        base.accept("f1", self._show_keys)  # noqa: F821
        base.accept("escape", base.main_menu.show)  # noqa: F821
        base.accept("r", self._show_char_relations)  # noqa: F821
        base.accept("m", base.world.rails_scheme.show)  # noqa: F821
        base.accept("j", base.journal.show)  # noqa: F821

        # configure mouse collisions
        col_node = CollisionNode("mouse_ray")
        col_node.setIntoCollideMask(NO_MASK)
        col_node.setFromCollideMask(MOUSE_MASK)
        self._mouse_ray = CollisionRay()
        col_node.addSolid(self._mouse_ray)

        # set common collisions handler
        handler = CollisionHandlerEvent()
        handler.addInPattern("%fn-into")
        handler.addAgainPattern("%fn-again")
        handler.addOutPattern("%fn-out")

        self.traverser = CollisionTraverser("traverser")
        self.traverser.addCollider(
            base.cam.attachNewNode(col_node), handler  # noqa: F821
        )
        self.set_mouse_events()

        taskMgr.doMethodLater(0.03, self._collide_mouse, "collide_mouse")  # noqa: F821
        taskMgr.doMethodLater(0.04, self._traverse, name="main_traverse")  # noqa: F821
Пример #19
0
 def buildProjCollisions(self):
     gagSph = CollisionSphere(0, 0, 0, 1)
     gagSph.setTangible(0)
     gagNode = CollisionNode('projSensor')
     gagNode.addSolid(gagSph)
     gagNP = self.gag.attach_new_node(gagNode)
     gagNP.setScale(0.75, 0.8, 0.75)
     gagNP.setPos(0.0, 0.1, 0.5)
     gagNP.setCollideMask(BitMask32.bit(0))
     gagNP.node().setFromCollideMask(CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.addCollider(gagNP, event)
Пример #20
0
 def setupHeadSphere(self, avatarNodePath):
     collSphere = CollisionSphere(0, 0, 0, 1)
     collSphere.setTangible(1)
     collNode = CollisionNode('Flyer.cHeadCollSphere')
     collNode.setFromCollideMask(ToontownGlobals.CeilingBitmask)
     collNode.setIntoCollideMask(BitMask32.allOff())
     collNode.addSolid(collSphere)
     self.cHeadSphereNodePath = avatarNodePath.attachNewNode(collNode)
     self.cHeadSphereNodePath.setZ(base.localAvatar.getHeight() + 1.0)
     self.headCollisionEvent = CollisionHandlerEvent()
     self.headCollisionEvent.addInPattern('%fn-enter-%in')
     self.headCollisionEvent.addOutPattern('%fn-exit-%in')
     base.cTrav.addCollider(self.cHeadSphereNodePath,
                            self.headCollisionEvent)
Пример #21
0
 def __init__(self, model = "models/sphere", texture = "exit", pos = (0,0,0), scale = (1,1,1), cubetype = "A"):
     super(LevelExit, self).__init__(model, texture, pos, scale)
     #self.node.setTransparency(TransparencyAttrib.MAlpha)
     self.node.setTag('noportals', '1')
     self.node.setTag('isexit', '1')
     cn = CollisionNode('levelExit')
     cn.setFromCollideMask(COLLISIONMASKS['exit'])
     cn.setIntoCollideMask(BitMask32.allOff())
     np = self.node.attachNewNode(cn)
     cn.addSolid(CollisionSphere(0,0,0,1.1))
     h = CollisionHandlerEvent()
     h.addInPattern('%fn-into-%in')
     h.addOutPattern('%fn-outof-%in')
     base.cTrav.addCollider(np, h)
Пример #22
0
 def enterPlay(self):
     self.notify.debug('enterPlay')
     self.startGameWalk()
     self.spawnUpdateSuitsTask()
     self.accept('control', self.controlKeyPressed)
     self.pieHandler = CollisionHandlerEvent()
     self.pieHandler.setInPattern('pieHit-%fn')
Пример #23
0
    def __init__(self, spawn, taregt, id):

        self.projectileNode = NodePath('projectile'+str(id))
        self.projectileNode.reparentTo(render)

        self.projectileNode.setPos(spawn,0,-10, 0)
        self.projectileNode.setScale(.1)
        projectileModel = loader.loadModel("./resources/cubeShot.egg")
        projectileModel.setColorScale(200, 0, 255, 100)
        projectileModel.reparentTo(self.projectileNode)
        self.projectileNode.setHpr(spawn, 0, 0, 0)


        dir = render.getRelativeVector(spawn, Vec3(0, 1, 0))

        #speed up or slow down projectiles here
        #dir = dir*20
        self.vec = dir*-200
        
        cs = CollisionSphere(0, 0, 0, 2.5)
        cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
        cnodepath.node().addSolid(cs)
        self.collHand = CollisionHandlerEvent()
        self.collHand.addInPattern('enemyProjectileinto'+str(id))
        self.collHand.addOutPattern('outof')
        base.cTrav.addCollider(cnodepath, self.collHand)
        self.acceptOnce('enemyProjectileinto'+str(id), self.hit)
        self.damage = 10
Пример #24
0
 def start(self):
     self.fullyChargedSound = base.loadSfx('phase_4/audio/sfx/MG_pairing_match.mp3')
     self.rechargeSound = base.loadSfx('phase_4/audio/sfx/MG_sfx_travel_game_blue_arrow.mp3')
     self.batteryFrame = DirectFrame(parent=base.a2dBottomRight, pos=(-0.2, 0, 0.1), scale=(0.8, 0, 1))
     self.batteryBg = OnscreenImage(image='phase_4/maps/battery_charge_frame.png', parent=self.batteryFrame)
     self.batteryBg.setTransparency(1)
     self.batteryBg.setX(0.03)
     self.batteryBg.setScale(0.17, 0, 0.05)
     self.batteryBar = DirectWaitBar(value=0, range=5, barColor=(1, 1, 1, 1), relief=None, scale=(0.12, 0.0, 0.3), parent=self.batteryFrame)
     self.cameraFocus = loader.loadModel('phase_4/models/minigames/photo_game_viewfinder.bam')
     self.cameraFocus.reparentTo(base.aspect2d)
     self.focusCollHandler = CollisionHandlerEvent()
     self.focusCollHandler.setInPattern('%fn-into')
     self.focusCollHandler.setOutPattern('%fn-out')
     self.focusCollNode = CollisionNode('mouseRay')
     self.focusCollNP = base.camera.attachNewNode(self.focusCollNode)
     self.focusCollNode.setCollideMask(BitMask32(0))
     self.focusCollNode.setFromCollideMask(CIGlobals.WallBitmask)
     self.focusRay = CollisionRay()
     self.focusRay.setFromLens(base.camNode, 0.0, 0.0)
     self.focusCollNode.addSolid(self.focusRay)
     base.cTrav.addCollider(self.focusCollNP, self.focusCollHandler)
     base.localAvatar.walkControls.setWalkSpeed(CIGlobals.ToonForwardSpeed, 0.0, CIGlobals.ToonReverseSpeed, CIGlobals.ToonRotateSpeed)
     FirstPerson.start(self)
     return
Пример #25
0
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        base.camLens.setNearFar(1.0, 10000)
        base.camLens.setFov(75)
        
        a = 33
        base.camera.setPos(0,-a,a+3)#80)
        # collision
        base.cTrav = CollisionTraverser("base collision traverser")
        base.cHandler = CollisionHandlerEvent()
        base.cPusher = CollisionHandlerPusher()
        base.cQueue = CollisionHandlerQueue()
        base.globalClock=ClockObject.getGlobalClock()
        base.cHandler.addInPattern('%fn-into-%in')
        base.cHandler.addOutPattern('%fn-out-%in')
        base.cHandler.addAgainPattern('%fn-again-%in')
        # ai init
        base.AIworld = AIWorld(render)
        # 3d manager
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)
        self.monsters = []
        self.accept('c',self._create)

        base.enableParticles()
Пример #26
0
    def postInit(self):
        #
        # initialize game content
        #
        # camera
        base.camLens.setNearFar(1.0, 10000)
        base.camLens.setFov(75)

        a = 33
        base.camera.setPos(0, -a, a + 3)  #80)
        # collision
        base.cTrav = CollisionTraverser("base collision traverser")
        base.cHandler = CollisionHandlerEvent()
        base.cPusher = CollisionHandlerPusher()
        base.cQueue = CollisionHandlerQueue()
        base.globalClock = ClockObject.getGlobalClock()
        base.cHandler.addInPattern('%fn-into-%in')
        base.cHandler.addOutPattern('%fn-out-%in')
        base.cHandler.addAgainPattern('%fn-again-%in')
        # ai init
        base.AIworld = AIWorld(render)
        # 3d manager
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)
        # manager
        self.archiveManager = ArchiveManager()
        self.mapManager = MapManager()
        self.initHeroInfo = None
        # Lock
        self.lock = threading.Lock()
        self.gameThread = None

        self.filters = CommonFilters(base.win, base.cam)
        # UI
        self.menu = Menu()
        self.option = Option()
        self.archive = Archive()
        self.death = Death()
        # self.oobe()
        #self.Archive_status = 0
        # self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        # self.menuMusic.setLoop(True)
        # self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        # self.fightMusic.setLoop(True)
        # base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        self.titleVideo, self.titleCard = loadVideo('title.mp4')

        self.isInited = False
        self.isSkip = False
        self.isRenew = False
        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")
Пример #27
0
 def buildCollisions(self):
     TrapGag.buildCollisions(self)
     gagSph = CollisionSphere(0, 0, 0, self.collRadius)
     gagSph.setTangible(0)
     gagNode = CollisionNode('gagSensor')
     gagNode.addSolid(gagSph)
     gagNP = self.gag.attachNewNode(gagNode)
     gagNP.setScale(0.75, 0.8, 0.75)
     gagNP.setPos(0.0, 0.1, 0.5)
     gagNP.setCollideMask(BitMask32.bit(0))
     gagNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.addCollider(gagNP, event)
     if self.isLocal():
         self.avatar.accept('gagSensor-into', self.onCollision)
Пример #28
0
    def __init__(self):
        # Initialize the traverser.
        base.cTrav = CollisionTraverser()

        # Initialize the handler.
        self.collHandEvent = CollisionHandlerEvent()
        self.collHandEvent.addInPattern('into-%in')
        self.collHandEvent.addOutPattern('outof-%in')

        # Make a variable to store the unique collision string count.
        self.collCount = 0

        # Load a model. Reparent it to the camera so we can move it.
        s = base.loader.loadModel('smiley')
        s.reparentTo(base.camera)
        s.setPos(0, 25, 0)

        # Setup a collision solid for this model.
        sColl = self.initCollisionSphere(s, True)

        # Add this object to the traverser.
        base.cTrav.addCollider(sColl[0], self.collHandEvent)

        # Accept the events sent by the collisions.
        self.accept('into-' + sColl[1], self.collide3)
        self.accept('outof-' + sColl[1], self.collide4)
        print(sColl[1])

        # Load another model.
        t = base.loader.loadModel('smiley')
        t.reparentTo(base.render)
        t.setPos(5, 25, 0)

        # Setup a collision solid for this model.
        tColl = self.initCollisionSphere(t, True)

        # Add this object to the traverser.
        base.cTrav.addCollider(tColl[0], self.collHandEvent)

        # Accept the events sent by the collisions.
        self.accept('into-' + tColl[1], self.collide)
        self.accept('outof-' + tColl[1], self.collide2)
        print(tColl[1])

        print("WERT")
Пример #29
0
    def swordHitEnemy(self, task):
        # When the sword collides with enemy, enemy dies
        for enemy in self.enemies:
            self.playerKill = CollisionHandlerEvent()
            base.cTrav.addCollider(enemy.collider, self.playerKill)
            self.playerKill.addInPattern('%fn-into-%in')

            # perform the task
            self.kill = DirectObject()
            self.kill.accept('enemy' + str(enemy.numb) + '-into-swordCollider',
                             enemy.killEnemy)
            self.swordHit = DirectObject()
            self.swordHit.accept(
                'enemy' + str(enemy.numb) + '-into-swordCollider',
                self.swordHitSound)
            if not enemy.isAlive:
                self.enemies.remove(enemy)
        return task.cont
 def __init__(self, id, toon, game, guiMgr):
     CogdoMazePlayer.__init__(self, id, toon)
     self.disableGagCollision()
     self.game = game
     self.maze = self.game.maze
     self._guiMgr = guiMgr
     self.cameraMgr = CogdoMazeCameraManager(self.toon, self.maze, camera,
                                             render)
     self._proximityRadius = self.maze.cellWidth * Globals.CameraRemoteToonRadius
     orthoDrive = OrthoDrive(
         Globals.ToonRunSpeed,
         maxFrameMove=self.maze.cellWidth / 2,
         customCollisionCallback=self.maze.doOrthoCollisions,
         wantSound=True)
     self.orthoWalk = OrthoWalk(orthoDrive)
     self._audioMgr = base.cogdoGameAudioMgr
     self._getMemoSfx = self._audioMgr.createSfx('getMemo',
                                                 source=self.toon)
     self._waterCoolerFillSfx = self._audioMgr.createSfx('waterCoolerFill',
                                                         source=self.toon)
     self._hitByDropSfx = self._audioMgr.createSfx('toonHitByDrop',
                                                   source=self.toon)
     self._winSfx = self._audioMgr.createSfx('win')
     self._loseSfx = self._audioMgr.createSfx('lose')
     self.enabled = False
     self.pickupCount = 0
     self.numEntered = 0
     self.throwPending = False
     self.coolDownAfterHitInterval = Sequence(
         Wait(Globals.HitCooldownTime),
         Func(self.setInvulnerable, False),
         name='coolDownAfterHitInterval-%i' % self.toon.doId)
     self.invulnerable = False
     self.gagHandler = CollisionHandlerEvent()
     self.gagHandler.addInPattern('%fn-into-%in')
     self.exited = False
     self.hints = {
         'find': False,
         'throw': False,
         'squashed': False,
         'boss': False,
         'minion': False
     }
     self.accept('control', self.controlKeyPressed)
Пример #31
0
    def startActivity(self, timestamp):
        self.pieHandler = CollisionHandlerEvent()
        self.pieHandler.setInPattern('pieHit-%fn')
        if self.player is not None:
            self.player.resetScore()
            self.hideTeamFlags(self.player.team)
        for player in list(self.players.values()):
            self.finishToonIval(player.toon.doId)
            player.enable()

        for cog in self.cogManager.cogs:
            cog.request('Active', timestamp)

        for ival in self.pieIvals:
            if ival.isPlaying():
                ival.finish()

        self.pieIvals = []
        return
 def createCatchCollisions(self):
     radius = 0.7
     handler = CollisionHandlerEvent()
     handler.setInPattern('ltCatch%in')
     self.ltLegsCollNode = CollisionNode('catchLegsCollNode')
     self.ltLegsCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask)
     self.ltHeadCollNode = CollisionNode('catchHeadCollNode')
     self.ltHeadCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask)
     self.ltLHandCollNode = CollisionNode('catchLHandCollNode')
     self.ltLHandCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask)
     self.ltRHandCollNode = CollisionNode('catchRHandCollNode')
     self.ltRHandCollNode.setCollideMask(PartyGlobals.CatchActivityBitmask)
     legsCollNodepath = base.localAvatar.attachNewNode(self.ltLegsCollNode)
     legsCollNodepath.hide()
     head = base.localAvatar.getHeadParts().getPath(2)
     headCollNodepath = head.attachNewNode(self.ltHeadCollNode)
     headCollNodepath.hide()
     lHand = base.localAvatar.getLeftHands()[0]
     lHandCollNodepath = lHand.attachNewNode(self.ltLHandCollNode)
     lHandCollNodepath.hide()
     rHand = base.localAvatar.getRightHands()[0]
     rHandCollNodepath = rHand.attachNewNode(self.ltRHandCollNode)
     rHandCollNodepath.hide()
     base.localAvatar.cTrav.addCollider(legsCollNodepath, handler)
     base.localAvatar.cTrav.addCollider(headCollNodepath, handler)
     base.localAvatar.cTrav.addCollider(lHandCollNodepath, handler)
     base.localAvatar.cTrav.addCollider(lHandCollNodepath, handler)
     if self.ShowToonSpheres:
         legsCollNodepath.show()
         headCollNodepath.show()
         lHandCollNodepath.show()
         rHandCollNodepath.show()
     self.ltLegsCollNode.addSolid(CollisionSphere(0, 0, radius, radius))
     self.ltHeadCollNode.addSolid(CollisionSphere(0, 0, 0, radius))
     self.ltLHandCollNode.addSolid(
         CollisionSphere(0, 0, 0, 2 * radius / 3.0))
     self.ltRHandCollNode.addSolid(
         CollisionSphere(0, 0, 0, 2 * radius / 3.0))
     self.toonCollNodes = [
         legsCollNodepath, headCollNodepath, lHandCollNodepath,
         rHandCollNodepath
     ]
Пример #33
0
    def __init__(self, camera, look, id, model):
        self.id = id
        #nodepath of the projectile, give it a trajectory
        self.projectileNode = NodePath('projectile'+str(id))
        self.projectileNode.reparentTo(render)
        
        #by passing the camera node form the camMov object, all projectiles are spawned 5 units in front of the camera
        self.projectileNode.setHpr(look, 0, 0, 0)
        self.projectileNode.setPos(camera,0,3, 3)
        
        #fix z position to line up with gun
        self.projectileNode.setScale(.1)
        projectileModel = loader.loadModel("./resources/cubeShot.egg")
        projectileModel.setColor(255, 0, 0)
        projectileModel.reparentTo(self.projectileNode)
    	
        #must calculate unit vector based on direction
        dir = render.getRelativeVector(look, Vec3(0, 1, 0))
    	
        #speed up or slow down projectiles here
        dir = dir*10
        self.vec = dir

        #Balance vectors when magnitude in direction is low
        if self.vec.x < 2:
            self.vec.x += random.randint(-1,1)
        if self.vec.z < 2:
            self.vec.z += random.randint(-1,1)
        if self.vec.y < 2: 
            self.vec.y += random.randint(-1,1)
        
        #Random vector displacements
        self.vec.x *= random.uniform(.5,1)
        self.vec.y *= random.uniform(.5,1)
        self.vec.z *= random.uniform(.5,1)
        
        
        #base.cTrav = CollisionTraverser()
        cs = CollisionSphere(0, 0, 0, 2.5)
        self.cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
        self.cnodepath.node().addSolid(cs)
        self.collHand = CollisionHandlerEvent()

        self.cnodepath.setTag('tag', str(self.cnodepath))
        self.collHand.addInPattern('%(tag)ix-into'+str(id))
        self.collHand.addOutPattern('outof')
        #cTrav has the distinction of global colider handler
        base.cTrav.addCollider(self.cnodepath, self.collHand) 
        self.acceptOnce(self.cnodepath.getTag('self')+'-into'+str(id), self.hit)
	    #deal with colliding or special effects here.
	    #wanted projectiles to be short lived
	    # so i will make them delete themselves after impact or time expired
        # writing a task that will rek the projectiles at the end of time
        self.damage = 1.1
Пример #34
0
 def getFlyBallBubble(self):
     if self.__flyBallBubble == None:
         bubble = CollisionSphere(0, 0, 0, GolfGlobals.GOLF_BALL_RADIUS)
         node = CollisionNode('flyBallBubble')
         node.addSolid(bubble)
         node.setFromCollideMask(ToontownGlobals.PieBitmask | ToontownGlobals.CameraBitmask | ToontownGlobals.FloorBitmask)
         node.setIntoCollideMask(BitMask32.allOff())
         self.__flyBallBubble = NodePath(node)
         self.flyBallHandler = CollisionHandlerEvent()
         self.flyBallHandler.addInPattern('flyBallHit-%d' % self.index)
     return self.__flyBallBubble
Пример #35
0
 def createPortalCollisions(self):
     # Enter the portals
     cn = CollisionNode('bluePortal')
     cn.setFromCollideMask(COLLISIONMASKS['portals'])
     cn.setIntoCollideMask(BitMask32.allOff())
     np = self.bluePortal.attachNewNode(cn)
     cn.addSolid(CollisionSphere(0,0,0,2))
     h = CollisionHandlerEvent()
     h.addInPattern('%fn-into-%in')
     h.addOutPattern('%fn-outof-%in')
     self.base.cTrav.addCollider(np, h)
     cn = CollisionNode('orangePortal')
     cn.setFromCollideMask(COLLISIONMASKS['portals'])
     cn.setIntoCollideMask(BitMask32.allOff())
     np = self.orangePortal.attachNewNode(cn)
     cn.addSolid(CollisionSphere(0,0,0,2))
     h = CollisionHandlerEvent()
     h.addInPattern('%fn-into-%in')
     h.addOutPattern('%fn-outof-%in')
     self.base.cTrav.addCollider(np, h)
Пример #36
0
class Pickup(DirectObject):

    #Creates health pickup object
    def __init__(self, idappend, spawn):
        
        self.id = "pick"+str(idappend)
        self.deletePickup = False          
        self.projectileNode = NodePath('heal'+str(self.id))

        self.projectileNode.setScale(1)
        self.projectileModel = loader.loadModel("./resources/healthPickup.egg")
        self.projectileModel.setColorScale(200, 0, 0, 100)
        self.projectileModel.reparentTo(self.projectileNode)
        self.projectileNode.reparentTo(render)
        self.projectileNode.setPos(spawn)
        cs = CollisionSphere(0, 0, 0, .5)
        cnode = CollisionNode('heal')
        self.colNode = self.projectileModel.attachNewNode(cnode)
        self.colNode.node().addSolid(cs)
        self.collHand = CollisionHandlerEvent()
        self.collHand.addInPattern('pickupin'+str(self.id))
        self.collHand.addOutPattern('oot')
        base.cTrav.addCollider(self.colNode, self.collHand)
        self.accept('pickupin'+str(self.id), self.pickup)
   
    #Detects if the player has picked up the health
    def pickup(self, col):
        
        if col.getIntoNodePath().getName() == "cnode":

            messenger.send("pickuphealth")
            self.deletePickup = True

    #Destroys the health pickups from the scene graph
    def destroy(self):

        self.projectileNode.removeNode()
        self.projectileModel.removeNode()
        self.colNode.node().clearSolids()
        
        del self
Пример #37
0
class CollisionBase(ShowBase):
    def __init__(self):
        self.cTrav = CollisionTraverser()
        self.mchandler = CollisionHandlerEvent()
        self.mchandler.addInPattern('into-%in')
        self.mchandler.addAgainPattern('%fn-again-%in')
        self.mchandler.addOutPattern('out-%in')
Пример #38
0
 def setupEventSphere(self, bitmask, avatarRadius):
     self.avatarRadius = avatarRadius
     cSphere = CollisionSphere(0.0, 0.0, self.avatarRadius + 0.75, self.avatarRadius * 1.04)
     cSphere.setTangible(0)
     cSphereNode = CollisionNode('Flyer.cEventSphereNode')
     cSphereNode.addSolid(cSphere)
     cSphereNodePath = self.avatarNodePath.attachNewNode(cSphereNode)
     cSphereNode.setFromCollideMask(bitmask)
     cSphereNode.setIntoCollideMask(BitMask32.allOff())
     self.event = CollisionHandlerEvent()
     self.event.addInPattern('enter%in')
     self.event.addOutPattern('exit%in')
     self.cEventSphereNodePath = cSphereNodePath
Пример #39
0
 def setupFloorEventSphere(self, avatarNodePath, bitmask, avatarRadius):
     cSphere = CollisionSphere(0.0, 0.0, 0.0, 0.75)
     cSphereNode = CollisionNode('Flyer.cFloorEventSphere')
     cSphereNode.addSolid(cSphere)
     cSphereNodePath = avatarNodePath.attachNewNode(cSphereNode)
     cSphereNode.setFromCollideMask(bitmask)
     cSphereNode.setIntoCollideMask(BitMask32.allOff())
     self.floorCollisionEvent = CollisionHandlerEvent()
     self.floorCollisionEvent.addInPattern('%fn-enter-%in')
     self.floorCollisionEvent.addAgainPattern('%fn-again-%in')
     self.floorCollisionEvent.addOutPattern('%fn-exit-%in')
     base.cTrav.addCollider(cSphereNodePath, self.floorCollisionEvent)
     self.cFloorEventSphereNodePath = cSphereNodePath
Пример #40
0
 def setupHeadSphere(self, avatarNodePath):
     collSphere = CollisionSphere(0, 0, 0, 1)
     collSphere.setTangible(1)
     collNode = CollisionNode('Flyer.cHeadCollSphere')
     collNode.setFromCollideMask(ToontownGlobals.CeilingBitmask)
     collNode.setIntoCollideMask(BitMask32.allOff())
     collNode.addSolid(collSphere)
     self.cHeadSphereNodePath = avatarNodePath.attachNewNode(collNode)
     self.cHeadSphereNodePath.setZ(base.localAvatar.getHeight() + 1.0)
     self.headCollisionEvent = CollisionHandlerEvent()
     self.headCollisionEvent.addInPattern('%fn-enter-%in')
     self.headCollisionEvent.addOutPattern('%fn-exit-%in')
     base.cTrav.addCollider(self.cHeadSphereNodePath, self.headCollisionEvent)
Пример #41
0
  def __init__(self):
    #--Collision Handler------------------------------------------------------
    self.collHandler = CollisionHandlerEvent()
    self.collHandler.addInPattern('%fn-into-%in')
    base.cTrav = CollisionTraverser('world traverser')

    #--Mouse Control----------------------------------------------------------
    base.disableMouse()
    self.properties = WindowProperties()
    self.properties.setCursorHidden(True)
    base.win.requestProperties(self.properties)

    #--Register Hud Elements--------------------------------------------------
    self.instruction1 = self.addInstruction("[click] to Shoot",2)
    self.instruction2 = self.addInstruction("[a] to accelerate", 1)
    self.instruction3 = self.addInstruction("[esc] to quit", 0)

    self.scoreHud = self.addHudElement("", 0)
    self.accuracy = self.addHudElement("", 1)
    self.speedHud = self.addHudElement("", 2)

    self.bigHud = OnscreenText(text="", style=1, fg=(1,1,1,1), pos=(0,0), align=TextNode.ACenter, scale = .1)

    #--Load Objects and Models------------------------------------------------
    self.ship = Ship(self.collHandler)
    self.loadSkyBox()
    game.camera.reparentTo(self.ship.getModel())

    #--Start Game-------------------------------------------------------------
    self.asteroids = []
    self.resetGame()

    #--Controls --------------------------------------------------------------
    self.keysDown = {'a': 0}

    self.controlTask = taskMgr.add(self.gameLoop, "game-control-task")
    self.controlTask.lastTime = 0

    self.accept("escape", sys.exit, [0])
    self.accept("a", self.keyDown, ['a'])
    self.accept("a-up", self.keyUp, ['a'])
    self.accept("mouse1", self.shoot)
    self.accept("space", self.shoot)
    self.accept("resetgame", self.gameOver)

    if(DEBUG_CONTROLS):
      self.accept("0", self.ship.stop)
      self.accept("9", self.ship.getModel().setHpr, [0,0,0])

    #--Register CollisionEvent Handlers---------------------------------------
    self.accept('asteroid-into-bullet', self.bulletAsteroidCollision)
Пример #42
0
    def __init__(self, _main):
        self.main = _main
        self.name = ""
        self.points = 0
        self.health = 100.0
        self.runSpeed = 1.8
        self.keyMap = {
            "left":False,
            "right":False,
            "up":False,
            "down":False
            }
        base.camera.setPos(0,0,0)
        self.model = loader.loadModel("Player")
        self.model.find('**/+SequenceNode').node().stop()
        self.model.find('**/+SequenceNode').node().pose(0)
        base.camera.setP(-90)
        self.playerHud = Hud()
        self.playerHud.hide()
        self.model.hide()

        # Weapons: size=2, 0=main, 1=offhand
        self.mountSlot = []
        self.activeWeapon = None
        self.isAutoActive = False
        self.trigger = False
        self.lastShot = 0.0
        self.fireRate = 0.0

        self.playerTraverser = CollisionTraverser()
        self.playerEH = CollisionHandlerEvent()
        ## INTO PATTERNS
        self.playerEH.addInPattern('intoPlayer-%in')
        #self.playerEH.addInPattern('colIn-%fn')
        self.playerEH.addInPattern('intoHeal-%in')
        self.playerEH.addInPattern('intoWeapon-%in')
        ## OUT PATTERNS
        self.playerEH.addOutPattern('outOfPlayer-%in')
        playerCNode = CollisionNode('playerSphere')
        playerCNode.setFromCollideMask(BitMask32.bit(1))
        playerCNode.setIntoCollideMask(BitMask32.bit(1))
        self.playerSphere = CollisionSphere(0, 0, 0, 0.6)
        playerCNode.addSolid(self.playerSphere)
        self.playerNP = self.model.attachNewNode(playerCNode)
        self.playerTraverser.addCollider(self.playerNP, self.playerEH)
        #self.playerNP.show()

        self.playerPusher = CollisionHandlerPusher()
        self.playerPusher.addCollider(self.playerNP, self.model)
        self.playerPushTraverser = CollisionTraverser()
        self.playerPushTraverser.addCollider(self.playerNP, self.playerPusher)
Пример #43
0
    def setupCollision(self):
        base.cTrav = CollisionTraverser()
        self.collisionHandlerEvent = CollisionHandlerEvent()
        self.collisionHandlerEvent.addInPattern('into-%in')
        self.collisionHandlerEvent.addOutPattern('outof-%in')

        hitBox = CollisionBox(  Point3(7,0,-4.5) , 0.5,5,0.5)
        cnodePath = self.player.attachNewNode( CollisionNode('marioHitBox') )
        cnodePath.node().addSolid(hitBox)
        cnodePath.show()
        base.cTrav.addCollider(cnodePath, self.collisionHandlerEvent)

        stairs1 =  self.scene.find("root/bottomstair")
        hitBox = CollisionBox(  Point3(-6.8,0,-3.0) , 0.5,5,2.5)
        cnodePath = stairs1.attachNewNode( CollisionNode('stairsHitBox') )
        cnodePath.node().addSolid(hitBox)


        cnodePath.show()

        self.accept('into-stairsHitBox', self.enableStair)
        self.accept('outof-stairsHitBox', self.disableStair)
        base.cTrav.showCollisions(self.render)
 def loadAttack(self):
     self.weapon = loader.loadModel('phase_5/models/props/bounced-check.bam')
     self.weapon.setScale(10)
     self.weapon.setTwoSided(1)
     self.bounceSound = base.audio3d.loadSfx('phase_5/audio/sfx/SA_bounce_check_bounce.ogg')
     base.audio3d.attachSoundToObject(self.bounceSound, self.suit)
     cSphere = CollisionSphere(0, 0, 0, 0.1)
     cSphere.setTangible(0)
     if hasattr(self, 'uniqueName'):
         name = self.uniqueName('bounced_check_collision')
     else:
         name = 'bounced_check_collision'
     cNode = CollisionNode(name)
     cNode.addSolid(cSphere)
     cNode.setFromCollideMask(CIGlobals.FloorBitmask)
     cNP = self.weapon.attachNewNode(cNode)
     cNP.setCollideMask(BitMask32(0))
     self.event = CollisionHandlerEvent()
     self.event.setInPattern('%fn-into')
     self.event.setOutPattern('%fn-out')
     base.cTrav.addCollider(cNP, self.event)
     self.wsnp = cNP
     self.wsnp.show()
Пример #45
0
    def __init__(self, world):
        self.world = world
        self.root = self.world.root.attach_new_node("player")
        self.root_target = self.world.root.attach_new_node("player_target")
        self.pivot = self.root.attach_new_node("player_pivot")
        base.camera.reparent_to(self.pivot)
        base.camera.set_z(1.7)
        base.cam.node().get_lens().set_fov(90)
        self.traverser = CollisionTraverser()
        self.ray = setup_ray(
            self.pivot,
            self.traverser,
            self.world.mask,
            # ray ends well below feet to register downward slopes
            (0, 0, 1),
            (0, 0, -1))
        self.xyh_inertia = Vec3(0, 0, 0)
        h_acc = ConfigVariableDouble('mouse-accelleration', 0.1).get_value()
        self.xyh_acceleration = Vec3(0.8, 0.8, h_acc)
        self.friction = 0.15
        self.torque = 0.5
        self.last_up = Vec3(0, 0, 1)

        # Collider for portals
        csphere = CollisionSphere(0, 0, 1.25, 1.5)
        cnode = CollisionNode('player')
        cnode.add_solid(csphere)
        cnode.set_from_collide_mask(0x2)
        cnode.set_into_collide_mask(CollideMask.all_off())
        self.collider = self.root.attach_new_node(cnode)
        self.event_handler = CollisionHandlerEvent()
        self.event_handler.add_in_pattern('into-%in')
        self.traverser.add_collider(self.collider, self.event_handler)
        self.collider.show()
        self.teleported = False

        base.input.set_mouse_relativity(True)
 def setupCollisions(self):
     sphere = CollisionSphere(0, 0, 0, 0.1)
     collnode = CollisionNode('bulletCollNode-' + str(id(self)))
     collnode.addSolid(sphere)
     self.collnp = self.bullet.attachNewNode(collnode)
     self.collnp.setCollideMask(BitMask32(0))
     self.collnp.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask | CIGlobals.EventBitmask)
     event = CollisionHandlerEvent()
     event.setInPattern('%fn-into')
     event.setOutPattern('%fn-out')
     base.cTrav.addCollider(self.collnp, event)
 def buildCollisions(self):
     gagSph = CollisionSphere(0, 1.5, 0, 2)
     gagSensor = CollisionNode('gagSensor')
     gagSensor.addSolid(gagSph)
     sensorNP = self.gag.attachNewNode(gagSensor)
     sensorNP.setCollideMask(BitMask32(0))
     sensorNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern("%fn-into")
     event.set_out_pattern("%fn-out")
     base.cTrav.addCollider(sensorNP, event)
     self.avatar.acceptOnce('gagSensor-into', self.onCollision)
 def buildCollisions(self, entity):
     pieSphere = CollisionSphere(0, 0, 0, 1)
     pieSensor = CollisionNode('gagSensor')
     pieSensor.addSolid(pieSphere)
     pieNP = entity.attachNewNode(pieSensor)
     pieNP.setCollideMask(BitMask32(0))
     pieNP.node().setFromCollideMask(CIGlobals.WallBitmask | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.add_collider(pieNP, event)
     self.avatar.acceptOnce('gagSensor-into', self.onCollision)
Пример #49
0
 def buildCollisions(self):
     pieSphere = CollisionSphere(0, 0, 0, 1)
     pieSensor = CollisionNode('turretGagSensor' + str(id(self)))
     pieSensor.addSolid(pieSphere)
     pieNP = self.gag.attachNewNode(pieSensor)
     pieNP.setCollideMask(BitMask32(0))
     pieNP.node().setFromCollideMask(CIGlobals.WallBitmask
                                     | CIGlobals.FloorBitmask)
     event = CollisionHandlerEvent()
     event.set_in_pattern('%fn-into')
     event.set_out_pattern('%fn-out')
     base.cTrav.addCollider(pieNP, event)
Пример #50
0
    def __init__( self ):
        # Initialize the traverser.
        base.cTrav = CollisionTraverser()
 
        # Initialize the handler.
        self.collHandEvent = CollisionHandlerEvent()
        self.collHandEvent.addInPattern('into-%in')
        self.collHandEvent.addOutPattern('outof-%in')
 
        # Make a variable to store the unique collision string count.
        self.collCount = 0
 
        # Load a model. Reparent it to the camera so we can move it.
        s = loader.loadModel('smiley')	
        s.reparentTo(camera)
        s.setPos(0, 25, 0)
 
        # Setup a collision solid for this model.
        sColl = self.initCollisionSphere(s, True)
 
        # Add this object to the traverser.
        base.cTrav.addCollider(sColl[0], self.collHandEvent)
 
        # Accept the events sent by the collisions.
        self.accept('into-' + sColl[1], self.collide3)
        self.accept('outof-' + sColl[1], self.collide4)
        print(sColl[1])
 
        # Load another model.
        t = loader.loadModel('smiley')
        t.reparentTo(render)
        t.setPos(5, 25, 0)
 
        # Setup a collision solid for this model.
        tColl = self.initCollisionSphere(t, True)
 
        # Add this object to the traverser.
        base.cTrav.addCollider(tColl[0], self.collHandEvent)
 
        # Accept the events sent by the collisions.
        self.accept('into-' + tColl[1], self.collide)
        self.accept('outof-' + tColl[1], self.collide2)
        print(tColl[1])
 
        print("WERT")
Пример #51
0
    def pieCollisions(self):
        pss = CollisionSphere(0, 0, 0, 1)
        psnode = CollisionNode('projectilePieSensor' + str(id(self)))
        psnode.add_solid(pss)
        self.psnp = self.pie.attach_new_node(psnode)
        self.psnp.set_collide_mask(BitMask32(0))
        self.psnp.node().set_from_collide_mask(CIGlobals.WallBitmask
                                               | CIGlobals.FloorBitmask)

        event = CollisionHandlerEvent()
        event.set_in_pattern("%fn-into")
        event.set_out_pattern("%fn-out")
        base.cTrav.add_collider(self.psnp, event)
Пример #52
0
    def __init__(self, camera, look, id):
        
        #nodepath of the projectile, give it a trajectory
        self.projectileNode = NodePath('projectile'+str(id))
        self.projectileNode.setTransparency(TransparencyAttrib.MAlpha)
        self.projectileNode.reparentTo(render)
        
        #by passing the camera node form the camMov object, all projectiles are spawned 5 units in front of the camera
        self.projectileNode.setHpr(look, 0, 0, 0)
        self.projectileNode.setPos(camera,-1,10, 3)
        
        #fix z position to line up with gun
        self.projectileNode.setScale(.1)
        projectileModel = loader.loadModel("./resources/cubeShot.egg")
        projectileModel.setColorScale(0, 0, 0, .5)
        projectileModel.setSz(50)
        projectileModel.setSy(1)
        projectileModel.setSx(50)
        projectileModel.reparentTo(self.projectileNode)
    	
        #must calculate unit vector based on direction
        dir = render.getRelativeVector(look, Vec3(0, 1, 0))
    	
        #speed up or slow down projectiles here
        dir = dir*10
        self.vec = dir
        
        #base.cTrav = CollisionTraverser()
        cs = CollisionSphere(0, 0, 0, 25)
        cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
        cnodepath.node().addSolid(cs)
        self.collHand = CollisionHandlerEvent()
        self.collHand.addInPattern('into'+str(id))
        self.collHand.addOutPattern('outof')
        
        #cTrav has the distinction of global colider handler
        base.cTrav.addCollider(cnodepath, self.collHand)
        self.acceptOnce('into'+str(id), self.hit)
      
	    #deal with colliding or special effects here.
	    #wanted projectiles to be short lived
	    #so i will make them delete themselves after impact or time expired
        #writing a task that will rek the projectiles at the end of time
        self.damage = 20
Пример #53
0
    def __init__(self, idappend, spawn):
        
        self.id = "pick"+str(idappend)
        self.deletePickup = False          
        self.projectileNode = NodePath('heal'+str(self.id))

        self.projectileNode.setScale(1)
        self.projectileModel = loader.loadModel("./resources/healthPickup.egg")
        self.projectileModel.setColorScale(200, 0, 0, 100)
        self.projectileModel.reparentTo(self.projectileNode)
        self.projectileNode.reparentTo(render)
        self.projectileNode.setPos(spawn)
        cs = CollisionSphere(0, 0, 0, .5)
        cnode = CollisionNode('heal')
        self.colNode = self.projectileModel.attachNewNode(cnode)
        self.colNode.node().addSolid(cs)
        self.collHand = CollisionHandlerEvent()
        self.collHand.addInPattern('pickupin'+str(self.id))
        self.collHand.addOutPattern('oot')
        base.cTrav.addCollider(self.colNode, self.collHand)
        self.accept('pickupin'+str(self.id), self.pickup)
Пример #54
0
 def loadAttack(self):
     self.weapon = loader.loadModel('phase_5/models/props/bounced-check.bam')
     self.weapon.setScale(10)
     self.weapon.setTwoSided(1)
     self.bounceSound = base.audio3d.loadSfx('phase_5/audio/sfx/SA_bounce_check_bounce.mp3')
     base.audio3d.attachSoundToObject(self.bounceSound, self.suit)
     cSphere = CollisionSphere(0, 0, 0, 0.1)
     cSphere.setTangible(0)
     if hasattr(self, 'uniqueName'):
         name = self.uniqueName('bounced_check_collision')
     else:
         name = 'bounced_check_collision'
     cNode = CollisionNode(name)
     cNode.addSolid(cSphere)
     cNode.setFromCollideMask(CIGlobals.FloorBitmask)
     cNP = self.weapon.attachNewNode(cNode)
     cNP.setCollideMask(BitMask32(0))
     self.event = CollisionHandlerEvent()
     self.event.setInPattern('%fn-into')
     self.event.setOutPattern('%fn-out')
     base.cTrav.addCollider(cNP, self.event)
     self.wsnp = cNP
     self.wsnp.show()
Пример #55
0
 def setupTire(self, avId, index):
     tireNp, tireBody, tireOdeGeom = self.createTire(index)
     self.tireDict[avId] = {'tireNodePath': tireNp,
      'tireBody': tireBody,
      'tireOdeGeom': tireOdeGeom}
     if avId <= 0:
         tireBlocker = tireNp.find('**/tireblockermesh')
         if not tireBlocker.isEmpty():
             tireBlocker.hide()
     if avId == self.localAvId:
         tireNp = self.tireDict[avId]['tireNodePath']
         self.treasureSphereName = 'treasureCollider'
         self.treasureCollSphere = CollisionSphere(0, 0, 0, IceGameGlobals.TireRadius)
         self.treasureCollSphere.setTangible(0)
         self.treasureCollNode = CollisionNode(self.treasureSphereName)
         self.treasureCollNode.setFromCollideMask(ToontownGlobals.PieBitmask)
         self.treasureCollNode.addSolid(self.treasureCollSphere)
         self.treasureCollNodePath = tireNp.attachNewNode(self.treasureCollNode)
         self.treasureHandler = CollisionHandlerEvent()
         self.treasureHandler.addInPattern('%fn-intoTreasure')
         base.cTrav.addCollider(self.treasureCollNodePath, self.treasureHandler)
         eventName = '%s-intoTreasure' % self.treasureCollNodePath.getName()
         self.notify.debug('eventName = %s' % eventName)
         self.accept(eventName, self.toonHitSomething)
Пример #56
0
    def __init__(self, spawn, taregt, id):
        
        self.projectileNode = NodePath('projectile'+str(id))
        self.projectileNode.reparentTo(render)

        self.projectileNode.setPos(spawn,0,-10, 0)
        self.projectileNode.setScale(1.5)
        self.projectileModel = Actor("./resources/sphereShot",{"grow":"./resources/sphereShot-grow"})
        self.projectileModel.setColorScale(200, 0, 255, 100)
        self.projectileModel.reparentTo(self.projectileNode)
        self.projectileNode.setHpr(spawn, 0, 0, 0)


        dir = render.getRelativeVector(spawn, Vec3(0, 1, 0))
        self.vec = dir*-100
        cs = CollisionSphere(0, 0, 0, 2.5)
        cnodepath = self.projectileNode.attachNewNode(CollisionNode('projNode'))
        cnodepath.node().addSolid(cs)
        self.collHand = CollisionHandlerEvent()
        self.collHand.addInPattern('bossProjectileinto'+str(id))
        self.collHand.addOutPattern('outof')
        base.cTrav.addCollider(cnodepath, self.collHand)
        self.acceptOnce('bossProjectileinto'+str(id), self.hit)
        self.damage = 15
Пример #57
0
class BounceCheckAttack(ThrowAttack):
    notify = directNotify.newCategory('BounceCheckAttack')
    MaxBounces = 3
    WeaponHitDistance = 0.5

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

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

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

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

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

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

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

    def cleanup(self):
        taskMgr.remove('pollCheckDistance')
        self.ignore(self.wsnp.node().getName() + '-into')
        self.bounceSound = None
        ThrowAttack.cleanup(self)
        return
Пример #58
0
    def loadLevel(self, level):

        #Resets

        self.avatarActor = Actor("models/panda",
                                {"walk": "models/panda-walk"})
        self.avatarActor.setScale(.5, .5, .5)
        self.avatarActor.setHpr(180, 0, 0)
        self.avatarActor.setCollideMask(BitMask32.allOff())

        self.asteroidManager = AsteroidManager()

        #Alternate modes

        if int(self.level) == self.level: self.play_mode = TERRAIN

        else: self.play_mode = SPACE

        #Specifics

        if self.play_mode == SPACE:

            self.avatar = Avatar(self.avatarActor)
            self.avatar.objectNP.reparentTo(render)

            ########## Sky #########

            cubeMap = loader.loadCubeMap(self.loadSpaceTexture(self.level))
            self.spaceSkyBox = loader.loadModel('models/box')

            self.spaceSkyBox.setScale(100)
            self.spaceSkyBox.setBin('background', 0)
            self.spaceSkyBox.setDepthWrite(0)
            self.spaceSkyBox.setTwoSided(True)
            self.spaceSkyBox.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap)
            self.spaceSkyBox.setTexture(cubeMap, 1)
            #self.spaceSkyBox.setEffect(CompassEffect.make(render))

            parentNP = render.attachNewNode('parent')

            self.spaceSkyBox.reparentTo(parentNP)
            self.spaceSkyBox.setPos(-self.spaceSkyBox.getSx()/2, -self.spaceSkyBox.getSy()/2, 
                                    -self.spaceSkyBox.getSz()/2)

            self.asteroidManager.initialize(self.level)

        elif self.play_mode == TERRAIN:

            ########## Terrain #########

            #self.environ = loader.loadModel("../mystuff/test.egg")
            self.environ = loader.loadModel("models/environment")
            self.environ.setName("terrain")
            self.environ.reparentTo(render)
            self.environ.setPos(0, 0, 0)
            self.environ.setCollideMask(BitMask32.bit(0))

            ######### Models #########

            ######### Physics #########

            base.enableParticles()

            gravityForce = LinearVectorForce(0, 0, -9.81)
            gravityForce.setMassDependent(False)
            gravityFN = ForceNode("world-forces")
            gravityFN.addForce(gravityForce)
            render.attachNewNode(gravityFN)
            base.physicsMgr.addLinearForce(gravityForce)

            self.avatarPhysicsActorNP = render.attachNewNode(ActorNode("player"))
            self.avatarPhysicsActorNP.node().getPhysicsObject().setMass(50.)
            self.avatarActor.reparentTo(self.avatarPhysicsActorNP)
            base.physicsMgr.attachPhysicalNode(self.avatarPhysicsActorNP.node())

            self.avatarPhysicsActorNP.setPos(15, 10, 5)

            ######### Game objects #########

            self.avatar = Avatar(self.avatarPhysicsActorNP)

            ######### Collisions #########

            self.cTrav = CollisionTraverser()

            #Make player rigid body

            self.pandaBodySphere = CollisionSphere(0, 0, 4, 3)

            self.pandaBodySphereNode = CollisionNode("playerBodyRay")
            self.pandaBodySphereNode.addSolid(self.pandaBodySphere)
            self.pandaBodySphereNode.setFromCollideMask(BitMask32.bit(0))
            self.pandaBodySphereNode.setIntoCollideMask(BitMask32.allOff())

            self.pandaBodySphereNodepath = self.avatar.objectNP.attachNewNode(self.pandaBodySphereNode)
            self.pandaBodySphereNodepath.show()

            self.pandaBodyCollisionHandler = PhysicsCollisionHandler()
            self.pandaBodyCollisionHandler.addCollider(self.pandaBodySphereNodepath, self.avatar.objectNP)

            #Keep player on ground

            self.pandaGroundSphere = CollisionSphere(0, 0, 1, 1)

            self.pandaGroundSphereNode = CollisionNode("playerGroundRay")
            self.pandaGroundSphereNode.addSolid(self.pandaGroundSphere)
            self.pandaGroundSphereNode.setFromCollideMask(BitMask32.bit(0))
            self.pandaGroundSphereNode.setIntoCollideMask(BitMask32.allOff())

            self.pandaGroundSphereNodepath = self.avatar.objectNP.attachNewNode(self.pandaGroundSphereNode)
            self.pandaGroundSphereNodepath.show()

            self.pandaGroundCollisionHandler = PhysicsCollisionHandler()
            self.pandaGroundCollisionHandler.addCollider(self.pandaGroundSphereNodepath, self.avatar.objectNP)

            #Notify when player lands

            self.pandaGroundRayJumping = CollisionSphere(0, 0, 1, 1)

            self.pandaGroundRayNodeJumping = CollisionNode("playerGroundRayJumping")
            self.pandaGroundRayNodeJumping.addSolid(self.pandaGroundRayJumping)
            self.pandaGroundRayNodeJumping.setFromCollideMask(BitMask32.bit(0))
            self.pandaGroundRayNodeJumping.setIntoCollideMask(BitMask32.allOff())

            self.pandaGroundRayNodepathJumping = self.avatar.objectNP.attachNewNode(self.pandaGroundRayNodeJumping)
            self.pandaGroundRayNodepathJumping.show()

            self.collisionNotifier = CollisionHandlerEvent()
            self.collisionNotifier.addInPattern("%fn-in")
            self.collisionNotifier.addOutPattern("%fn-out")

            self.cTrav.addCollider(self.pandaGroundSphereNodepath, self.pandaGroundCollisionHandler)
            self.cTrav.addCollider(self.pandaGroundRayNodepathJumping, self.collisionNotifier)
            self.cTrav.addCollider(self.pandaBodySphereNodepath, self.pandaBodyCollisionHandler)
Пример #59
0
class GameContainer(ShowBase):

    def __init__(self):

        ShowBase.__init__(self)

        ########## Window configuration #########

        wp = WindowProperties()
        wp.setSize(1024, 860)

        self.win.requestProperties(wp)

        ########## Gameplay settings #########

        self.GAME_MODE = PLAY
        self.play_mode = SPACE

        self.level = 1.5

        self.mode_initialized = False

        ######### Camera #########

        self.disableMouse()

        self.mainCamera = Camera(self.camera)

        self.mainCamera.camObject.setHpr(0, 0, 0)

        #Trigger game chain

        self.loadLevel(LEVEL)

        ######### Events #########

        self.taskMgr.add(self.gameLoop, "gameLoop", priority = 35)

        self.keys = {"w" : 0, "s" : 0, "a" : 0, "d" : 0, "space" : 0}

        self.accept("w", self.setKey, ["w", 1])
        self.accept("w-up", self.setKey, ["w", 0])
        self.accept("s", self.setKey, ["s", 1])
        self.accept("s-up", self.setKey, ["s", 0])
        self.accept("a", self.setKey, ["a", 1])
        self.accept("a-up", self.setKey, ["a", 0])
        self.accept("d", self.setKey, ["d", 1])
        self.accept("d-up", self.setKey, ["d", 0])
        self.accept("space", self.setKey, ["space", 1])
        self.accept("space-up", self.setKey, ["space", 0])
        self.accept("wheel_up", self.zoomCamera, [-1])
        self.accept("wheel_down", self.zoomCamera, [1])
        self.accept("escape", self.switchGameMode, [IN_GAME_MENU])

        self.accept("window-event", self.handleWindowEvent)

        self.accept("playerGroundRayJumping-in", self.avatar.handleCollisionEvent, ["in"])
        self.accept("playerGroundRayJumping-out", self.avatar.handleCollisionEvent, ["out"])

        ######### GUI #########

        self.gui_elements = []

    def loadSpaceTexture(self, level):

        if level < 10: return 'textures/space#.jpg'
        elif level < 15: pass  

    def loadLevel(self, level):

        #Resets

        self.avatarActor = Actor("models/panda",
                                {"walk": "models/panda-walk"})
        self.avatarActor.setScale(.5, .5, .5)
        self.avatarActor.setHpr(180, 0, 0)
        self.avatarActor.setCollideMask(BitMask32.allOff())

        self.asteroidManager = AsteroidManager()

        #Alternate modes

        if int(self.level) == self.level: self.play_mode = TERRAIN

        else: self.play_mode = SPACE

        #Specifics

        if self.play_mode == SPACE:

            self.avatar = Avatar(self.avatarActor)
            self.avatar.objectNP.reparentTo(render)

            ########## Sky #########

            cubeMap = loader.loadCubeMap(self.loadSpaceTexture(self.level))
            self.spaceSkyBox = loader.loadModel('models/box')

            self.spaceSkyBox.setScale(100)
            self.spaceSkyBox.setBin('background', 0)
            self.spaceSkyBox.setDepthWrite(0)
            self.spaceSkyBox.setTwoSided(True)
            self.spaceSkyBox.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap)
            self.spaceSkyBox.setTexture(cubeMap, 1)
            #self.spaceSkyBox.setEffect(CompassEffect.make(render))

            parentNP = render.attachNewNode('parent')

            self.spaceSkyBox.reparentTo(parentNP)
            self.spaceSkyBox.setPos(-self.spaceSkyBox.getSx()/2, -self.spaceSkyBox.getSy()/2, 
                                    -self.spaceSkyBox.getSz()/2)

            self.asteroidManager.initialize(self.level)

        elif self.play_mode == TERRAIN:

            ########## Terrain #########

            #self.environ = loader.loadModel("../mystuff/test.egg")
            self.environ = loader.loadModel("models/environment")
            self.environ.setName("terrain")
            self.environ.reparentTo(render)
            self.environ.setPos(0, 0, 0)
            self.environ.setCollideMask(BitMask32.bit(0))

            ######### Models #########

            ######### Physics #########

            base.enableParticles()

            gravityForce = LinearVectorForce(0, 0, -9.81)
            gravityForce.setMassDependent(False)
            gravityFN = ForceNode("world-forces")
            gravityFN.addForce(gravityForce)
            render.attachNewNode(gravityFN)
            base.physicsMgr.addLinearForce(gravityForce)

            self.avatarPhysicsActorNP = render.attachNewNode(ActorNode("player"))
            self.avatarPhysicsActorNP.node().getPhysicsObject().setMass(50.)
            self.avatarActor.reparentTo(self.avatarPhysicsActorNP)
            base.physicsMgr.attachPhysicalNode(self.avatarPhysicsActorNP.node())

            self.avatarPhysicsActorNP.setPos(15, 10, 5)

            ######### Game objects #########

            self.avatar = Avatar(self.avatarPhysicsActorNP)

            ######### Collisions #########

            self.cTrav = CollisionTraverser()

            #Make player rigid body

            self.pandaBodySphere = CollisionSphere(0, 0, 4, 3)

            self.pandaBodySphereNode = CollisionNode("playerBodyRay")
            self.pandaBodySphereNode.addSolid(self.pandaBodySphere)
            self.pandaBodySphereNode.setFromCollideMask(BitMask32.bit(0))
            self.pandaBodySphereNode.setIntoCollideMask(BitMask32.allOff())

            self.pandaBodySphereNodepath = self.avatar.objectNP.attachNewNode(self.pandaBodySphereNode)
            self.pandaBodySphereNodepath.show()

            self.pandaBodyCollisionHandler = PhysicsCollisionHandler()
            self.pandaBodyCollisionHandler.addCollider(self.pandaBodySphereNodepath, self.avatar.objectNP)

            #Keep player on ground

            self.pandaGroundSphere = CollisionSphere(0, 0, 1, 1)

            self.pandaGroundSphereNode = CollisionNode("playerGroundRay")
            self.pandaGroundSphereNode.addSolid(self.pandaGroundSphere)
            self.pandaGroundSphereNode.setFromCollideMask(BitMask32.bit(0))
            self.pandaGroundSphereNode.setIntoCollideMask(BitMask32.allOff())

            self.pandaGroundSphereNodepath = self.avatar.objectNP.attachNewNode(self.pandaGroundSphereNode)
            self.pandaGroundSphereNodepath.show()

            self.pandaGroundCollisionHandler = PhysicsCollisionHandler()
            self.pandaGroundCollisionHandler.addCollider(self.pandaGroundSphereNodepath, self.avatar.objectNP)

            #Notify when player lands

            self.pandaGroundRayJumping = CollisionSphere(0, 0, 1, 1)

            self.pandaGroundRayNodeJumping = CollisionNode("playerGroundRayJumping")
            self.pandaGroundRayNodeJumping.addSolid(self.pandaGroundRayJumping)
            self.pandaGroundRayNodeJumping.setFromCollideMask(BitMask32.bit(0))
            self.pandaGroundRayNodeJumping.setIntoCollideMask(BitMask32.allOff())

            self.pandaGroundRayNodepathJumping = self.avatar.objectNP.attachNewNode(self.pandaGroundRayNodeJumping)
            self.pandaGroundRayNodepathJumping.show()

            self.collisionNotifier = CollisionHandlerEvent()
            self.collisionNotifier.addInPattern("%fn-in")
            self.collisionNotifier.addOutPattern("%fn-out")

            self.cTrav.addCollider(self.pandaGroundSphereNodepath, self.pandaGroundCollisionHandler)
            self.cTrav.addCollider(self.pandaGroundRayNodepathJumping, self.collisionNotifier)
            self.cTrav.addCollider(self.pandaBodySphereNodepath, self.pandaBodyCollisionHandler)

    def maintainTurrets(self):

        pass

    def setKey(self, key, value):

        self.keys[key] = value

    def zoomCamera(self, direction):

        Camera.AVATAR_DIST += direction

    def b(self, hey):

        self.avatarLanded = True

    def handleWindowEvent(self, window=None):

        wp = window.getProperties()

        self.win_center_x = wp.getXSize() / 2
        self.win_center_y = wp.getYSize() / 2

    def switchGameMode(self, newGameMode=None):

        self.cleanupGUI()

        if self.GAME_MODE == IN_GAME_MENU: 

            if newGameMode == PLAY:

                render.clearFog()

            elif newGameMode == MAIN_MENU:

                pass

        elif True:

            pass

        self.GAME_MODE = newGameMode

        self.mode_initialized = False

    def cleanupGUI(self):

        for gui_element in self.gui_elements:

            gui_element.destroy()

    def evenButtonPositions(self, button_spacing, button_height, num_buttons):

        center_offset = (button_spacing/(2.0) if (num_buttons % 2 == 0) else 0)

        button_positions = []

        current_pos = center_offset + ((num_buttons - 1)/2) * button_spacing

        for i in range(0, num_buttons):

            button_positions.append(current_pos + (button_height/2.0))

            current_pos -= button_spacing

        return button_positions

    def buildInGameMenu(self):

        props = WindowProperties()
        props.setCursorHidden(False) 
        base.win.requestProperties(props)

        resume_button = DirectButton(text = "Resume", scale = .1, command = (lambda: self.switchGameMode(PLAY)),
                                    rolloverSound=None)

        main_menu_button = DirectButton(text = "Main Menu", scale = .1, command = self.b,
                                    rolloverSound=None)

        options_button = DirectButton(text = "Options", scale = .1, command = self.b,
                                    rolloverSound=None)

        exit_button = DirectButton(text = "Exit", scale = .1, command = exit,
                                    rolloverSound=None)

        BUTTON_SPACING = .2
        BUTTON_HEIGHT = resume_button.getSy()

        button_positions = self.evenButtonPositions(BUTTON_SPACING, BUTTON_HEIGHT, 4)

        resume_button.setPos(Vec3(0, 0, button_positions[0]))
        main_menu_button.setPos(Vec3(0, 0, button_positions[1]))
        options_button.setPos(Vec3(0, 0, button_positions[2]))
        exit_button.setPos(Vec3(0, 0, button_positions[3]))

        self.gui_elements.append(resume_button)
        self.gui_elements.append(main_menu_button)
        self.gui_elements.append(options_button)
        self.gui_elements.append(exit_button)

    def buildMainMenu(self):

        props = WindowProperties()
        props.setCursorHidden(False) 
        base.win.requestProperties(props)

        start_game_button = DirectButton(text = "Start", scale = .1,
                            command = self.b)

        select_level_button = DirectButton(text = "Select Level", scale = .1,
                            command = self.b)

        game_options_button = DirectButton(text = "Options", scale = .1,
                            command = self.b)

        exit_button = DirectButton(text = "Exit", scale = .1,
                            command = exit)

        BUTTON_SPACING = .2
        BUTTON_HEIGHT = start_game_button.getSy()

        button_positions = self.evenButtonPositions(BUTTON_SPACING, BUTTON_HEIGHT)

        start_game_button.setPos(Vec3(0, 0, button_positions[0]))
        select_level_button.setPos(Vec3(0, 0, button_positions[1]))
        game_options_button.setPos(Vec3(0, 0, button_positions[2]))
        exit_button.setPos(Vec3(0, 0, button_positions[3]))

        self.gui_elements.append(start_game_button)
        self.gui_elements.append(select_level_button)
        self.gui_elements.append(game_options_button)
        self.gui_elements.append(exit_button)

    def gameLoop(self, task):

        #Compensate for inconsistent update intervals

        dt = globalClock.getDt()

        if self.GAME_MODE == MAIN_MENU:

            if not self.mode_initialized:

                self.buildMainMenu()

                self.mode_initialized = True

        if self.GAME_MODE == IN_GAME_MENU:

            if not self.mode_initialized:

                #Fog out background

                inGameMenuFogColor = (50, 150, 50)

                inGameMenuFog = Fog("inGameMenuFog")

                inGameMenuFog.setMode(Fog.MExponential)
                inGameMenuFog.setColor(*inGameMenuFogColor)
                inGameMenuFog.setExpDensity(.01)

                render.setFog(inGameMenuFog)

                self.buildInGameMenu()

                self.mode_initialized = True

        if self.GAME_MODE == PLAY:

            if not self.mode_initialized:

                props = WindowProperties()
                props.setCursorHidden(True) 
                base.win.requestProperties(props)

                self.last_mouse_x = self.win.getPointer(0).getX()
                self.last_mouse_y = self.win.getPointer(0).getY()

                self.mode_initialized = True

            if self.play_mode == TERRAIN:

                self.maintainTurrets()
                self.avatar.move(dt)

            elif self.play_mode == SPACE:

                self.asteroidManager.maintainAsteroidField(self.avatar.objectNP.getPos(), 
                                                           self.avatar.speed, dt)

            #Handle keyboard input

            self.avatar.handleKeys(self.keys, self.play_mode)

            ########## Mouse-based viewpoint rotation ##########

            mouse_pos = self.win.getPointer(0)

            current_mouse_x = mouse_pos.getX()
            current_mouse_y = mouse_pos.getY()

            #Side to side

            if self.play_mode == TERRAIN:

                mouse_shift_x = current_mouse_x - self.last_mouse_x
                self.last_mouse_x = current_mouse_x

                if current_mouse_x < 5 or current_mouse_x >= (self.win_center_x * 1.5):

                    base.win.movePointer(0, self.win_center_x, current_mouse_y)
                    self.last_mouse_x = self.win_center_x

                yaw_shift = -((mouse_shift_x) * Camera.ROT_RATE[0])

                self.avatar.yawRot += yaw_shift

                self.avatar.objectNP.setH(self.avatar.yawRot)

            #Up and down

            mouse_shift_y = current_mouse_y - self.last_mouse_y
            self.last_mouse_y = current_mouse_y

            if current_mouse_y < 5 or current_mouse_y >= (self.win_center_y * 1.5):

                base.win.movePointer(0, current_mouse_x, self.win_center_y)
                self.last_mouse_y = self.win_center_y

            pitch_shift = -((mouse_shift_y) * Camera.ROT_RATE[1])

            self.mainCamera.pitchRot += pitch_shift

            if self.mainCamera.pitchRot > Camera.FLEX_ROT_MAG[0]:

                self.mainCamera.pitchRot = Camera.FLEX_ROT_MAG[0]

            elif self.mainCamera.pitchRot < -Camera.FLEX_ROT_MAG[0]:

                self.mainCamera.pitchRot = -Camera.FLEX_ROT_MAG[0]

            xy_plane_cam_dist = Camera.AVATAR_DIST

            cam_x_adjust = xy_plane_cam_dist*sin(radians(self.avatar.yawRot))  
            cam_y_adjust = xy_plane_cam_dist*cos(radians(self.avatar.yawRot))
            cam_z_adjust = Camera.ELEVATION

            self.mainCamera.camObject.setH(self.avatar.yawRot)
            self.mainCamera.camObject.setP(self.mainCamera.pitchRot)

            self.mainCamera.camObject.setPos(self.avatar.objectNP.getX() + cam_x_adjust, self.avatar.objectNP.getY() - cam_y_adjust, 
                            self.avatar.objectNP.getZ() + cam_z_adjust)

            #Find collisions

            #self.cTrav.traverse(render)

            #print self.environ.getBounds()

        return Task.cont