コード例 #1
0
class App(ShowBase):
    def moveForward(self, catch):
        print('w key pressed')
        self.cy = 3.0
        print(self.current_pos)

    def moveBackward(self, catch):
        print('w key pressed')
        self.cy = -3.0
        print(self.current_pos)

    def moveLeft(self, catch):
        print('w key pressed')
        self.cx = 3.0
        print(self.current_pos)

    def moveRight(self, catch):
        print('w key pressed')
        self.cx = -3.0
        print(self.current_pos)

    def lookLeft(self, catch):
        self.current_omega = 120

    def lookRight(self, catch):
        self.current_omega = -120

    def lookUp(self, catch):
        self.current_hpr = (self.current_hpr[0], self.current_hpr[1] - 1,
                            self.current_hpr[2])

    def moveUp(self, catch):
        self.current_pos = (self.current_pos[0], self.current_pos[1],
                            self.current_pos[2] + 1)

    def lookUp(self, catch):
        self.current_hpr = (self.current_hpr[0], self.current_hpr[1] + 1,
                            self.current_hpr[2])

    def lookDown(self, catch):
        self.current_hpr = (self.current_hpr[0], self.current_hpr[1] - 1,
                            self.current_hpr[2])

    def fire(self, catch):
        print("Fire!")
        if self.pandaPos[0] == self.current_pos[0] and self.pandaPos[
                2] + 0.5 == self.current_pos[2] and not self.pandaPos[
                    1] == self.current_pos[1] and not self.pandaPos[
                        1] - 1 == self.current_pos[1] and not self.current_pos[
                            1] - 1 == self.pandaPos[1] and not self.current_pos[
                                1] > self.pandaPos[1]:
            print('Oof')

    def jump(self, catch):
        self.player.setMaxJumpHeight(5.0)
        self.player.setJumpSpeed(8.0)
        self.player.doJump()

    def __init__(self):
        ShowBase.__init__(self)
        #self.word = BulletWorld()
        self.cx = 0.0
        self.cy = 0.0
        self.current_omega = 0
        s = self.loader.loadSfx('Doom Soundtrack - Level 1 (Extended).mp3')
        s.play()
        self.current_pos = (10, 5, 1)
        self.current_hpr = (0, 0, 0)
        #self.fxboy = self.loader.loadModel("cubearm.egg")
        self.world = BulletWorld()
        self.world.setGravity(Vec3(0, 0, -12.0))
        #self.physicsMgr.attachPhysicalNode(self.camera)
        keyboard.on_press_key('w', self.moveForward)
        keyboard.on_press_key('s', self.moveBackward)
        keyboard.on_press_key('j', self.lookLeft)
        keyboard.on_press_key('y', self.lookUp)
        keyboard.on_press_key('h', self.lookDown)
        keyboard.on_press_key('g', self.lookRight)
        keyboard.on_press_key('d', self.moveLeft)
        #self.fxboy.reparentTo(self.render)
        #self.camera.reparentTo(self.render)
        #self.camera.reparentTo(self.fxboy)
        keyboard.on_press_key('a', self.moveRight)
        keyboard.on_press_key('space', self.fire)
        keyboard.on_press_key('2', self.jump)
        #keyboard.on_press_key('y',self.lookUp)
        keyboard.on_press_key('1', self.moveUp)

        self.cam = BulletCapsuleShape(radius, height - 2 * radius, ZUp)
        self.player = BulletCharacterControllerNode(self.cam, 0.4, 'Player')
        self.playernp = self.render.attachNewNode(self.player)
        self.world.attachCharacter(self.playernp.node())
        self.camera.reparentTo(self.playernp)
        self.playernp.setPos(self.current_pos)
        self.playernp.setHpr(self.current_hpr)
        self.playernp.setH(45)
        #self.player.setMass(10.0)
        # self.playernp.setCollideMask(BitMask32.allOn())
        self.disableMouse()

        self.scenes = BulletBoxShape(Vec3(0.25, 0.25, 0.25))
        self.scenenode = BulletRigidBodyNode('Scene')
        self.scenenode.setMass(12.0)
        self.scenenode.addShape(self.scenes)
        self.scenenp = render.attachNewNode(self.scenenode)
        self.scenenp.setPos(-8, 40, 0)
        self.world.attachRigidBody(self.scenenode)
        self.scene = self.loader.loadModel("models/environment.egg.pz")
        self.scene.reparentTo(self.render)
        self.scene.setScale(0.25, 0.25, 0.25)
        self.scene.setPos(-8, 40, 0)
        self.scene.reparentTo(self.scenenp)
        self.scenenode.setGravity(Vec3(0, 0, 0))

        #self.taskMgr.add(self.spinCameraTask,"SpinCameraTask")
        self.taskMgr.add(self.moveChar, "MoveChar")
        self.taskMgr.add(self.moveCBod, "MoveCBod")
        self.pandaActor = Actor("cubearm.egg",
                                {"walk": "cubearm4-ArmatureAction.egg"})
        self.pandaActor.setScale(0.12, 0.12, 0.12)
        self.pandaActor.setPos((10, 10, 0.5))
        self.pandaPos = (10, 10, 0.5)
        self.pandaActor.reparentTo(self.render)
        self.pandaActor.loop('walk')
        '''
        posInterval1 = self.pandaActor.posInterval(13,Point3(0,-10,0),startPos=Point3(0,10,0))
        posInterval2 = self.pandaActor.posInterval(13,Point3(0,10,0),startPos=Point3(0,-10,0))
        hprInterval1 = self.pandaActor.hprInterval(3,Point3(180,0,0),startHpr=Point3(0,0,0))
        hprInterval2 = self.pandaActor.hprInterval(3,Point3(0,0,0),startHpr=Point3(180,0,0))
        self.pandaPace = Sequence(posInterval1,hprInterval1,posInterval2,hprInterval2,name="pandaPace")
        self.pandaPace.loop()
        '''

    def spinCameraTask(self, task):
        print(task.time * 6.0)
        angleDegrees = task.time * 6.0
        angleRadians = angleDegrees * (pi / 180.0)
        self.camera.setPos(20 * sin(angleRadians), -20 * cos(angleRadians), 3)
        self.camera.setHpr(angleDegrees, 0, 0)
        return Task.cont

    def moveChar(self, task):
        speed = Vec3(0, 0, 0)
        omega = self.current_omega
        speed.setX(self.cx)
        speed.setY(self.cy)
        #self.scenenp.setPos(-8,40,0)
        print('[Scene]: ' + str(self.scenenp.getPos()))
        print('[Cam]: ' + str(self.playernp.getPos()))
        self.player.setAngularMovement(omega)
        #self.player.setLinearMovement(speed,True)
        #self.playernp.setPos(self.current_pos)
        self.playernp.setHpr(self.current_hpr)

        return task.cont

    def moveCBod(self, task):
        self.world.doPhysics(globalClock.getDt())
        return task.cont
コード例 #2
0
ファイル: Player.py プロジェクト: nextmatrixman/UpAllTheWay
class Player(object):
  def __init__(self, render, world, x, y, z):
    self.render = render
    self.world = world
    self.x = x
    self.y = y
    self.z = z
    
    # Game state variables
    self.isMoving = False
    self.isJumping = False
    
    # This is used to store which keys are currently pressed.
    self.keyMap = {"left": 0, "right": 0, "forward": 0, "reverse": 0}
    
    # Defining sound effects
    self.jumpSound = base.loader.loadSfx("sounds/jumping.wav")
    self.runSound = base.loader.loadSfx("sounds/running.ogg")
    
    self.createPlayer()
    
  def createPlayer(self):
    h = 1.75
    w = 0.4
    shape = BulletCapsuleShape(w, h - 2 * w, ZUp)

    self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
    #    self.character.setMass(1.0)
    self.characterNP = self.render.attachNewNode(self.character)
    self.characterNP.setPos(self.x, self.y, self.z)
    self.characterNP.setH(45)
    self.characterNP.setCollideMask(BitMask32.allOn())
    self.world.attachCharacter(self.character)

    self.actorNP = Actor('models/Bricker/Bricker3.egg', {
                     'run': 'models/Bricker/Bricker-run.egg',
                     'jump': 'models/Bricker/Bricker-jump.egg'})
    self.actorNP.reparentTo(self.characterNP)
    self.actorNP.setScale(0.3048)
    self.actorNP.setH(180)
    self.actorNP.setPos(0, 0, 0.27)
    
  def setKey(self, key, value):
    self.keyMap[key] = value
  
  def doJump(self):
    self.character.setMaxJumpHeight(5.0)
    self.character.setJumpSpeed(8.5)
    self.character.doJump()
    self.actorNP.play("jump")
    self.jumpSound.play()
  
  def move(self):
    speed = Vec3(0, 0, 0)
    omega = 0.0
    
    if self.keyMap["left"]:
      omega =  120.0
    if self.keyMap["right"]:
      omega = -120.0
    if self.keyMap["forward"]:
      speed.setY(4.0)
    if self.keyMap["reverse"]:
      speed.setY(-4.0)
      
    self.character.setAngularMovement(omega)
    self.character.setLinearMovement(speed, True)
    
    if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["reverse"]:
      if self.isMoving is False:
        self.actorNP.loop("run")
        self.runSound.play()
        self.isMoving = True
    else:
      if self.isMoving:
        self.actorNP.stop()
        self.runSound.stop()
        self.isMoving = False
  
  def getCharacterNP(self):
    return self.characterNP
  
  def getCharacter(self):
    return self.character
  
  def getActrorNP(self):
    return self.actorNP
  
  def resetCharacter(self):
    if (Data.currentLevel == 1):
      self.characterNP.setPos(0, 0, 0)
    else:
      self.characterNP.setPos(100, 100, 0)
コード例 #3
0
class Character2(object):
    def __init__(self):

        self.models = Models2()
        self.health = 100.0
        self.lost = 0
        self.won = 0
        self.debug = False
        self.ev = False
        self.re = False
        self.isMoving = False
        self.nextLevel = False
        self.b3 = 0

        self.setUp()
        self.setUpEnemies()
        taskMgr.add(self.update, 'update')
        taskMgr.add(self.updateItems, 'updateItems')
        taskMgr.add(self.updateEnemies, 'updateEnemies')
        taskMgr.add(self.updateEndPoint, 'updateEndPoint')

        self.mySoundRing = base.loader.loadSfx("sound/ring.mp3")
        self.mySoundPunch = base.loader.loadSfx("sound/punch_or_whack.mp3")
        self.mySoundEvil = base.loader.loadSfx("sound/Evil_Laugh_Male.mp3")
        self.mySoundEndFx = base.loader.loadSfx("sound/End_Fx.mp3")
        self.mySoundEnd = base.loader.loadSfx("sound/Fireworks.mp3")
        self.mySoundRunning = base.loader.loadSfx("sound/running.mp3")
        self.mySoundJump = base.loader.loadSfx("sound/jump.mp3")

    def setUpEnemies(self):
        h2 = 3.75
        w2 = 1.1
        shape2 = BulletCapsuleShape(w2, h2 - 2 * w2, ZUp)

        self.e1 = BulletRigidBodyNode("E1")
        self.e1.setMass(0)
        self.e1.addShape(shape2)
        self.e1NP = render.attachNewNode(self.e1)
        self.e1NP.setPos(self.models.box6.getX(), self.models.box6.getY(),
                         self.models.box6.getZ() + 3)
        self.e1NP.setCollideMask(BitMask32.allOn())
        self.models.world.attachRigidBody(self.e1)

        self.actorNPe1 = loader.loadModel('models/mummy/mummy.egg')

        self.actorNPe1.reparentTo(self.e1NP)
        self.actorNPe1.setScale(0.05)
        self.actorNPe1.setPos(0, 0, -1.0)
        self.e1Hited = 0

        h3 = 3.75
        w3 = 1.1
        shape3 = BulletCapsuleShape(w3, h3 - 2 * w3, ZUp)

        self.e2 = BulletRigidBodyNode("E2")
        self.e2.setMass(0)
        self.e2.addShape(shape3)
        self.e2NP = render.attachNewNode(self.e2)
        self.e2NP.setPos(self.models.Cylinder1.getX(),
                         self.models.Cylinder1.getY(),
                         self.models.Cylinder1.getZ() + 3)
        self.e2NP.setCollideMask(BitMask32.allOn())
        self.models.world.attachRigidBody(self.e2)

        self.actorNPe2 = loader.loadModel('models/mummy/mummy.egg')

        self.actorNPe2.reparentTo(self.e2NP)
        self.actorNPe2.setScale(0.05)
        self.actorNPe2.setPos(0, 0, -1.0)
        self.e2Hited = 0

        h4 = 3.75
        w4 = 1.1
        shape4 = BulletCapsuleShape(w4, h4 - 2 * w4, ZUp)

        self.e3 = BulletRigidBodyNode("E3")
        self.e3.setMass(0)
        self.e3.addShape(shape4)
        self.e3NP = render.attachNewNode(self.e3)
        self.e3NP.setPos(self.models.Cylinder2.getX(),
                         self.models.Cylinder2.getY(),
                         self.models.Cylinder2.getZ() + 3)
        self.e3NP.setCollideMask(BitMask32.allOn())
        self.models.world.attachRigidBody(self.e3)

        self.actorNPe3 = loader.loadModel('models/mummy/mummy.egg')

        self.actorNPe3.reparentTo(self.e3NP)
        self.actorNPe3.setScale(0.05)
        self.actorNPe3.setPos(0, 0, -1.0)
        self.e3Hited = 0

        h5 = 3.75
        w5 = 1.1
        shape5 = BulletCapsuleShape(w5, h5 - 2 * w5, ZUp)

        self.e4 = BulletRigidBodyNode("E4")
        self.e4.setMass(0)
        self.e4.addShape(shape5)
        self.e4NP = render.attachNewNode(self.e4)
        self.e4NP.setPos(self.models.Cylinder3.getX(),
                         self.models.Cylinder3.getY(),
                         self.models.Cylinder3.getZ() + 3)
        self.e4NP.setCollideMask(BitMask32.allOn())
        self.models.world.attachRigidBody(self.e4)

        self.actorNPe4 = loader.loadModel('models/mummy/mummy.egg')

        self.actorNPe4.reparentTo(self.e4NP)
        self.actorNPe4.setScale(0.05)
        self.actorNPe4.setPos(0, 0, -1.0)
        self.e4Hited = 0

    def setUp(self):
        self.itemNumber = 0
        self.incBar()

        # Character
        h = 1.75
        w = 0.4
        shape = BulletCapsuleShape(w, h - 2 * w, ZUp)

        self.character = BulletCharacterControllerNode(shape, 0.4, 'Player')
        self.characterNP = render.attachNewNode(self.character)
        self.characterNP.setPos(0, 0, 130)
        self.characterNP.setH(180)
        self.characterNP.setCollideMask(BitMask32.allOn())
        self.models.world.attachCharacter(self.character)

        self.actorNP = Actor(
            'models/Bricker/Bricker3.egg', {
                'run': 'models/Bricker/Bricker-run.egg',
                'walk': 'models/Bricker/Bricker-walk.egg',
                'jump': 'models/Bricker/Bricker-jump.egg',
                'fallbackGetup': 'models/Bricker/FallbackGetup.egg',
                'fallforwardGetup':
                'models/Bricker/Bricker-FallforwardGetup.egg',
                'fireball': 'models/Bricker/Bricker-fireball.egg',
                'punching': 'models/Bricker/Bricker-punching.egg',
                'superpunch': 'models/Bricker/Bricker-superpunch.egg'
            })

        self.actorNP.reparentTo(self.characterNP)
        self.actorNP.setScale(0.3)
        self.actorNP.setH(180)
        self.actorNP.setPos(0, 0, 0.2)

        #enemies

        #self.setUpEnemies()

        #debug

        self.debugNode = BulletDebugNode('Debug')
        self.debugNode.showWireframe(True)
        self.debugNode.showConstraints(True)
        self.debugNode.showBoundingBoxes(False)
        self.debugNode.showNormals(False)
        self.debugNP = render.attachNewNode(self.debugNode)
        self.debugNP.hide()
        self.models.world.setDebugNode(self.debugNP.node())

    def doJump(self):
        self.character.setMaxJumpHeight(15.0)
        self.character.setJumpSpeed(8.0)
        self.character.doJump()

    def processInput(self, dt):
        speed = Vec3(0, 0, 0)
        omega = 0.0

        if inputState.isSet('forward') and self.won == 0 and self.lost == 0:

            if inputState.isSet('speedUp'):
                speed.setY(20.0)
            else:
                speed.setY(10.0)

        if inputState.isSet('reverse') and self.won == 0 and self.lost == 0:
            if inputState.isSet('speedUp'):
                speed.setY(-20.0)
            else:
                speed.setY(-10.0)

        if inputState.isSet('turnLeft') and self.won == 0 and self.lost == 0:
            omega = 60.0

        if inputState.isSet('turnRight') and self.won == 0 and self.lost == 0:
            omega = -60.0

        if inputState.isSet('jump') and self.won == 0 and self.lost == 0:
            self.actorNP.loop("jump")
            self.mySoundRunning.stop()
            self.mySoundJump.play()
            self.mySoundJump.setVolume(0.6)
            self.doJump()

        if inputState.isSet('hit') and self.won == 0 and self.lost == 0:
            self.actorNP.loop("punching")
            speed.setY(30.0)

        if inputState.isSet('debug') and self.won == 0 and self.lost == 0:
            if self.debug == True:
                self.debug = False
            else:
                self.debug = True

        if inputState.isSet('forward') or inputState.isSet(
                'reverse') or inputState.isSet('turnLeft') or inputState.isSet(
                    'turnRight'):
            if self.isMoving is False and self.won == 0 and self.lost == 0:
                self.actorNP.loop("run")
                self.isMoving = True
                self.mySoundRunning.play()
                self.mySoundRunning.setVolume(0.4)
        else:
            if self.isMoving:
                self.actorNP.stop()
                self.actorNP.pose("walk", 0)
                self.isMoving = False
                self.mySoundRunning.stop()

        if inputState.isSet(
                'rotateCamLeft') and self.won == 0 and self.lost == 0:
            base.camera.setX(base.camera, -20 * globalClock.getDt())
        if inputState.isSet(
                'rotateCamRight') and self.won == 0 and self.lost == 0:
            base.camera.setX(base.camera, +20 * globalClock.getDt())

        self.character.setAngularMovement(omega)
        self.character.setLinearMovement(speed, True)

    def update(self, task):

        if self.debug == True:
            self.debugNP.show()
        else:
            self.debugNP.hide()

        angleDegrees = task.time * 1000.0
        angleRadians = angleDegrees * (pi / 180.0)

        self.models.Cylinder1.setHpr(angleRadians, 0, 0)
        self.models.np16.setHpr(angleRadians, 0, 0)

        self.models.Cylinder2.setHpr(-angleRadians, 0, 0)
        self.models.np17.setHpr(-angleRadians, 0, 0)

        self.models.Cylinder3.setHpr(angleRadians, 0, 0)
        self.models.np18.setHpr(angleRadians, 0, 0)

        self.models.Cylinder4.setHpr(-angleRadians, 0, 0)
        self.models.np19.setHpr(-angleRadians, 0, 0)

        if self.models.np19.is_empty(
        ) == False and self.models.Cylinder4.is_empty() == False:

            if self.testWithSingleBody(
                    self.models.node19) == True and inputState.isSet(
                        'forward') == False and inputState.isSet(
                            'reverse') == False and inputState.isSet(
                                'turnLeft') == False and inputState.isSet(
                                    'turnRight') == False and inputState.isSet(
                                        'jump') == False:

                self.characterNP.setPos(0, -5, 220)
                self.mySoundEndFx.play()

        return task.cont

    def updateItems(self, task):

        angleDegrees = task.time * 1000.0
        angleRadians = angleDegrees * (pi / 180.0)

        for i in range(self.models.index):

            if self.models.iteamsNpsList[i].is_empty(
            ) == False and self.models.iteamsModelsList[i].is_empty() == False:
                self.models.iteamsModelsList[i].setHpr(angleRadians * 10, 90,
                                                       0)
                self.models.iteamsNpsList[i].setHpr(angleRadians * 10, 90, 0)

                if self.testWithSingleBody(
                        self.models.iteamsNodesList[i]) == True:
                    self.models.iteamsModelsList[i].setZ(2000)
                    self.models.iteamsNpsList[i].setZ(2000)
                    self.models.iteamsModelsList[i].remove_node()
                    self.models.iteamsNpsList[i].remove_node()

                    self.mySoundRing.play()

                    self.itemNumber += 1
                    self.item.destroy()
                    self.item = DirectFrame(text=str(self.itemNumber),
                                            scale=0.07,
                                            pos=(0.9, 0.5, 0.8),
                                            frameColor=(0, 0, 0, 0),
                                            text_fg=(1, 1, 1, 1),
                                            text_shadow=(0, 0, 0, 0.9))

        return task.cont

    def youLost(self):

        if (self.health < 1
                or self.characterNP.getZ() < 90) and self.lost == 0:
            taskMgr.remove('updateEnemies')

            self.lost = DirectFrame(text="You Lost",
                                    scale=0.2,
                                    pos=(0, 0, 0),
                                    frameColor=(0, 0, 0, 0),
                                    text_fg=(1, 0, 0, 1),
                                    text_shadow=(0, 0, 0, 0.9))

            p = float(
                float(self.itemNumber) / float(self.models.index) * 100.0)
            d = int(p)
            self.lost2 = DirectFrame(text="You Collected " + str(d) +
                                     "% of the Items",
                                     scale=0.1,
                                     pos=(0, 0, -0.15),
                                     frameColor=(0, 0, 0, 0),
                                     text_fg=(1, 1, 1, 1),
                                     text_shadow=(0, 0, 0, 0.9))

            self.b = DirectButton(text="Exit",
                                  scale=.07,
                                  command=sys.exit,
                                  pos=(-0.3, 0, -0.3),
                                  text_shadow=(0, 0, 0, 0.9),
                                  text_bg=(0, 0, 0, 1),
                                  text_fg=(1, 1, 1, 1))

            self.b2 = DirectButton(text="Restart",
                                   scale=.07,
                                   command=self.setRestart,
                                   pos=(0.3, 0, -0.3),
                                   text_shadow=(0, 0, 0, 0.9),
                                   text_bg=(0, 0, 0, 1),
                                   text_fg=(1, 1, 1, 1))

    def updateEnemies(self, task):

        self.youLost()

        if self.testWithSingleBody(self.models.node6) == True:

            if self.actorNPe1.is_empty() == False and self.e1NP.is_empty(
            ) == False:
                if self.ev == False:
                    self.mySoundEvil.play()
                    self.ev = True

                vecE1 = self.characterNP.getPos() - self.e1NP.getPos()
                vecE1.setZ(0)
                vecE1.normalize()
                self.e1NP.setPos(self.e1NP.getPos() + vecE1 * (1.0 / 10.0))
                self.actorNPe1.setH(self.actorNPe1.getH() -
                                    1000 * globalClock.getDt())

        if self.testWithSingleBody(self.models.node16) == True:

            if self.actorNPe2.is_empty() == False and self.e2NP.is_empty(
            ) == False:

                if self.ev == False:
                    self.mySoundEvil.play()
                    self.ev = True

                vecE2 = self.characterNP.getPos() - self.e2NP.getPos()
                vecE2.setZ(0)
                vecE2.normalize()
                self.e2NP.setPos(self.e2NP.getPos() + vecE2 * (1.0 / 10.0))
                self.actorNPe2.setH(self.actorNPe2.getH() -
                                    1000 * globalClock.getDt())

        if self.testWithSingleBody(self.models.node17) == True:

            if self.actorNPe3.is_empty() == False and self.e3NP.is_empty(
            ) == False:

                if self.ev == False:
                    self.mySoundEvil.play()
                    self.ev = True

                vecE3 = self.characterNP.getPos() - self.e3NP.getPos()
                vecE3.setZ(0)
                vecE3.normalize()
                self.e3NP.setPos(self.e3NP.getPos() + vecE3 * (1.0 / 10.0))
                self.actorNPe3.setH(self.actorNPe3.getH() -
                                    1000 * globalClock.getDt())

        if self.testWithSingleBody(self.models.node18) == True:

            if self.actorNPe4.is_empty() == False and self.e4NP.is_empty(
            ) == False:

                if self.ev == False:
                    self.mySoundEvil.play()
                    self.ev = True

                vecE4 = self.characterNP.getPos() - self.e4NP.getPos()
                vecE4.setZ(0)
                vecE4.normalize()
                self.e4NP.setPos(self.e4NP.getPos() + vecE4 * (1.0 / 10.0))
                self.actorNPe4.setH(self.actorNPe4.getH() -
                                    1000 * globalClock.getDt())

        if self.testWithSingleBody(self.e1) == True:
            self.pain()
            if inputState.isSet('hit'):
                self.e1Hited += 1.0
                self.mySoundPunch.play()
                self.mySoundPunch.setVolume(0.5)
                if self.actorNPe1.is_empty() == False and self.e1NP.is_empty(
                ) == False and self.e1Hited > 3:
                    self.actorNPe1.setZ(2000)
                    self.e1NP.setZ(2000)
                    self.actorNPe1.remove_node()
                    self.e1NP.remove_node()

        if self.testWithSingleBody(self.e2) == True:
            self.pain()
            if inputState.isSet('hit'):
                self.e2Hited += 1.0
                self.mySoundPunch.play()
                self.mySoundPunch.setVolume(0.5)
                if self.actorNPe2.is_empty() == False and self.e2NP.is_empty(
                ) == False and self.e2Hited > 3:
                    self.actorNPe2.setZ(2000)
                    self.e2NP.setZ(2000)
                    self.actorNPe2.remove_node()
                    self.e2NP.remove_node()

        if self.testWithSingleBody(self.e3) == True:
            self.pain()
            if inputState.isSet('hit'):
                self.e3Hited += 1.0
                self.mySoundPunch.play()
                self.mySoundPunch.setVolume(0.5)
                if self.actorNPe3.is_empty() == False and self.e3NP.is_empty(
                ) == False and self.e3Hited > 3:
                    self.actorNPe3.setZ(2000)
                    self.e3NP.setZ(2000)
                    self.actorNPe3.remove_node()
                    self.e3NP.remove_node()

        if self.testWithSingleBody(self.e4) == True:
            self.pain()
            if inputState.isSet('hit'):
                self.e4Hited += 1.0
                self.mySoundPunch.play()
                self.mySoundPunch.setVolume(0.5)
                if self.actorNPe4.is_empty() == False and self.e4NP.is_empty(
                ) == False and self.e4Hited > 3:
                    self.actorNPe4.setZ(2000)
                    self.e4NP.setZ(2000)
                    self.actorNPe4.remove_node()
                    self.e4NP.remove_node()

        return task.cont

    def incBar(self):
        # Create a frame
        # Add button
        self.bar = DirectWaitBar(text="HEALTH",
                                 value=self.health,
                                 range=100,
                                 pos=(0.8, 0.5, 0.9),
                                 scale=0.5,
                                 barColor=(0, 0.9, 0, 1),
                                 text_fg=(0, 0.5, 0, 1),
                                 text_shadow=(0, 0, 0, 0.5))

        self.frame = DirectFrame(text=" Items #",
                                 scale=0.07,
                                 pos=(0.7, 0.5, 0.8),
                                 frameColor=(0, 0, 0, 0),
                                 text_fg=(1, 1, 1, 1),
                                 text_shadow=(0, 0, 0, 0.9))

        self.item = DirectFrame(text=str(self.itemNumber),
                                scale=0.07,
                                pos=(0.9, 0.5, 0.8),
                                frameColor=(0, 0, 0, 0),
                                text_fg=(1, 1, 1, 1),
                                text_shadow=(0, 0, 0, 0.9))

    def pain(self):
        self.bar.destroy()
        self.health -= 0.3
        if self.health < 101 and self.health > 70:
            self.bar = DirectWaitBar(text="HEALTH",
                                     value=self.health,
                                     range=100,
                                     pos=(0.8, 0.5, 0.9),
                                     scale=0.5,
                                     barColor=(0, 0.9, 0, 1),
                                     text_fg=(0, 0.5, 0, 1),
                                     text_shadow=(0, 0, 0, 0.5))
        elif self.health < 71 and self.health > 40:
            self.bar = DirectWaitBar(text="HEALTH",
                                     value=self.health,
                                     range=100,
                                     pos=(0.8, 0.5, 0.9),
                                     scale=0.5,
                                     barColor=(0.9, 0.9, 0, 1),
                                     text_fg=(0.5, 0.5, 0, 1),
                                     text_shadow=(0, 0, 0, 0.5))
        else:
            self.bar = DirectWaitBar(text="HEALTH",
                                     value=self.health,
                                     range=100,
                                     pos=(0.8, 0.5, 0.9),
                                     scale=0.5,
                                     barColor=(0.9, 0, 0, 1),
                                     text_fg=(0.5, 0, 0, 1),
                                     text_shadow=(0, 0, 0, 0.5))

    def updateEndPoint(self, task):

        angleDegrees = task.time * 5000.0
        angleRadians = angleDegrees * (pi / 180.0)

        if self.models.npEnd.is_empty(
        ) == False and self.models.endpoint.is_empty(
        ) == False and self.won == 0:

            self.models.endpoint.setHpr(angleRadians, 0, 0)
            self.models.npEnd.setHpr(angleRadians, 0, 0)

            if self.testWithSingleBody(self.models.nodeEnd) == True:
                self.mySoundEnd.play()
                self.models.endpoint.remove_node()
                self.models.npEnd.remove_node()
                self.won = DirectFrame(text="You Won",
                                       scale=0.2,
                                       pos=(0, 0, 0),
                                       frameColor=(0, 0, 0, 0),
                                       text_fg=(0.5, 1, 0.5, 1),
                                       text_shadow=(0, 0, 0, 0.9))

                p = float(
                    float(self.itemNumber) / float(self.models.index) * 100.0)
                d = int(p)
                self.won2 = DirectFrame(text="You Collected " + str(d) +
                                        "% of the Items",
                                        scale=0.1,
                                        pos=(0, 0, -0.15),
                                        frameColor=(0, 0, 0, 0),
                                        text_fg=(1, 1, 1, 1),
                                        text_shadow=(0, 0, 0, 0.9))

                self.b = DirectButton(text="Exit",
                                      scale=.07,
                                      command=sys.exit,
                                      pos=(-0.3, 0, -0.3),
                                      text_shadow=(0, 0, 0, 0.9),
                                      text_bg=(0, 0, 0, 1),
                                      text_fg=(1, 1, 1, 1))

                self.b2 = DirectButton(text="Restart",
                                       scale=.07,
                                       command=self.setRestart,
                                       pos=(0.3, 0, -0.3),
                                       text_shadow=(0, 0, 0, 0.9),
                                       text_bg=(0, 0, 0, 1),
                                       text_fg=(1, 1, 1, 1))
                self.b3 = DirectButton(text="Go To Level 1",
                                       scale=.07,
                                       command=self.nextLevel1,
                                       pos=(0, 0, -0.5),
                                       text_shadow=(0, 0, 0, 0.9),
                                       text_bg=(0, 0, 0, 1),
                                       text_fg=(1, 1, 1, 1))

        return task.cont

    def testWithSingleBody(self, secondNode):
        contactResult = self.models.world.contactTestPair(
            self.character, secondNode)  # returns a BulletContactResult object
        if len(contactResult.getContacts()) > 0:
            return True

    def setRestart(self):
        self.re = True
        taskMgr.remove('update')
        taskMgr.remove('updateItems')
        taskMgr.remove('updateEnemies')
        taskMgr.remove('updateEndPoint')

        self.itemNumber = 0
        self.item.destroy()
        self.item = DirectFrame(text=str(self.itemNumber),
                                scale=0.07,
                                pos=(0.9, 0.5, 0.8),
                                frameColor=(0, 0, 0, 0),
                                text_fg=(1, 1, 1, 1),
                                text_shadow=(0, 0, 0, 0.9))

        for i in range(self.models.index):

            if self.models.iteamsNpsList[i].is_empty(
            ) == False and self.models.iteamsModelsList[i].is_empty() == False:
                self.models.iteamsModelsList[i].setZ(2000)
                self.models.iteamsNpsList[i].setZ(2000)
                self.models.iteamsModelsList[i].remove_node()
                self.models.iteamsNpsList[i].remove_node()

        self.models.iteamsModelsList = 0
        self.models.iteamsNodesList = 0
        self.models.iteamsNpsList = 0

        self.models.setupItems()

        if (self.won != 0):
            self.won.destroy()
            self.won2.destroy()
            self.models.setupEndPoint()

        if (self.lost != 0):
            self.lost.destroy()
            self.lost2.destroy()

        self.b.destroy()
        self.b2.destroy()

        if (self.b3 != 0):
            self.b3.destroy()

        self.bar.destroy()
        self.health = 100
        self.bar = DirectWaitBar(text="HEALTH",
                                 value=self.health,
                                 range=100,
                                 pos=(0.8, 0.5, 0.9),
                                 scale=0.5,
                                 barColor=(0, 0.9, 0, 1),
                                 text_fg=(0, 0.5, 0, 1),
                                 text_shadow=(0, 0, 0, 0.5))

        self.won = 0

        self.characterNP.setPos(0, 0, 130)
        self.characterNP.setH(180)

        if self.actorNPe1.is_empty() == False and self.e1NP.is_empty(
        ) == False:
            self.actorNPe1.setZ(2000)
            self.e1NP.setZ(2000)
            self.actorNPe1.remove_node()
            self.e1NP.remove_node()

        if self.actorNPe2.is_empty() == False and self.e2NP.is_empty(
        ) == False:
            self.actorNPe2.setZ(2000)
            self.e2NP.setZ(2000)
            self.actorNPe2.remove_node()
            self.e2NP.remove_node()

        if self.actorNPe3.is_empty() == False and self.e3NP.is_empty(
        ) == False:
            self.actorNPe3.setZ(2000)
            self.e3NP.setZ(2000)
            self.actorNPe3.remove_node()
            self.e3NP.remove_node()

        if self.actorNPe4.is_empty() == False and self.e4NP.is_empty(
        ) == False:
            self.actorNPe4.setZ(2000)
            self.e4NP.setZ(2000)
            self.actorNPe4.remove_node()
            self.e4NP.remove_node()

        self.setUpEnemies()

        base.camera.setPos(self.characterNP.getX(),
                           self.characterNP.getY() + 10, 5)
        base.camera.setHpr(self.characterNP.getHpr())
        base.camera.lookAt(self.characterNP)

        self.lost = 0

        taskMgr.add(self.update, 'update')
        taskMgr.add(self.updateItems, 'updateItems')
        taskMgr.add(self.updateEnemies, 'updateEnemies')
        taskMgr.add(self.updateEndPoint, 'updateEndPoint')

    def removeAll(self):
        self.re = True
        taskMgr.remove('update')
        taskMgr.remove('updateItems')
        taskMgr.remove('updateEnemies')
        taskMgr.remove('updateEndPoint')

        self.itemNumber = 0
        self.item.destroy()

        for i in range(self.models.index):
            if self.models.iteamsNpsList[i].is_empty(
            ) == False and self.models.iteamsModelsList[i].is_empty() == False:
                self.models.iteamsModelsList[i].setZ(2000)
                self.models.iteamsNpsList[i].setZ(2000)
                self.models.iteamsModelsList[i].remove_node()
                self.models.iteamsNpsList[i].remove_node()

        self.models.iteamsModelsList = 0
        self.models.iteamsNodesList = 0
        self.models.iteamsNpsList = 0

        if (self.won != 0):
            self.won.destroy()
            self.won2.destroy()
            self.b.destroy()
            self.b2.destroy()
            self.b3.destroy()

        if (self.lost != 0):
            self.lost.destroy()
            self.lost2.destroy()
            self.b.destroy()
            self.b2.destroy()
            self.b3.destroy()

        self.bar.destroy()
        self.health = 100

        self.won = 0

        self.lost = 0

        self.actorNP.remove_node()
        self.characterNP.remove_node()

        self.models.sky.remove_node()
        self.models.groundNp.remove_node()

        self.models.endpoint.remove_node()
        self.models.npEnd.remove_node()

        self.models.np1.remove_node()
        self.models.box1.remove_node()
        self.models.np2.remove_node()
        self.models.box2.remove_node()
        self.models.np3.remove_node()
        self.models.box3.remove_node()
        self.models.np4.remove_node()
        self.models.box4.remove_node()
        self.models.np5.remove_node()
        self.models.box5.remove_node()
        self.models.box6.remove_node()
        self.models.np6.remove_node()
        self.models.Cylinder1.remove_node()
        self.models.np16.remove_node()
        self.models.Cylinder2.remove_node()
        self.models.np17.remove_node()
        self.models.Cylinder3.remove_node()
        self.models.np18.remove_node()
        self.models.Cylinder4.remove_node()
        self.models.np19.remove_node()
        self.models.fire.remove_node()
        self.models.np7.remove_node()
        self.models.box7.remove_node()

        if self.actorNPe1.is_empty() == False and self.e1NP.is_empty(
        ) == False:
            self.actorNPe1.setZ(2000)
            self.e1NP.setZ(2000)
            self.actorNPe1.remove_node()
            self.e1NP.remove_node()

        if self.actorNPe2.is_empty() == False and self.e2NP.is_empty(
        ) == False:
            self.actorNPe2.setZ(2000)
            self.e2NP.setZ(2000)
            self.actorNPe2.remove_node()
            self.e2NP.remove_node()

        if self.actorNPe3.is_empty() == False and self.e3NP.is_empty(
        ) == False:
            self.actorNPe3.setZ(2000)
            self.e3NP.setZ(2000)
            self.actorNPe3.remove_node()
            self.e3NP.remove_node()

        if self.actorNPe4.is_empty() == False and self.e4NP.is_empty(
        ) == False:
            self.actorNPe4.setZ(2000)
            self.e4NP.setZ(2000)
            self.actorNPe4.remove_node()
            self.e4NP.remove_node()

    def nextLevel1(self):
        self.nextLevel = True
コード例 #4
0
ファイル: human.py プロジェクト: MattMcMullan/GdProj3
class Human():
    def __init__(self,parent, world, worldNP):
        """__init__
        parameters:
            self
            parent: the World object
            world: bullet world
            worldNP: where in the world to put it
        returns:
            none
        Description:
            Create the human player
        """
        self.traptime = 0
        self.world = world
        self.worldNP = worldNP
        
        self.projectiles = list()
        self.floatTraps = list()
        
        self.keymap = {"left": 0, "right":0, "up":0,"down":0, "m1":0}
        self.prevTime = 0
        # panda walk
        parent.accept("w",self.setKey,["up",1])
        parent.accept("w-up",self.setKey,["up",0])
        parent.accept("s",self.setKey,["down",1])
        parent.accept("s-up",self.setKey,["down",0])
        parent.accept("a",self.setKey,["left",1])
        parent.accept("a-up",self.setKey,["left",0])
        parent.accept("d",self.setKey,["right",1])
        parent.accept("d-up",self.setKey,["right",0])
        parent.accept("mouse1", self.setKey, ["m1",1])
        
        self.velocity = 0
        self.dir = (0,0,0)
        
        self.vel = (0,0,0)
        
        taskMgr.add(self.fpMove,"moveTask",sort=50)
        taskMgr.add(self.mouseTask, 'mouseTask')
        self.parent = parent
        #self.human = self.parent.human
        #self.human = collision.loadAndPositionModelFromFile("../assets/3d/Actors/robot rig 10 coll.egg",scale=.07,show=0)
        self.human = Actor('../assets/3d/Actors/robot_idle_final_actor.egg', {
          'idle':'../assets/3d/Actors/robot_idle_final_anim.egg',
        #  'throw':'../assets/3d/Actors/animation eggs/robot_throw_final.egg',
        #  'place':'../assets/3d/Actors/animation eggs/robot_place_final.egg',
        #  'death':'../assets/3d/Actors/animation eggs/robot_death_final.egg',
        })
        #print self.human.find("**/eyes_sphere").getPos()
        #self.human.flattenLight()
        print self.human.ls()
        #self.human.node().getChild(0).removeChild(0)
        self.human.setH(camera.getH()+180)
        campos = self.human.getPos()
        campos[2] = campos[2]-5
        camera.lookAt(campos)
        
        pnode = ModelRoot("player")
        self.player = render.attachNewNode(pnode)
        pc = self.player.attachNewNode(CollisionNode("playerCollision"))
        pc.node().addSolid(CollisionRay(0,0,-1,0,0,1))
        self.playerCnode = pc
        self.player.setPos(0,0,1)
        #self.human.play('idle')
        self.human.loop('idle')
    def bulletInit(self,world,pos):
        """bulletInit
        parameters:
            self
            task: the tskMgr structure
        returns:
            none
        Description:
            The rest of init requires bullet things
        """
        oldpath = self.human.find("**/body_coll")
        self.shape = BulletSphereShape(10)#oldpath.node().getSolid(0).getRadius())
        self.character = BulletCharacterControllerNode(self.shape, 0.4, 'Human')
        self.characterNP = render.attachNewNode(self.character)
        self.characterNP.setPos(pos[0],pos[1],pos[2])
        self.character.setGravity(0)
        #self.human.setPos(pos)
        self.human.reparentTo(self.characterNP)
        self.human.hide()
        #self.player.setPos(pos)
        self.player.reparentTo(self.characterNP)
        self.characterNP.setCollideMask(BitMask32.allOn())
        
        world.attachCharacter(self.character)
    def fpMove(self,task):
        """fpMove
        parameters:
            self
            task: the taskMgr structure
        returns:
            none
        Description:
            player movement
        """
        dt = task.time-self.prevTime
        camera.setPos(self.player.getPos()+(0,0,1))
        damp = (1.-(.2*dt))
        self.vel = map(lambda x: damp*x, self.vel)
        if self.traptime>0:
            self.traptime = self.traptime-dt
        #self.human.setZ(self.player.getZ()-.5)
        #if not self.parent.editMode:
        #camera.setPos(self.player.getPos()-(0.0264076, 4.60993, -10.0715))
        self.prevTime = task.time
        pos = self.player.getParent().getPos()
        delta = 10*dt
        h = deg2Rad(camera.getH())
        p = deg2Rad(camera.getP())
        # player control
        if self.keymap["up"] and self.traptime<=0:
            dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
            self.vel = map(lambda i: self.vel[i]+dir[i]*delta, range(3))
        if self.keymap["down"] and self.traptime<=0:
            dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
            self.vel = map(lambda i: self.vel[i]-dir[i]*delta, range(3))
        if self.keymap["m1"] and self.traptime<=0:
            weapon = self.parent.overlay.wepCounter
            if self.parent.overlay.wepAmmo[weapon] > 0:
                self.parent.overlay.changeAmmo(weapon, -1)
                if weapon == 0:
                    self.launch()
                    dir = (-cos(p)*sin(h), cos(p)*cos(h), sin(p))
                    self.vel = map(lambda i: self.vel[i]-dir[i]*100, range(3))
                elif weapon == 1:
                    self.placeFloatTrap()
                elif weapon == 2:
                    self.placeClawTrap()
            self.keymap["m1"] = 0
        self.character.setAngularMovement(0)
        self.character.setLinearMovement(LVector3(self.vel[0],self.vel[1],self.vel[2]),True)
        #get displacement
        dis = (self.vel[0]*dt,self.vel[1]*dt,self.vel[2]*dt)
        #set the new position
        self.player.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2])
        self.human.setPos(pos[0]+dis[0],pos[1]+dis[1],pos[2]+dis[2])
        #self.human.setX(self.player.getX()+sin(deg2Rad(camera.getH())+math.pi))
        #self.human.setY(self.player.getY()-cos(deg2Rad(camera.getH())+math.pi))
        return task.cont
    def launch(self):
        """launch
        parameters:
            self
        returns:
            none
        Description:
            Fire a projectile
        """
        self.projectiles.append(Projectile(self.player.getPos(),deg2Rad(camera.getH()),deg2Rad(camera.getP()),self,self.vel, self.world, self.worldNP))
    def placeFloatTrap(self):
        """placeFloatTrap
        parameters:
            self
        returns:
            none
        Description:
            Place a float trap
        """
        self.floatTraps.append(floatTrap(self.player.getPos(),self.world,self.worldNP)) 
    def placeClawTrap(self):
        """placeClawTrap
        parameters:
            self
        returns:
            none
        Description:
            Place a claw trap
        """
        trap = clawTrap(self.world,self.worldNP)
        weapon = self.parent.overlay.wepCounter
        self.parent.overlay.changeAmmo(weapon, trap.failed)
    def setKey(self,key,value):
        self.keymap[key] = value
    def mouseTask(self,task): 
        """mouseTask
        parameters:
            self
            task: the tskMgr structure
        returns:
            none
        Description:
            Keep track of the mouse and record its movement
        """
        global mousePos, mousePrevPos 
        
        if (not base.mouseWatcherNode.hasMouse() ): return Task.cont
        
        # Get mouse coordinates from mouse watcher 
        x=base.mouseWatcherNode.getMouseX()
        y=base.mouseWatcherNode.getMouseY()
        mousePos = [x,y] 
        # Calculate mouse movement from last frame and output (print) 
        move = [mousePos[0],mousePos[1]] 
        if move==[0,0]: return Task.cont
        #print "Moved:\t %f right, \t %f up." %(move[0], move[1]) 
        base.win.movePointer(0, base.win.getXSize() / 2, base.win.getYSize() / 2)
        # Save current position for next calculation 
        mousePrevPos = mousePos
        
        camera.setP(camera.getP()+75*move[1])
        camera.setH(camera.getH()-75*move[0])
        
        self.human.setH(camera.getH()+180)
        self.human.setX(self.player.getX()+sin(deg2Rad(camera.getH()+180)))
        self.human.setY(self.player.getY()-cos(deg2Rad(camera.getH()+180)))
        
        contacts = self.world.contactTest(self.character).getContacts()
        for c in contacts:
            contactObject = c.getNode0()
            if c.getNode0().getName()=="Human":
                contactObject = c.getNode1()
            if contactObject.getName()=="env":
                self.vel = map(lambda x: x*.9, self.vel)
        
        return Task.cont
    def die(self,event):
        """die
        parameters:
            self
            task: the tskMgr structure
        returns:
            none
        Description:
            Kill the player
        """
        #base.cTrav.removeCollider(self.wheelsphere)
        self.human.node().getChild(0).removeChild(0)
        self.filters.setInverted()
        print "You Died!"
    def trap1(self):
        """trap1
        parameters:
            self
        returns:
            none
        Description:
            Inflict the floating trap penalty
        """
        self.vel = map(lambda x: x*.25, self.vel)
        self.traptime = self.traptime + 20
        return
    def trap2(self):
        """trap2
        parameters:
            self
        returns:
            none
        Description:
            Inflict the claw trap penalty
        """
        self.vel = (0,0,0)
        self.traptime = self.traptime + 30
        return
    def impact(self,vel):
        diff = map(lambda i: self.vel[i]-vel[i], range(3))
        self.vel = map(lambda i: self.vel[i]-diff[i], range(3))