コード例 #1
0
    def __init__(self, fulcrum, terrain):
        TerrainCamera.__init__(self)

        self.terrain = terrain
        self.fulcrum = fulcrum
        # in behind Ralph regardless of ralph's movement.
        self.camNode.reparentTo(fulcrum)
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.focus = self.fulcrum.attachNewNode("focus")

        self.maxDistance = 500.0
        self.minDistance = 2
        self.maxPitch = 80
        self.minPitch = -70

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()
        self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
コード例 #2
0
 def initializeSmartCameraCollisions(self):
     if self.initialized:
         return
     self.ccTrav = CollisionTraverser('LocalAvatar.ccTrav')
     self.ccLine = CollisionSegment(0.0, 0.0, 0.0, 1.0, 0.0, 0.0)
     self.ccLineNode = CollisionNode('ccLineNode')
     self.ccLineNode.addSolid(self.ccLine)
     self.ccLineNodePath = base.localAvatar.attachNewNode(self.ccLineNode)
     self.ccLineBitMask = CIGlobals.CameraBitmask
     self.ccLineNode.setFromCollideMask(self.ccLineBitMask)
     self.ccLineNode.setIntoCollideMask(BitMask32.allOff())
     self.camCollisionQueue = CollisionHandlerQueue()
     self.ccTrav.addCollider(self.ccLineNodePath, self.camCollisionQueue)
     self.ccSphere = CollisionSphere(0, 0, 0, 1)
     self.ccSphereNode = CollisionNode('ccSphereNode')
     self.ccSphereNode.addSolid(self.ccSphere)
     self.ccSphereNodePath = base.camera.attachNewNode(self.ccSphereNode)
     self.ccSphereNode.setFromCollideMask(CIGlobals.CameraBitmask)
     self.ccSphereNode.setIntoCollideMask(BitMask32.allOff())
     self.camPusher = CollisionHandlerPusher()
     self.camPusher.addCollider(self.ccSphereNodePath, base.camera)
     self.camPusher.setCenter(base.localAvatar)
     self.ccPusherTrav = CollisionTraverser('LocalAvatar.ccPusherTrav')
     self.ccSphere2 = self.ccSphere
     self.ccSphereNode2 = CollisionNode('ccSphereNode2')
     self.ccSphereNode2.addSolid(self.ccSphere2)
     self.ccSphereNodePath2 = base.camera.attachNewNode(self.ccSphereNode2)
     self.ccSphereNode2.setFromCollideMask(CIGlobals.CameraBitmask)
     self.ccSphereNode2.setIntoCollideMask(BitMask32.allOff())
     self.camPusher2 = CollisionHandlerPusher()
     self.ccPusherTrav.addCollider(self.ccSphereNodePath2, self.camPusher2)
     self.camPusher2.addCollider(self.ccSphereNodePath2, base.camera)
     self.camPusher2.setCenter(base.localAvatar)
     self.camFloorRayNode = base.localAvatar.attachNewNode('camFloorRayNode')
     self.ccRay = CollisionRay(0.0, 0.0, 0.0, 0.0, 0.0, -1.0)
     self.ccRayNode = CollisionNode('ccRayNode')
     self.ccRayNode.addSolid(self.ccRay)
     self.ccRayNodePath = self.camFloorRayNode.attachNewNode(self.ccRayNode)
     self.ccRayBitMask = CIGlobals.FloorBitmask
     self.ccRayNode.setFromCollideMask(self.ccRayBitMask)
     self.ccRayNode.setIntoCollideMask(BitMask32.allOff())
     self.ccTravFloor = CollisionTraverser('LocalAvatar.ccTravFloor')
     self.camFloorCollisionQueue = CollisionHandlerQueue()
     self.ccTravFloor.addCollider(self.ccRayNodePath, self.camFloorCollisionQueue)
     self.ccTravOnFloor = CollisionTraverser('LocalAvatar.ccTravOnFloor')
     self.ccRay2 = CollisionRay(0.0, 0.0, 0.0, 0.0, 0.0, -1.0)
     self.ccRay2Node = CollisionNode('ccRay2Node')
     self.ccRay2Node.addSolid(self.ccRay2)
     self.ccRay2NodePath = self.camFloorRayNode.attachNewNode(self.ccRay2Node)
     self.ccRay2BitMask = CIGlobals.FloorBitmask
     self.ccRay2Node.setFromCollideMask(self.ccRay2BitMask)
     self.ccRay2Node.setIntoCollideMask(BitMask32.allOff())
     self.ccRay2MoveNodePath = hidden.attachNewNode('ccRay2MoveNode')
     self.camFloorCollisionBroadcaster = CollisionHandlerFloor()
     self.camFloorCollisionBroadcaster.setInPattern('on-floor')
     self.camFloorCollisionBroadcaster.setOutPattern('off-floor')
     self.camFloorCollisionBroadcaster.addCollider(self.ccRay2NodePath, self.ccRay2MoveNodePath)
     self.cTrav.addCollider(self.ccRay2NodePath, self.camFloorCollisionBroadcaster)
     self.initialized = True
コード例 #3
0
    def __init__(self, pos):
        Enemy.__init__(self, pos,
                       "Models/Misc/simpleEnemy",
                       {
                        "stand" : "Models/Misc/simpleEnemy-stand",
                        "walk" : "Models/Misc/simpleEnemy-walk",
                        "attack" : "Models/Misc/simpleEnemy-attack",
                        "die" : "Models/Misc/simpleEnemy-die",
                        "spawn" : "Models/Misc/simpleEnemy-spawn"
                        },
                       3.0,
                       7.0,
                       "walkingEnemy")

        self.attackDistance = 0.75
        self.attackDelay = 0.3
        self.attackDelayTimer = 0
        self.attackWaitTimer = 0
        self.acceleration = 100.0

        mask = BitMask32()
        mask.setBit(2)

        self.collider.node().setIntoCollideMask(mask)

        self.attackSegment = CollisionSegment(0, 0, 0, 1, 0, 0)

        segmentNode = CollisionNode("enemyAttackSegment")
        segmentNode.addSolid(self.attackSegment)

        mask = BitMask32()
        mask.setBit(1)

        segmentNode.setFromCollideMask(mask)

        mask = BitMask32()

        segmentNode.setIntoCollideMask(mask)

        self.attackSegmentNodePath = render.attachNewNode(segmentNode)
        self.segmentQueue = CollisionHandlerQueue()

        base.cTrav.addCollider(self.attackSegmentNodePath, self.segmentQueue)

        self.attackDamage = -1

        self.deathSound = loader.loadSfx("Sounds/enemyDie.ogg")
        self.attackSound = loader.loadSfx("Sounds/enemyAttack.ogg")

        self.yVector = Vec2(0, 1)

        self.actor.play("spawn")
コード例 #4
0
    def startPhysics(self):
        #self.actorNode = ActorNode("playerPhysicsControler")
        #base.physicsMgr.attachPhysicalNode(self.actorNode)
        #self.actorNode.getPhysicsObject().setMass(self.player_mass)
        #self.mainNode = render.attachNewNode(self.actorNode)
        self.mainNode = render.attachNewNode("CharacterColliders")
        self.reparentTo(self.mainNode)

        charCollisions = self.mainNode.attachNewNode(
            CollisionNode(self.char_collision_name))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0, self.player_height/4.0))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0*3.05, self.player_height/4.0))
        charCollisions.node().addSolid(
            CollisionSphere(0, 0, self.player_height / 2.0,
                            self.player_height / 4.0))
        charCollisions.node().setIntoCollideMask(BitMask32(0x80))  # 1000 0000
        if self.show_collisions:
            charCollisions.show()
        self.pusher.addCollider(charCollisions, self.mainNode)
        base.cTrav.addCollider(charCollisions, self.pusher)

        charFFootCollisions = self.attachNewNode(CollisionNode("floor_ray"))
        charFFootCollisions.node().addSolid(CollisionRay(0, 0, 0.5, 0, 0, -1))
        #charFFootCollisions.node().addSolid(CollisionSegment((0, 0, 0.2), (0, 0, -1)))
        charFFootCollisions.node().setIntoCollideMask(BitMask32.allOff())
        charFFootCollisions.node().setFromCollideMask(
            BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            charFFootCollisions.show()

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(charFFootCollisions, self.mainNode)
        #self.floor_handler.setOffset(0)
        self.floor_handler.setMaxVelocity(5)
        base.cTrav.addCollider(charFFootCollisions, self.floor_handler)

        self.accept("{}-in".format(self.char_collision_name),
                    self.checkCharCollisions)

        self.raytest_segment = CollisionSegment(0, 1)
        self.raytest_np = render.attachNewNode(CollisionNode("testRay"))
        self.raytest_np.node().addSolid(self.raytest_segment)
        self.raytest_np.node().setIntoCollideMask(BitMask32.allOff())
        self.raytest_np.node().setFromCollideMask(BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            self.raytest_np.show()

        self.raytest_queue = CollisionHandlerQueue()
        self.rayCTrav.addCollider(self.raytest_np, self.raytest_queue)
コード例 #5
0
ファイル: camera.py プロジェクト: PlumpMath/vinerx
    def __setup_collision(self):

        self.cTrav = CollisionTraverser('cameraTraverser')

        self.__camSeg = CollisionSegment((0, 0, self.__camRef), (0, 0, 0))

        cameraCol = CollisionNode('cameraSeg')
        cameraCol.addSolid(self.__camSeg)
        cameraCol.setFromCollideMask(BitMask32.bit(0))
        cameraCol.setIntoCollideMask(BitMask32.allOff())

        cameraColNp = self.ponto.attachNewNode(cameraCol)

        self.__camColHandler = CollisionHandlerQueue()

        self.cTrav.addCollider(cameraColNp, self.__camColHandler)
コード例 #6
0
    def __init__(self, fulcrum, terrain):
        TerrainCamera.__init__(self)

        self.terrain = terrain
        self.fulcrum = fulcrum
        # in behind Ralph regardless of ralph's movement.
        self.camNode.reparentTo(fulcrum)
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.focus = self.fulcrum.attachNewNode("focus")
        
        self.maxDistance = 500.0
        self.minDistance = 2
        self.maxPitch = 80
        self.minPitch = -70
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser() 
        self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler) 
コード例 #7
0
ファイル: bulletCamera.py プロジェクト: Wully616/Swifter
    def setUpCamera(self):
        """ puts camera behind the player in third person """
        
        
        # Set up the camera
        # Adding the camera to actor is a simple way to keep the camera locked
        # in behind actor regardless of actor's movement.
        base.camera.reparentTo(self.actor)
        # We don't actually want to point the camera at actors's feet.
        # This value will serve as a vertical offset so we can look over the actor
        self.cameraTargetHeight = 0.5
        # How far should the camera be from the actor
        self.cameraDistance = 10
        # Initialize the pitch of the camera
        self.cameraPitch = 45
        
        # The mouse moves rotates the camera so lets get rid of the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        
        #set up FOV
        pl =  base.cam.node().getLens()
        pl.setFov(70)
        base.cam.node().setLens(pl)
        
        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.
        """
TODO::        This will need to be changed to bullet
        """
        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0,0,1000)
        self.groundRay.setDirection(0,0,-1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
        
        # We will detect anything obstructing the camera's view of the player

        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.actor.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
コード例 #8
0
    def __init__(self):
        try:
            self.__initialized
            return
        except:
            self.__initialized = 1

        NodePath.__init__(self, hidden.attachNewNode('PositionExaminer'))
        self.cRay = CollisionRay(0.0, 0.0, 6.0, 0.0, 0.0, -1.0)
        self.cRayNode = CollisionNode('cRayNode')
        self.cRayNode.addSolid(self.cRay)
        self.cRayNodePath = self.attachNewNode(self.cRayNode)
        self.cRayNodePath.hide()
        self.cRayBitMask = CIGlobals.FloorBitmask
        self.cRayNode.setFromCollideMask(self.cRayBitMask)
        self.cRayNode.setIntoCollideMask(BitMask32.allOff())
        self.cSphere = CollisionSphere(0.0, 0.0, 0.0, 1.5)
        self.cSphereNode = CollisionNode('cSphereNode')
        self.cSphereNode.addSolid(self.cSphere)
        self.cSphereNodePath = self.attachNewNode(self.cSphereNode)
        self.cSphereNodePath.hide()
        self.cSphereBitMask = CIGlobals.WallBitmask
        self.cSphereNode.setFromCollideMask(self.cSphereBitMask)
        self.cSphereNode.setIntoCollideMask(BitMask32.allOff())
        self.ccLine = CollisionSegment(0.0, 0.0, 0.0, 1.0, 0.0, 0.0)
        self.ccLineNode = CollisionNode('ccLineNode')
        self.ccLineNode.addSolid(self.ccLine)
        self.ccLineNodePath = self.attachNewNode(self.ccLineNode)
        self.ccLineNodePath.hide()
        self.ccLineBitMask = CIGlobals.CameraBitmask
        self.ccLineNode.setFromCollideMask(self.ccLineBitMask)
        self.ccLineNode.setIntoCollideMask(BitMask32.allOff())
        self.cRayTrav = CollisionTraverser('PositionExaminer.cRayTrav')
        self.cRayTrav.setRespectPrevTransform(False)
        self.cRayQueue = CollisionHandlerQueue()
        self.cRayTrav.addCollider(self.cRayNodePath, self.cRayQueue)
        self.cSphereTrav = CollisionTraverser('PositionExaminer.cSphereTrav')
        self.cSphereTrav.setRespectPrevTransform(False)
        self.cSphereQueue = CollisionHandlerQueue()
        self.cSphereTrav.addCollider(self.cSphereNodePath, self.cSphereQueue)
        self.ccLineTrav = CollisionTraverser('PositionExaminer.ccLineTrav')
        self.ccLineTrav.setRespectPrevTransform(False)
        self.ccLineQueue = CollisionHandlerQueue()
        self.ccLineTrav.addCollider(self.ccLineNodePath, self.ccLineQueue)
コード例 #9
0
ファイル: player.py プロジェクト: tcdude/oneironautics
def setup_ray(node, traverser, bitmask, point_a=(0, 0, 1), point_b=(0, 0, 0)):
    ray = CollisionSegment(point_a, point_b)
    col = CollisionNode(node.getName() + "-ray")
    col.add_solid(ray)
    col.set_from_collide_mask(bitmask)
    col.set_into_collide_mask(CollideMask.all_off())
    col_node = node.attach_new_node(col)
    handler = CollisionHandlerQueue()
    traverser.add_collider(col_node, handler)
    return {"collider": col, "ray": ray, "handler": handler, "node": col_node}
コード例 #10
0
def attachCollisionSegment(self, name, ax, ay, az, bx, by, bz, fromCollide, intoCollide):
        from panda3d.core import CollisionSegment
        from panda3d.core import CollisionNode
        coll = CollisionSegment(ax, ay, az, bx, by, bz)
        collNode = CollisionNode(name)
        collNode.addSolid(coll)
        collNode.setFromCollideMask(fromCollide)
        collNode.setIntoCollideMask(intoCollide)
        collNodePath = self.attachNewNode(collNode)
        return collNodePath
コード例 #11
0
    def __init__(self, mask, damage, knockback, range=None):
        Weapon.__init__(self, mask, range, damage, knockback)

        if range is None:
            self.ray = CollisionRay(0, 0, 0, 0, 1, 0)
        else:
            self.ray = CollisionSegment(0, 0, 0, 1, 0, 0)

        rayNode = CollisionNode("playerRay")
        rayNode.addSolid(self.ray)

        rayNode.setFromCollideMask(mask)
        rayNode.setIntoCollideMask(0)

        self.rayNodePath = render.attachNewNode(rayNode)
        self.rayQueue = CollisionHandlerQueue()

        self.traverser = CollisionTraverser()
        self.traverser.addCollider(self.rayNodePath, self.rayQueue)
コード例 #12
0
 def init_entity(self, filter_name, entity):
     camera = entity[ThirdPersonCamera]
     camera_col = entity[CollisionZoom]
     w = camera_col.body_width / 2
     segs = ((0, 0, w), (0, 0, -w), (w, 0, 0), (-w, 0, 0))
     for seg in segs:
         segment = CollisionSegment(seg, (0, -camera.distance, 0))
         camera_col.collision.addSolid(segment)
     camera_col.collision.set_into_collide_mask(0)
     cn = camera.camera.parent.attachNewNode(camera_col.collision)
     camera_col.traverser.addCollider(cn, camera_col.queue)
コード例 #13
0
ファイル: camera.py プロジェクト: janEntikan/wecs
    def init_entity(self, filter_name, entity):
        camera = entity[Camera]
        center = entity[ObjectCentricCameraMode]
        zoom = entity[CollisionZoom]

        w = zoom.body_width / 2
        segs = ((0, 0, w), (0, 0, -w), (w, 0, 0), (-w, 0, 0))
        for seg in segs:
            segment = CollisionSegment(seg,(0, -center.distance, 0))
            zoom.collision.add_solid(segment)
        zoom.collision.set_into_collide_mask(0)
        cn = camera.camera.parent.attach_new_node(zoom.collision)
        zoom.traverser.add_collider(cn, zoom.queue)
コード例 #14
0
 def __init__(self, charId, charNr, controls):
     FSM.__init__(self, "FSM-Player{}".format(charNr))
     self.charId = charId
     charPath = "characters/character{}/".format(charNr)
     self.character = Actor(
         charPath + "char", {
             "Idle": charPath + "idle",
             "Walk": charPath + "walk",
             "Walk_back": charPath + "walk_back",
             "Punch_l": charPath + "punch_l",
             "Punch_r": charPath + "punch_r",
             "Kick_l": charPath + "kick_l",
             "Kick_r": charPath + "kick_r",
             "Hit": charPath + "hit",
             "Defend": charPath + "defend",
             "Defeated": charPath + "defeated"
         })
     self.character.reparentTo(render)
     self.character.hide()
     self.walkSpeed = 2.0
     if controls == "p1":
         self.character.setH(90)
         self.leftButton = KeyboardButton.asciiKey("d")
         self.rightButton = KeyboardButton.asciiKey("f")
         self.punchLButton = KeyboardButton.asciiKey("q")
         self.punchRButton = KeyboardButton.asciiKey("w")
         self.kickLButton = KeyboardButton.asciiKey("a")
         self.kickRButton = KeyboardButton.asciiKey("s")
         self.defendButton = KeyboardButton.asciiKey("e")
     elif controls == "p2":
         self.character.setH(-90)
         self.leftButton = KeyboardButton.right()
         self.rightButton = KeyboardButton.left()
         self.punchLButton = KeyboardButton.asciiKey("i")
         self.punchRButton = KeyboardButton.asciiKey("o")
         self.kickLButton = KeyboardButton.asciiKey("k")
         self.kickRButton = KeyboardButton.asciiKey("l")
         self.defendButton = KeyboardButton.asciiKey("p")
     characterSphere = CollisionSphere(0, 0, 1.0, 0.5)
     self.collisionNodeName = "character{}Collision".format(charId)
     characterColNode = CollisionNode(self.collisionNodeName)
     characterColNode.addSolid(characterSphere)
     self.characterCollision = self.character.attachNewNode(
         characterColNode)
     base.pusher.addCollider(self.characterCollision, self.character)
     base.cTrav.addCollider(self.characterCollision, base.pusher)
     characterHitRay = CollisionSegment(0, -0.5, 1.0, 0, -0.8, 1.0)
     characterColNode.addSolid(characterHitRay)
     self.getPos = self.character.getPos
     self.getX = self.character.getX
コード例 #15
0
 def ray(self, name, bitmask, point_a=(0, 0, 1), point_b=(0, 0, 0)):
     shape = CollisionSegment(point_a, point_b)
     col = CollisionNode(self.node.getName() + "-ray-" + name)
     col.add_solid(shape)
     col.set_from_collide_mask(bitmask)
     col.set_into_collide_mask(CollideMask.all_off())
     col_node = self.node.attach_new_node(col)
     handler = CollisionHandlerQueue()
     self.traverser.add_collider(col_node, handler)
     return {
         "collider": col,
         "shape": shape,
         "handler": handler,
         "node": col_node
     }
コード例 #16
0
ファイル: weapon.py プロジェクト: grimfang/owp_shooter
 def setupRay(self):
     self.shootTraverser = CollisionTraverser()
     self.shootingQH = CollisionHandlerQueue()
     #self.shootingEH = CollisionHandlerEvent()
     #self.shootingEH.addInPattern('into-%in')
     # Create a collision Node
     shootNode = CollisionNode('WeaponRay')
     # set the nodes collision bitmask
     shootNode.setFromCollideMask(BitMask32.bit(1))
     # create a collision segment (ray like)
     self.shootRay = CollisionSegment()
     shootNode.addSolid(self.shootRay)
     #self.pickerNP = self.main.player.model.attachNewNode(pickerNode)
     self.shootNP = render.attachNewNode(shootNode)
     #self.shootTraverser.addCollider(self.shootNP, self.shootingEH)
     self.shootTraverser.addCollider(self.shootNP, self.shootingQH)
コード例 #17
0
 def __endFireWater(self):
     if self.aimStart == None:
         return
     if not self.state == 'Controlled':
         return
     if not self.avId == localAvatar.doId:
         return
     taskMgr.remove(self.waterPowerTaskName)
     messenger.send('wakeup')
     self.aimStart = None
     origin = self.nozzle.getPos(render)
     target = self.boss.getPos(render)
     angle = deg2Rad(self.waterPitcherNode.getH() + 90)
     x = math.cos(angle)
     y = math.sin(angle)
     fireVector = Point3(x, y, 0)
     if self.power < 0.001:
         self.power = 0.001
     self.lastPowerFired = self.power
     fireVector *= self.fireLength * self.power
     target = origin + fireVector
     segment = CollisionSegment(origin[0], origin[1], origin[2], target[0],
                                target[1], target[2])
     fromObject = render.attachNewNode(CollisionNode('pitcherColNode'))
     fromObject.node().addSolid(segment)
     fromObject.node().setFromCollideMask(ToontownGlobals.PieBitmask
                                          | ToontownGlobals.CameraBitmask
                                          | ToontownGlobals.FloorBitmask)
     fromObject.node().setIntoCollideMask(BitMask32.allOff())
     queue = CollisionHandlerQueue()
     base.cTrav.addCollider(fromObject, queue)
     base.cTrav.traverse(render)
     queue.sortEntries()
     self.hitObject = None
     if queue.getNumEntries():
         entry = queue.getEntry(0)
         target = entry.getSurfacePoint(render)
         self.hitObject = entry.getIntoNodePath()
     base.cTrav.removeCollider(fromObject)
     fromObject.removeNode()
     self.d_firingWater(origin, target)
     self.fireWater(origin, target)
     self.resetPowerBar()
     return
コード例 #18
0
ファイル: PhysicsInternal.py プロジェクト: grimfang/pyweek21
    def startPhysics(self):
        #self.actorNode = ActorNode("playerPhysicsControler")
        #base.physicsMgr.attachPhysicalNode(self.actorNode)
        #self.actorNode.getPhysicsObject().setMass(self.player_mass)
        #self.mainNode = render.attachNewNode(self.actorNode)
        self.mainNode = render.attachNewNode("CharacterColliders")
        self.reparentTo(self.mainNode)

        charCollisions = self.mainNode.attachNewNode(CollisionNode(self.char_collision_name))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0, self.player_height/4.0))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0*3.05, self.player_height/4.0))
        charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/2.0, self.player_height/4.0))
        charCollisions.node().setIntoCollideMask(BitMask32(0x80))  # 1000 0000
        if self.show_collisions:
            charCollisions.show()
        self.pusher.addCollider(charCollisions, self.mainNode)
        base.cTrav.addCollider(charCollisions, self.pusher)

        charFFootCollisions = self.attachNewNode(CollisionNode("floor_ray"))
        charFFootCollisions.node().addSolid(CollisionRay(0, 0, 0.5, 0, 0, -1))
        #charFFootCollisions.node().addSolid(CollisionSegment((0, 0, 0.2), (0, 0, -1)))
        charFFootCollisions.node().setIntoCollideMask(BitMask32.allOff())
        charFFootCollisions.node().setFromCollideMask(BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            charFFootCollisions.show()

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(charFFootCollisions, self.mainNode)
        #self.floor_handler.setOffset(0)
        self.floor_handler.setMaxVelocity(5)
        base.cTrav.addCollider(charFFootCollisions, self.floor_handler)

        self.accept("{}-in".format(self.char_collision_name), self.checkCharCollisions)

        self.raytest_segment = CollisionSegment(0, 1)
        self.raytest_np = render.attachNewNode(CollisionNode("testRay"))
        self.raytest_np.node().addSolid(self.raytest_segment)
        self.raytest_np.node().setIntoCollideMask(BitMask32.allOff())
        self.raytest_np.node().setFromCollideMask(BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            self.raytest_np.show()

        self.raytest_queue = CollisionHandlerQueue()
        self.rayCTrav.addCollider(self.raytest_np, self.raytest_queue)
コード例 #19
0
    def __init__(self):
        FSM.__init__(self, "FSM-Golem")
        random.seed()
        self.golem = loader.loadModel("Golem")
        self.golem = Actor(
            "Golem", {
                "Idle": "Golem-Idle",
                "Walk": "Golem-Walk",
                "Attack": "Golem-Attack",
                "Destroyed": "Golem-Destroyed"
            })
        self.golem.setBlend(frameBlend=True)
        golemViewSphere = CollisionSphere(0, 0, 0.5, 6)
        golemViewSphere.setTangible(False)
        golemViewColNP = self.golem.attachNewNode(
            CollisionNode('golemViewField'))
        golemViewColNP.node().addSolid(golemViewSphere)
        golemHitSphere = CollisionSphere(0, 0, 0.5, 1)
        golemHitColNP = self.golem.attachNewNode(
            CollisionNode('golemHitField'))
        golemHitColNP.node().addSolid(golemHitSphere)

        # a collision segment to check attacks
        self.attackCheckSegment = CollisionSegment(0, 0, 1, 0, -1.3, 1)
        self.golemAttackRay = self.golem.attachNewNode(
            CollisionNode("golemAttackCollision"))
        self.golemAttackRay.node().addSolid(self.attackCheckSegment)
        self.golemAttackRay.node().setIntoCollideMask(0)
        self.attackqueue = CollisionHandlerQueue()
        base.cTrav.addCollider(self.golemAttackRay, self.attackqueue)

        attackAnim = self.golem.actorInterval("Attack", playRate=2)
        self.AttackSeq = Parallel(attackAnim,
                                  Sequence(Wait(0.5), Func(self.ceckAttack)))

        self.lookatFloater = NodePath(PandaNode("golemTracker"))
        self.lookatFloater.setPos(self.golem, 0, 0, 3.4)
        self.lookatFloater.hide()
        self.lookatFloater.reparentTo(render)
        self.trackerObject = loader.loadModel("misc/Pointlight")
        self.trackerObject.setColor(0, 1, 0)
        self.trackerObject.setScale(0.25)
        self.trackerObject.reparentTo(self.lookatFloater)
コード例 #20
0
    def __init__(self, pos, modelName, maxHealth, maxSpeed, colliderName,
                 size):
        Enemy.__init__(self, pos, modelName, maxHealth, maxSpeed, colliderName,
                       size)

        self.acceleration = 100.0

        self.turnRate = 200.0

        self.yVector = Vec2(0, 1)

        self.steeringRayNPs = []

        self.steeringQueue = CollisionHandlerQueue()

        self.state = FighterEnemy.STATE_ATTACK
        self.breakAwayTimer = 0
        self.breakAwayMaxDuration = 5

        self.evasionDuration = 2
        self.evasionDurationVariability = 0.2
        self.evasionTimer = 0
        self.evasionDirection = (0, 0)

        for i in range(4):
            ray = CollisionSegment(0, 0, 0, 0, 1, 0)

            rayNode = CollisionNode("steering ray")
            rayNode.addSolid(ray)

            rayNode.setFromCollideMask(MASK_WALLS)
            rayNode.setIntoCollideMask(0)

            rayNodePath = self.actor.attachNewNode(rayNode)

            #rayNodePath.show()

            self.steeringRayNPs.append(rayNodePath)

        Common.framework.traverser.addCollider(rayNodePath, self.steeringQueue)
コード例 #21
0
class WalkingEnemy(Enemy):
    def __init__(self, pos):
        Enemy.__init__(
            self, pos, "Models/Misc/simpleEnemy", {
                "stand": "Models/Misc/simpleEnemy-stand",
                "walk": "Models/Misc/simpleEnemy-walk",
                "attack": "Models/Misc/simpleEnemy-attack",
                "die": "Models/Misc/simpleEnemy-die",
                "spawn": "Models/Misc/simpleEnemy-spawn"
            }, 3.0, 7.0, "walkingEnemy")

        self.attackDistance = 0.75
        self.attackDelay = 0.3
        self.attackDelayTimer = 0
        self.attackWaitTimer = 0
        self.acceleration = 100.0

        mask = BitMask32()
        mask.setBit(2)

        self.collider.node().setIntoCollideMask(mask)

        self.attackSegment = CollisionSegment(0, 0, 0, 1, 0, 0)

        segmentNode = CollisionNode("enemyAttackSegment")
        segmentNode.addSolid(self.attackSegment)

        mask = BitMask32()
        mask.setBit(1)

        segmentNode.setFromCollideMask(mask)

        mask = BitMask32()

        segmentNode.setIntoCollideMask(mask)

        self.attackSegmentNodePath = render.attachNewNode(segmentNode)
        self.segmentQueue = CollisionHandlerQueue()

        base.cTrav.addCollider(self.attackSegmentNodePath, self.segmentQueue)

        self.attackDamage = -1

        self.deathSound = loader.loadSfx("Sounds/enemyDie.ogg")
        self.attackSound = loader.loadSfx("Sounds/enemyAttack.ogg")

        self.yVector = Vec2(0, 1)

        self.actor.play("spawn")

    def runLogic(self, player, dt):
        spawnControl = self.actor.getAnimControl("spawn")
        if spawnControl is not None and spawnControl.isPlaying():
            return

        vectorToPlayer = player.actor.getPos() - self.actor.getPos()

        vectorToPlayer2D = vectorToPlayer.getXy()
        distanceToPlayer = vectorToPlayer2D.length()

        vectorToPlayer2D.normalize()

        heading = self.yVector.signedAngleDeg(vectorToPlayer2D)

        self.attackSegment.setPointA(self.actor.getPos())
        self.attackSegment.setPointB(self.actor.getPos() +
                                     self.actor.getQuat().getForward() *
                                     self.attackDistance)

        if distanceToPlayer > self.attackDistance * 0.9:
            attackControl = self.actor.getAnimControl("attack")
            if not attackControl.isPlaying():
                self.walking = True
                vectorToPlayer.setZ(0)
                vectorToPlayer.normalize()
                self.velocity += vectorToPlayer * self.acceleration * dt
                self.attackWaitTimer = 0.2
                self.attackDelayTimer = 0
        else:
            self.walking = False
            self.velocity.set(0, 0, 0)

            if self.attackDelayTimer > 0:
                self.attackDelayTimer -= dt
                if self.attackDelayTimer <= 0:
                    if self.segmentQueue.getNumEntries() > 0:
                        self.segmentQueue.sortEntries()
                        segmentHit = self.segmentQueue.getEntry(0)

                        hitNodePath = segmentHit.getIntoNodePath()
                        if hitNodePath.hasPythonTag("owner"):
                            hitObject = hitNodePath.getPythonTag("owner")
                            hitObject.alterHealth(self.attackDamage)
                            self.attackWaitTimer = 1.0
            elif self.attackWaitTimer > 0:
                self.attackWaitTimer -= dt
                if self.attackWaitTimer <= 0:
                    self.attackWaitTimer = random.uniform(0.5, 0.7)
                    self.attackDelayTimer = self.attackDelay
                    self.actor.play("attack")
                    self.attackSound.play()

        self.actor.setH(heading)

    def alterHealth(self, dHealth):
        Enemy.alterHealth(self, dHealth)
        self.updateHealthVisual()

    def updateHealthVisual(self):
        perc = self.health / self.maxHealth
        if perc < 0:
            perc = 0
        self.actor.setColorScale(perc, perc, perc, 1)

    def cleanup(self):
        base.cTrav.removeCollider(self.attackSegmentNodePath)
        self.attackSegmentNodePath.removeNode()

        GameObject.cleanup(self)
コード例 #22
0
class FollowCamera(TerrainCamera):
    
    def __init__(self, fulcrum, terrain):
        TerrainCamera.__init__(self)

        self.terrain = terrain
        self.fulcrum = fulcrum
        # in behind Ralph regardless of ralph's movement.
        self.camNode.reparentTo(fulcrum)
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.focus = self.fulcrum.attachNewNode("focus")
        
        self.maxDistance = 500.0
        self.minDistance = 2
        self.maxPitch = 80
        self.minPitch = -70
        
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser() 
        self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler) 
        
    def zoom(self, zoomIn):
        if (zoomIn):
            self.cameraDistance += 0.1 * self.cameraDistance;
        else:
            self.cameraDistance -= 0.1 * self.cameraDistance;
        if self.cameraDistance < self.minDistance:
            self.cameraDistance = self.minDistance
        if self.cameraDistance > self.maxDistance:
            self.cameraDistance = self.maxDistance
        
    def update(self, x, y):
        
        # alter ralph's yaw by an amount proportionate to deltaX
        self.fulcrum.setH(self.fulcrum.getH() - 0.3 * x)
        # find the new camera pitch and clamp it to a reasonable range
        self.cameraPitch = self.cameraPitch + 0.1 * y
        if (self.cameraPitch < self.minPitch): 
            self.cameraPitch = self.minPitch
        if (self.cameraPitch > self.maxPitch): 
            self.cameraPitch = self.maxPitch
        self.camNode.setHpr(0, self.cameraPitch, 0)
        # set the camera at around ralph's middle
        # We should pivot around here instead of the view target which is noticebly higher
        self.camNode.setPos(0, 0, 0)
        # back the camera out to its proper distance
        self.camNode.setY(self.camNode, self.cameraDistance)
        self.fixHeight()
        correctedDistance = self.camNode.getPos().length()

        # point the camera at the view target

        forwardOffset = -math.sin(math.radians(self.cameraPitch))
        verticalOffset = 1- math.sin(math.radians(self.cameraPitch))
        self.focus.setPos(0, forwardOffset, verticalOffset + correctedDistance / 8.0)
        #keep camera from flipping over
        if self.focus.getY() > self.camNode.getY()*0.9:
            self.focus.setY(self.camNode.getY()*0.9)
        self.camNode.lookAt(self.focus)
        # reposition the end of the  camera's obstruction ray trace
        self.cameraRay.setPointB(self.camNode.getPos())
        
        # We will detect anything obstructing the camera via a ray trace
        # from the view target around the avatar's head, to the desired camera
        # podition. If the ray intersects anything, we move the camera to the
        # the first intersection point, This brings the camera in between its
        # ideal position, and any present obstructions.

#        entries = []
#        for i in range(self.cameraColHandler.getNumEntries()):
#            entry = self.cameraColHandler.getEntry(i)
#            entries.append(entry)
#        entries.sort(lambda x,y: cmp(-y.getSurfacePoint(self.ralph).getY(),
#                                     -x.getSurfacePoint(self.ralph).getY()))
#        if (len(entries)>0):
#            collisionPoint =  entries[0].getSurfacePoint(self.ralph)
#            collisionVec = ( viewTarget - collisionPoint)
#            if ( collisionVec.lengthSquared() < self.cameraDistance * self.cameraDistance ):
#                self.camNode.setPos(collisionPoint)
#                if (entries[0].getIntoNode().getName() == "terrain"):
#                    self.camNode.setZ(base.camera, 0.2)
#                self.camNode.setY(base.camera, 0.3)
#

    def fixHeight(self):
        pos = self.camNode.getPos(render)
        minZ = self.terrain.getElevation(pos.x, pos.y) + 1.2
        #logging.info( minZ)
        if pos.z < minZ:
            pos.z = minZ
        self.camNode.setPos(render, pos)
コード例 #23
0
    def setup(self, task):
        lens = OrthographicLens()
        lens.setFilmSize(25, 20)
        base.camNode.setLens(lens)

        self.player = self.scene.attachNewNode("Player")

        self.scene.find("root/barrel").setPos(0, 100, 0)

        self.scene.find("root/walls").hide()

        self.scene.find("root/rightWall").hide()

        self.lifes = [
            self.scene.attachNewNode("life1"),
            self.scene.attachNewNode("life2"),
            self.scene.attachNewNode("life3"),
        ]
        # init mario gfx stuff
        self.marioGfx = self.scene.find('root/mario')
        self.marioGfx.instanceTo(self.lifes[0])
        self.marioGfx.instanceTo(self.lifes[1])
        self.marioGfx.instanceTo(self.lifes[2])
        self.lifes[0].setPos(-9, 0, 7.5)
        self.lifes[1].setPos(-10, 0, 7.5)
        self.lifes[2].setPos(-11, 0, 7.5)

        self.marioGfx.reparentTo(self.player)
        self.marioGfx.setTwoSided(True)
        self.hammerDown = self.scene.find('root/hammerdowm')
        self.hammerDown.reparentTo(self.marioGfx)
        self.hammerDown.setPos(1, 0, 0)
        self.hammerUp = self.scene.find('root/hammerup')
        self.hammerUp.reparentTo(self.marioGfx)
        self.hammerUp.setPos(0, 0, 1)
        self.hammerDown.hide()
        self.hammerUp.hide()

        frame1 = Func(self.hammerFrame1)
        frame2 = Func(self.hammerFrame2)
        delay = Wait(0.1)
        self.hammerSequence = Sequence(frame1, delay, frame2, delay)
        #sequence.loop()
        #sequence.start()
        #sequence.finish()

        #input setup
        self.accept("raw-arrow_up", self.pressUp)
        self.accept("raw-arrow_down", self.pressDown)
        self.accept("raw-arrow_left", self.pressLeft)
        self.accept("raw-arrow_right", self.pressRight)
        self.accept("raw-space", self.pressSpace)

        self.accept("raw-arrow_up-up", self.pressUp)
        self.accept("raw-arrow_down-up", self.pressDown)
        self.accept("raw-arrow_left-up", self.pressLeft)
        self.accept("raw-arrow_right-up", self.pressRight)
        self.accept("raw-space-up", self.pressSpace)
        self.input = {
            'left': False,
            'right': False,
            'up': False,
            'down': False,
            'space': False
        }

        # collision handling
        base.cTrav = CollisionTraverser()
        self.collisionHandlerEvent = CollisionHandlerEvent()
        self.collisionHandlerEvent.addInPattern('into-%in')
        self.collisionHandlerEvent.addOutPattern('outof-%in')

        ray = CollisionSegment(0, 0, 0, 0, 0, -.6)
        cNodePath = self.player.attachNewNode(CollisionNode('marioRay'))
        cNodePath.node().addSolid(ray)
        cNodePath.node().setIntoCollideMask(0x3)
        cNodePath.node().setFromCollideMask(0x3)
        cNodePath.show()
        base.cTrav.addCollider(cNodePath, self.collisionHandlerEvent)

        self.donkeykonggfx = self.scene.find(f'root/donkeykong')
        self.donkeykong = self.createSquareCollider(8.7, 5, 1, 1, 'donkeykong',
                                                    'dkHitbox', 'DK',
                                                    self.reachedDk,
                                                    self.exitDk,
                                                    self.arcadeTexture, 0x2)

        self.floor1 = self.createSquareCollider(-1.8, -5.5, 9.3, .5, 'floor0',
                                                'floor1Hitbox', 'Floor1',
                                                self.enableJump,
                                                self.disableJump,
                                                self.blockTexture, 0x01)
        self.floor2 = self.createSquareCollider(2.08, -2.5, 8.0, .5, 'floor1',
                                                'floor2Hitbox', 'Floor2',
                                                self.enableJump,
                                                self.disableJump,
                                                self.blockTexture, 0x01)
        self.floor3_1 = self.createSquareCollider(3.6, 0.5, 3.8, .5, 'floor2',
                                                  'floor3_1Hitbox', 'Floor3_1',
                                                  self.enableJump,
                                                  self.disableJump,
                                                  self.blockTexture, 0x01)
        self.floor3_2 = self.createSquareCollider(-6.3, 0.5, 5, .5, 'pCube4',
                                                  'floor3_2Hitbox', 'Floor3_2',
                                                  self.enableJump,
                                                  self.disableJump,
                                                  self.blockTexture, 0x01)
        self.floor4 = self.createSquareCollider(1.8, 3.5, 8, .5, 'floors',
                                                'floor4Hitbox', 'Floor4',
                                                self.enableJump,
                                                self.disableJump,
                                                self.blockTexture, 0x01)

        self.hammer = self.createSquareCollider(6, 1.5, .5, .5, 'hammer',
                                                'hammerHitbox', 'hammer',
                                                self.enableHammer,
                                                self.disableHammer,
                                                self.arcadeTexture, 0x02)

        self.topstair = self.createSquareCollider(
            -6.8, 3.5, 0.5, 2.5, 'topstair', 'topstairHitbox', 'TopStair',
            self.enableStairs, self.disableStairs, self.stairsTexture, 0x02)
        self.middlestair = self.createSquareCollider(
            -0.86, 0.1, 0.5, 2.5, 'middlestair', 'middlestairHitbox',
            'MiddleStair', self.enableStairs, self.disableStairs,
            self.stairsTexture, 0x02)
        self.bottomstair = self.createSquareCollider(
            -6.8, -2.5, 0.5, 2.5, 'bottomstair', 'bottomstairHitbox',
            'BottomStair', self.enableStairs, self.disableStairs,
            self.stairsTexture, 0x02)

        self.leftWall = self.invisibleSquareCollider(-12.5, 0, 1, 10,
                                                     "leftWallHitbox",
                                                     "leftWall", 0x1)
        self.rightWall = self.invisibleSquareCollider(11.3, 0, 1, 20,
                                                      "rightWallHitbox",
                                                      "rightWall", 0x1)

        self.barrelDestroyer = self.invisibleSquareCollider(
            -0.5, -10, 10.5, 1, "barrelDestroyHitBox", "barrelDestroyer", 0x1)
        self.barrelBridge = self.invisibleSquareCollider(
            -0.4, 0.5, 2, 0.5, "barrelBridgeHitBox", "barrelBridge", 0x4)
        base.enableParticles()
        self.physicsCollisionPusher = PhysicsCollisionHandler()
        gravity = ForceNode("world-forces")
        gravityP = render.attachNewNode(gravity)
        gravityForce = LinearVectorForce(0, 0, -9.81)
        gravity.addForce(gravityForce)
        base.physicsMgr.addLinearForce(gravityForce)
        self.accept("into-barrelCollider", self.barrelCrash)

        #self.accept("raw-a", self.throwBarrel)

        #base.cTrav.showCollisions(self.render)

        self.barrels_frames = []
        self.barrels_frames.append(0)
        self.barrels_frames.append(0.410573 - 0.375774)
        self.barrels_frames.append(0.444913 - 0.375774)
        self.barrels_frames.append(0.479941 - 0.375774)

        self.createDKSequence()
        self.player.setPos(3, 0, -3)
        return Task.done
コード例 #24
0
ファイル: PhysicsInternal.py プロジェクト: grimfang/pyweek21
class Physics:
    def __init__(self):
        self.rayCTrav = CollisionTraverser("collision traverser for ray tests")
        #self.pusher = PhysicsCollisionHandler()
        self.pusher = CollisionHandlerPusher()
        self.pusher.addInPattern('%fn-in-%in')
        self.pusher.addOutPattern('%fn-out-%in')
        self.pusher.addInPattern('%fn-in')
        self.pusher.addOutPattern('%fn-out')

    def startPhysics(self):
        #self.actorNode = ActorNode("playerPhysicsControler")
        #base.physicsMgr.attachPhysicalNode(self.actorNode)
        #self.actorNode.getPhysicsObject().setMass(self.player_mass)
        #self.mainNode = render.attachNewNode(self.actorNode)
        self.mainNode = render.attachNewNode("CharacterColliders")
        self.reparentTo(self.mainNode)

        charCollisions = self.mainNode.attachNewNode(CollisionNode(self.char_collision_name))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0, self.player_height/4.0))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0*3.05, self.player_height/4.0))
        charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/2.0, self.player_height/4.0))
        charCollisions.node().setIntoCollideMask(BitMask32(0x80))  # 1000 0000
        if self.show_collisions:
            charCollisions.show()
        self.pusher.addCollider(charCollisions, self.mainNode)
        base.cTrav.addCollider(charCollisions, self.pusher)

        charFFootCollisions = self.attachNewNode(CollisionNode("floor_ray"))
        charFFootCollisions.node().addSolid(CollisionRay(0, 0, 0.5, 0, 0, -1))
        #charFFootCollisions.node().addSolid(CollisionSegment((0, 0, 0.2), (0, 0, -1)))
        charFFootCollisions.node().setIntoCollideMask(BitMask32.allOff())
        charFFootCollisions.node().setFromCollideMask(BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            charFFootCollisions.show()

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(charFFootCollisions, self.mainNode)
        #self.floor_handler.setOffset(0)
        self.floor_handler.setMaxVelocity(5)
        base.cTrav.addCollider(charFFootCollisions, self.floor_handler)

        self.accept("{}-in".format(self.char_collision_name), self.checkCharCollisions)

        self.raytest_segment = CollisionSegment(0, 1)
        self.raytest_np = render.attachNewNode(CollisionNode("testRay"))
        self.raytest_np.node().addSolid(self.raytest_segment)
        self.raytest_np.node().setIntoCollideMask(BitMask32.allOff())
        self.raytest_np.node().setFromCollideMask(BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            self.raytest_np.show()

        self.raytest_queue = CollisionHandlerQueue()
        self.rayCTrav.addCollider(self.raytest_np, self.raytest_queue)

    def stopPhysics(self):
        self.raytest_segment.removeNode()
        self.pusher.clearColliders()
        self.floor_handler.clearColliders()
        self.rayCTrav.clearColliders()

    def updatePlayerPos(self, speed, heading, dt):
        if heading is not None:
            self.mainNode.setH(camera, heading)
            self.mainNode.setP(0)
            self.mainNode.setR(0)
        self.mainNode.setFluidPos(self.mainNode, speed)
        self.doStep()

    def checkCharCollisions(self, args):
        self.doStep()

    def doStep(self):
        # do the step height check
        tmpNP = self.mainNode.attachNewNode("temporary")
        tmpNP.setPos(self.mainNode, 0, 0, -self.stepheight)
        pointA = self.mainNode.getPos(render)
        pointA.setZ(pointA.getZ() + self.player_height/1.8)
        pointB = tmpNP.getPos(render)
        if pointA == pointB: return
        char_step_collision = self.getFirstCollisionInLine(pointA, pointB)
        tmpNP.removeNode()
        if char_step_collision is not None:
            self.mainNode.setFluidZ(char_step_collision.getZ())
            return True
        return False

    def getFirstCollisionInLine(self, pointA, pointB):
        """A simple raycast check which will return the first collision point as
        seen from point A towards pointB"""
        self.raytest_segment.setPointA(pointA)
        self.raytest_segment.setPointB(pointB)
        self.rayCTrav.traverse(render)
        self.raytest_queue.sortEntries()
        pos = None
        if self.raytest_queue.getNumEntries() > 0:
            pos = self.raytest_queue.getEntry(0).getSurfacePoint(render)
        return pos
コード例 #25
0
class FollowCamera(TerrainCamera):
    def __init__(self, fulcrum, terrain):
        TerrainCamera.__init__(self)

        self.terrain = terrain
        self.fulcrum = fulcrum
        # in behind Ralph regardless of ralph's movement.
        self.camNode.reparentTo(fulcrum)
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.focus = self.fulcrum.attachNewNode("focus")

        self.maxDistance = 500.0
        self.minDistance = 2
        self.maxPitch = 80
        self.minPitch = -70

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
        self.cTrav = CollisionTraverser()
        self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)

    def zoom(self, zoomIn):
        if (zoomIn):
            self.cameraDistance += 0.1 * self.cameraDistance
        else:
            self.cameraDistance -= 0.1 * self.cameraDistance
        if self.cameraDistance < self.minDistance:
            self.cameraDistance = self.minDistance
        if self.cameraDistance > self.maxDistance:
            self.cameraDistance = self.maxDistance

    def update(self, x, y):

        # alter ralph's yaw by an amount proportionate to deltaX
        self.fulcrum.setH(self.fulcrum.getH() - 0.3 * x)
        # find the new camera pitch and clamp it to a reasonable range
        self.cameraPitch = self.cameraPitch + 0.1 * y
        if (self.cameraPitch < self.minPitch):
            self.cameraPitch = self.minPitch
        if (self.cameraPitch > self.maxPitch):
            self.cameraPitch = self.maxPitch
        self.camNode.setHpr(0, self.cameraPitch, 0)
        # set the camera at around ralph's middle
        # We should pivot around here instead of the view target which is noticebly higher
        self.camNode.setPos(0, 0, 0)
        # back the camera out to its proper distance
        self.camNode.setY(self.camNode, self.cameraDistance)
        self.fixHeight()
        correctedDistance = self.camNode.getPos().length()

        # point the camera at the view target

        forwardOffset = -math.sin(math.radians(self.cameraPitch))
        verticalOffset = 1 - math.sin(math.radians(self.cameraPitch))
        self.focus.setPos(0, forwardOffset,
                          verticalOffset + correctedDistance / 8.0)
        #keep camera from flipping over
        if self.focus.getY() > self.camNode.getY() * 0.9:
            self.focus.setY(self.camNode.getY() * 0.9)
        self.camNode.lookAt(self.focus)
        # reposition the end of the  camera's obstruction ray trace
        self.cameraRay.setPointB(self.camNode.getPos())

        # We will detect anything obstructing the camera via a ray trace
        # from the view target around the avatar's head, to the desired camera
        # podition. If the ray intersects anything, we move the camera to the
        # the first intersection point, This brings the camera in between its
        # ideal position, and any present obstructions.

#        entries = []
#        for i in range(self.cameraColHandler.getNumEntries()):
#            entry = self.cameraColHandler.getEntry(i)
#            entries.append(entry)
#        entries.sort(lambda x,y: cmp(-y.getSurfacePoint(self.ralph).getY(),
#                                     -x.getSurfacePoint(self.ralph).getY()))
#        if (len(entries)>0):
#            collisionPoint =  entries[0].getSurfacePoint(self.ralph)
#            collisionVec = ( viewTarget - collisionPoint)
#            if ( collisionVec.lengthSquared() < self.cameraDistance * self.cameraDistance ):
#                self.camNode.setPos(collisionPoint)
#                if (entries[0].getIntoNode().getName() == "terrain"):
#                    self.camNode.setZ(base.camera, 0.2)
#                self.camNode.setY(base.camera, 0.3)
#

    def fixHeight(self):
        pos = self.camNode.getPos(render)
        minZ = self.terrain.getElevation(pos.x, pos.y) + 1.2
        #logging.info( minZ)
        if pos.z < minZ:
            pos.z = minZ
        self.camNode.setPos(render, pos)
コード例 #26
0
ファイル: fg.py プロジェクト: imelendez/TheAmazeingRace
    def __init__(self):

        self.controlMap = {"left":0, "right":0, "forward":0, "backward":0,
            "zoom-in":0, "zoom-out":0, "wheel-in":0, "wheel-out":0}
        self.mousebtn = [0,0,0]
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Better Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "W A S D keys move Ralph forward, left, back, and right, respectively.")
        self.inst3 = addInstructions(0.85, "Use the mouse to look around and steer Ralph.")
        self.inst4 = addInstructions(0.80, "Zoom in and out using the mouse wheel, or page up and page down keys.")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("w", self.setControl, ["forward",1])
        self.accept("a", self.setControl, ["left",1])
        self.accept("s", self.setControl, ["backward",1])
        self.accept("d", self.setControl, ["right",1])
        self.accept("w-up", self.setControl, ["forward",0])
        self.accept("a-up", self.setControl, ["left",0])
        self.accept("s-up", self.setControl, ["backward",0])
        self.accept("d-up", self.setControl, ["right",0])
#        self.accept("mouse1", self.setControl, ["zoom-in", 1])
#        self.accept("mouse1-up", self.setControl, ["zoom-in", 0])
#        self.accept("mouse3", self.setControl, ["zoom-out", 1])
#        self.accept("mouse3-up", self.setControl, ["zoom-out", 0])
        self.accept("wheel_up", self.setControl, ["wheel-in", 1])
        self.accept("wheel_down", self.setControl, ["wheel-out", 1])
        self.accept("page_up", self.setControl, ["zoom-in", 1])
        self.accept("page_up-up", self.setControl, ["zoom-in", 0])
        self.accept("page_down", self.setControl, ["zoom-out", 1])
        self.accept("page_down-up", self.setControl, ["zoom-out", 0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        # Adding the camera to Ralph is a simple way to keep the camera locked
        # in behind Ralph regardless of ralph's movement.
        base.camera.reparentTo(self.ralph)
        # We don't actually want to point the camera at Ralph's feet.
        # This value will serve as a vertical offset so we can look over Ralph
        self.cameraTargetHeight = 6.0
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        # This just disables the built in camera controls; we're using our own.
        base.disableMouse()
        # The mouse moves rotates the camera so lets get rid of the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # We will detect anything obstructing the camera's view of the player

        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)

############## CollisionTube doesn't seem to be working
#        self.cameraRay = CollisionTube( (0,0,self.cameraTargetHeight),
#                                        (0,25,25),
#                                        (self.cameraTargetHeight/2))
#        self.cameraCol = CollisionNode('cameraRay')
#        self.cameraCol.addSolid(self.cameraRay)
#        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
#        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
#        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
#        self.cameraColHandler = CollisionHandlerQueue()
#        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
############

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
        #self.cameraColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        # lets add hdr lighting for fun
        render.setShaderAuto()
        render.setAttrib(LightRampAttrib.makeHdr1())
        ambientLight = AmbientLight("ambientLight")
        # existing lighting is effectively darkened so boost ambient a bit
        ambientLight.setColor(Vec4(.4, .4, .4, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        # hdr can handle any amount of lighting
        # lets make things nice and sunny
        directionalLight.setColor(Vec4(2.0, 2.0, 2.0, 1.0))
        directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
コード例 #27
0
class HitscanWeapon(Weapon):
    def __init__(self, mask, damage, knockback, range=None):
        Weapon.__init__(self, mask, range, damage, knockback)

        if range is None:
            self.ray = CollisionRay(0, 0, 0, 0, 1, 0)
        else:
            self.ray = CollisionSegment(0, 0, 0, 1, 0, 0)

        rayNode = CollisionNode("playerRay")
        rayNode.addSolid(self.ray)

        rayNode.setFromCollideMask(mask)
        rayNode.setIntoCollideMask(0)

        self.rayNodePath = render.attachNewNode(rayNode)
        self.rayQueue = CollisionHandlerQueue()

        self.traverser = CollisionTraverser()
        self.traverser.addCollider(self.rayNodePath, self.rayQueue)

    def performRayCast(self, origin, direction):
        if isinstance(self.ray, CollisionRay):
            self.ray.setOrigin(origin)
            self.ray.setDirection(direction)
        else:
            self.ray.setPointA(origin)
            self.ray.setPointB(origin + direction * self.range)

        self.traverser.traverse(render)

        if self.rayQueue.getNumEntries() > 0:
            self.rayQueue.sortEntries()
            rayHit = self.rayQueue.getEntry(0)

            return True, rayHit
        else:
            return False, None

    def fire(self, owner, dt):
        Weapon.fire(self, owner, dt)
        rayDir = owner.weaponNP.getQuat(render).getForward()
        hit, hitEntry = self.performRayCast(owner.weaponNP.getPos(render),
                                            rayDir)

        if hit:
            hitNP = hitEntry.getIntoNodePath()
            if hitNP.hasPythonTag(TAG_OWNER):
                subject = hitNP.getPythonTag(TAG_OWNER)
                subject.alterHealth(-self.damage, rayDir * self.knockback,
                                    self.flinchValue)

    def cleanup(self):
        self.traverser.removeCollider(self.rayNodePath)
        self.traverser = None

        if self.rayNodePath is not None:
            self.rayNodePath.removeNode()
            self.rayNodePath = None

        Weapon.cleanup(self)
コード例 #28
0
class RoamingRalphDemo(ShowBase):
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0.6, 0.6, 1.0, 1.0))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0,"cam-left":0,"cam-right":0, "zoom-in":0, "zoom-out":0, "wheel-in":0,"wheel-out":0,
            "c":0, "back":0, "space":0}
        self.mousebtn = [0,0,0];

        # Post the instructions
        #self.title = addTitle(
        #   "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        #self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
        #self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")


        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        #self.environ = loader.loadModel("models/world")
        #self.environ.reparentTo(render)

        self.room = loader.loadModel("models/room2.egg")
        self.room.reparentTo(render)
        #self.room.setScale(.1)
        self.room.setPos(0,0,-5)
        self.room.setShaderAuto()
        #self.room.writeBamFile("myRoom1.bam")
        #self.room.setColor(1,.3,.3,1)

        self.room2 = loader.loadModel("models/abstractroom2")
        self.room2.reparentTo(render)
        self.room2.setScale(.1)
        self.room2.setPos(-12,0,0)

        # Create the main character, Ralph

        #ralphStartPos = LVecBase3F(0,0,0) #self.room.find("**/start_point").getPos()

        self.ralph = Actor("models/chik"
                          )
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0,0,0)
    
        self.gianteye = loader.loadModel("models/gianteye")
        self.gianteye.reparentTo(render)
        self.gianteye.setScale(.1)
        self.gianteye.setPos(10,10,0)   
    
    #self.blue = loader.loadModel("models/blue1")
    #self.blue.reparentTo(render)
    #self.blue.setScale(.1)
    #self.blue.setPos(10,5,0)
    
        self.chik = loader.loadModel("models/chik")
        self.chik.reparentTo(render)
        self.chik.setScale(.1)
        self.chik.setPos(3,13,0)    

        self.pawn = loader.loadModel("pawn")
        self.pawn.reparentTo(render)
        self.pawn.setPos(0,0,0)

        self.shot = loader.loadModel("models/icosphere.egg")
        self.shot.reparentTo(render)
        self.shot.setScale(.5)
        self.shot.setPos(0,0,1)
        self.shot.setColor(1,.3,.3,1)

        self.myShot = loader.loadModel("models/icosphere.egg")
        #self.myShot.reparentTo(render)
        self.myShot.setScale(.1)
        self.myShot.setPos(0,0,1)
        self.myShotVec = LVector3(0,0,0)

        self.lightpivot3 = render.attachNewNode("lightpivot3")
        self.lightpivot3.setPos(0, 0, 0)
        self.lightpivot3.hprInterval(10, LPoint3(0, 0, 0)).loop()
        plight3 = PointLight('plight2')
        plight3.setColor((0, .3,0, 1))
        plight3.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp3 = self.lightpivot3.attachNewNode(plight3)
        plnp3.setPos(0, 0, 0)
        self.room2.setLight(plnp3)
        self.room.setLight(plnp3)
        sphere3 = loader.loadModel("models/icosphere")
        sphere3.reparentTo(plnp3)
        sphere3.setScale(0.1)
        sphere3.setColor((0,1,0,1))

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(8.0)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_down", self.setKey, ["back", 1])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down-up", self.setKey, ["back", 0])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])
        self.accept("wheel_up", self.setKey, ["wheel-in", 1])
        self.accept("wheel_down", self.setKey, ["wheel-out", 1])
        #self.accept("page_up", self.setKey, ["zoom-in", 1])
        #self.accept("page_up-up", self.setKey, ["zoom-in", 0])
        #self.accept("page_down", self.setKey, ["zoom-out", 1])
        #self.accept("page_down-up", self.setKey, ["zoom-out", 0])
    

        self.accept("space", self.setKey, ["space", True])
        self.accept("space-up", self.setKey, ["space", False])

        self.accept("c",self.setKey,["c",True])
        self.accept("c-up",self.setKey,["c",False])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False
        self.jumping = False
        self.vz = 0

        # Set up the camera
        base.camera.reparentTo(self.ralph)
        self.cameraTargetHeight = 6.0
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.disableMouse()
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 7, 3)
        self.camLens.setFov(60)
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        #def setupCollision(self):
        #cs = CollisionSphere(0,0,2,1)
        #cnodePath = self.ralph.attachNewNode(CollisionNode('cnode'))
        #cnodePath.node().addSolid(cs)
        #cnodePath.show()

        #for o in self.OBS:
        #   ct = CollisionTube(0,0,0, 0,0,1, 0.5)
        #   cn = o.attachNewNode(CollisionNode('ocnode'))
        #   cn.node().addSolid(ct)
        #   cn.show()

        #pusher = CollisionHandlerPusher()
        #pusher.addCollider(cnodePath, self.player)
        #self.cTrav = CollisionTraverser()
        #self.cTrav.add_collider(cnodePath,pusher)
        #self.cTrav.showCollisions(render)


        self.cTrav = CollisionTraverser()



        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()

        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()

        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        self.sphere = CollisionSphere(0,0,4,2)
        self.sphere2 = CollisionSphere(0,0,2,2)
        self.cnodePath = self.ralph.attachNewNode((CollisionNode('cnode')))
        self.cnodePath.node().addSolid(self.sphere)
        self.cnodePath.node().addSolid(self.sphere2)
        self.cnodePath.show()
        self.pusher = CollisionHandlerPusher()
        self.pusher.addCollider(self.cnodePath, self.ralph)
        self.cTrav.add_collider(self.cnodePath, self.pusher)

        
        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)


        # Uncomment this line to see the collision rays
        self.ralphGroundColNp.show()
        self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, .4))
        ambientLight2 = AmbientLight("ambientLight2")
        ambientLight2.setColor((1, 1, 1, 10))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((0, 0, -2))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        #self.environ.setLight(self.environ.attachNewNode(ambientLight2))
        render.setLight(render.attachNewNode(directionalLight))

        # Add a light to the scene.
        self.lightpivot = render.attachNewNode("lightpivot")
        self.lightpivot.setPos(0, 0, 1.6)
        self.lightpivot.hprInterval(20, LPoint3(360, 0, 0)).loop()
        plight = PointLight('plight')
        plight.setColor((.7, .3, 0, 1))
        plight.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp = self.lightpivot.attachNewNode(plight)
        plnp.setPos(5, 0, 0)
        self.room.setLight(plnp)
        sphere = loader.loadModel("models/icosphere")
        sphere.reparentTo(plnp)
        sphere.setScale(0.1)
        sphere.setColor((1,1,0,1))

        self.lightpivot2 = render.attachNewNode("lightpivot")
        self.lightpivot2.setPos(-16, 0, 1.6)
        self.lightpivot2.hprInterval(20, LPoint3(360, 0, 0)).loop()
        plight2 = PointLight('plight2')
        plight2.setColor((0, .4,.8, 1))
        plight2.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp2 = self.lightpivot2.attachNewNode(plight2)
        plnp2.setPos(5, 0, 0)
        self.room2.setLight(plnp2)
        sphere2 = loader.loadModel("models/icosphere")
        sphere2.reparentTo(plnp2)
        sphere2.setScale(0.2)
        sphere2.setColor((0,0,1,1))

        self.vec = LVector3(0,1,0)

    # Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # Get the time that elapsed since last frame.  We multiply this with
        # the desired speed in order to find out with which distance to move
        # in order to achieve that desired speed.
        dt = globalClock.getDt()

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        #if self.keyMap["cam-left"]:
            #self.camera.setZ(self.camera, -20 * dt)
        #if self.keyMap["cam-right"]:
            #self.camera.setZ(self.camera, +20 * dt)

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        if (self.keyMap["forward"]!=0):
            self.ralph.setY(self.ralph, -25 * globalClock.getDt())
        if (self.keyMap["back"]!=0):
            self.ralph.setY(self.ralph, 25 * globalClock.getDt())
        if (self.keyMap["left"]!=0):
            self.ralph.setX(self.ralph, 25 * globalClock.getDt())
        if (self.keyMap["right"]!=0):
            self.ralph.setX(self.ralph, -25 * globalClock.getDt())
        if self.keyMap["c"]:
            if self.jumping is False:
            #self.ralph.setH(self.ralph.getH() + 300 * dt)
            #self.ralph.setZ(self.ralph.getZ() + 100 * dt)
                self.jumping = True
                self.vz = 7

        if self.keyMap["space"]:
            self.lightpivot3.setPos(self.ralph.getPos())
            self.lightpivot3.setZ(self.ralph.getZ() + .5)
            self.lightpivot3.setX(self.ralph.getX() - .25)
            #self.myShot.setHpr(self.ralph.getHpr())
            #parent
            node = NodePath("tmp")
            node.setHpr(self.ralph.getHpr())
            vec = render.getRelativeVector(node,(0,-1,0))
            self.myShotVec = vec

        self.lightpivot3.setPos(self.lightpivot3.getPos() + self.myShotVec * dt * 15 )

        
        # If a zoom button is pressed, zoom in or out
        if (self.keyMap["wheel-in"]!=0):
            self.cameraDistance -= 0.1 * self.cameraDistance;
            if (self.cameraDistance < 5):
                self.cameraDistance = 5
            self.keyMap["wheel-in"] = 0
        elif (self.keyMap["wheel-out"]!=0):
            self.cameraDistance += 0.1 * self.cameraDistance;
            if (self.cameraDistance > 250):
                self.cameraDistance = 250
            self.keyMap["wheel-out"] = 0
        #if (self.keyMap["zoom-in"]!=0):
            #self.cameraDistance -= globalClock.getDt() * self.cameraDistance;
            #if (self.cameraDistance < 5):
                #self.cameraDistance = 5
        #elif (self.keyMap["zoom-out"]!=0):
            #self.cameraDistance += globalClock.getDt() * self.cameraDistance;
            #if (self.cameraDistance > 250):
                #self.cameraDistance = 250
        # point the camera at the view target

        
        if base.mouseWatcherNode.hasMouse():
            # get changes in mouse position
            md = base.win.getPointer(0)
            x = md.getX()
            y = md.getY()
            deltaX = md.getX() - 200
            deltaY = md.getY() - 200
            # reset mouse cursor position
            base.win.movePointer(0, 200, 200)
            # alter ralph's yaw by an amount proportionate to deltaX
            self.ralph.setH(self.ralph.getH() - 0.3* deltaX)
            # find the new camera pitch and clamp it to a reasonable range
            self.cameraPitch = self.cameraPitch + 0.1 * deltaY
            if (self.cameraPitch < -60): self.cameraPitch = -60
            if (self.cameraPitch >  80): self.cameraPitch =  80
            base.camera.setHpr(0,self.cameraPitch,0)
            # set the camera at around ralph's middle
            # We should pivot around here instead of the view target which is noticebly higher
            base.camera.setPos(0,0,self.cameraTargetHeight/2)
            # back the camera out to its proper distance
            base.camera.setY(base.camera,self.cameraDistance)
            
        viewTarget = Point3(0,0,self.cameraTargetHeight)
        base.camera.lookAt(viewTarget)
        # reposition the end of the  camera's obstruction ray trace
        self.cameraRay.setPointB(base.camera.getPos())
        # Use mouse input to turn both Ralph and the Camera
            

        if self.jumping is True:
            self.vz = self.vz - 16* dt
            self.ralph.setZ(self.ralph.getZ() + self.vz * dt )
            entries = list(self.ralphGroundHandler.getEntries())
            entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
            if len(entries) > 0 :
                if self.ralph.getZ() < 0:#entries[0].getSurfacePoint(render).getZ():
                    #self.ralph.setZ(entries[0].getSurfacePoint(render).getZ())
                    self.ralph.setZ(0)
                    self.jumping = False
        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        #if self.keyMap["forward"] or self.keyMap["left"] or self.keyMap["right"] or self.keyMap["c"] or self.keyMap["forward"] or self.keyMap["back"]:
            #if self.isMoving is False:
                #self.ralph.loop("run")
                #self.isMoving = True


       # else:
            #if self.isMoving:
               # self.ralph.stop()
                #self.ralph.pose("walk", 5)
                #self.isMoving = False

        #node = NodePath("tmp")
        #node.setHpr(self.ralph.getHpr())
        #vec = render.getRelativeVector(node,(1,0,0))

        #self.ralph.setPos(self.ralph.getPos() + vec * dt * 20)

        node = NodePath("tmp")
        #self.pawn.getH()
        node.setHpr(self.pawn.getHpr())
        vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0))
        self.shot.setPos(self.shot.getPos() + self.vec * dt * 10 )
        if self.shot.getY() < -15 or self.shot.getY() > 15 or self.shot.getX() < -15 or self.shot.getX() > 15:
            self.shot.setPos(self.pawn.getPos() + (0,0,0))
            self.vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0))
            self.vec = render.getRelativeVector(node,(random.random() * -0.8,random.random() + 1,0))

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.ralph.getPos() - self.camera.getPos()
        #camvec.setZ(self.camera.getZ())
        camdist = camvec.length()
        x = self.camera.getZ()
        camvec.normalize()
        if camdist > 6.0:
            self.camera.setPos(self.camera.getPos() + camvec * (camdist - 6))
            camdist = 10.0
            #self.camera.setZ(self.camera, x)
        if camdist < 6.0:
            self.camera.setPos(self.camera.getPos() - camvec * (6 - camdist))
            camdist = 5.0
            #self.camera.setZ(self.camera, x)

        # Normally, we would have to call traverse() to check for collisions.
        # However, the class ShowBase that we inherit from has a task to do
        # this for us, if we assign a CollisionTraverser to self.cTrav.
        #self.cTrav.traverse(render)

        # Adjust ralph's Z coordinate.  If ralph's ray hit terrain,
        # update his Z. If it hit anything else, or didn't hit anything, put
        # him back where he was last frame.

        entries = list(self.ralphGroundHandler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
        if self.jumping == False:
            if len(entries) > 0:# and entries[0].getIntoNode().getName() == "terrain":
                #self.ralph.setZ(entries[0].getSurfacePoint(render).getZ())
                pass
            else:
                self.ralph.setPos(startpos)

        # Keep the camera at one foot above the terrain,
        # or two feet above ralph, whichever is greater.

        entries = list(self.camGroundHandler.getEntries())
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())

        #if len(entries) > 0 and entries[0].getIntoNode().getName() == "ground":
            #self.camera.setZ(entries[0].getSurfacePoint(render).getZ() + 1.5)
        if self.camera.getZ() < self.ralph.getZ() + 1 or self.camera.getZ() > self.ralph.getZ() + 1:
            self.camera.setZ(self.ralph.getZ() + 1)

        #self.camera.setZ(self.ralph.getZ() + 1.5)
        #self.camera.setP(self.camera, 130)

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.
        self.camera.lookAt(self.floater)

        return task.cont
コード例 #29
0
    def setupCollision(self):
        base.cTrav = CollisionTraverser()
        self.collisionHandlerEvent = CollisionHandlerEvent()
        self.physicsCollisionPusher = PhysicsCollisionHandler()

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

        # create masks
        defaultCollisionMask = BitMask32(0b0001)  #0x1
        segmentCollisionMask = BitMask32(0b1000)  #0x8
        stairsCollisionMask = BitMask32(0b0010)  #0x2
        marioBodyCollisionMask = BitMask32(0b0011)  #0x3
        collisionWallsForBarrels = BitMask32(0b0100)  #0x4

        # mario segment collider
        ray = CollisionSegment(7, 0, -4.5, 7, 0, -5.1)
        cnodePath = self.mario.attachNewNode(CollisionNode('marioRay'))
        cnodePath.node().addSolid(ray)
        cnodePath.node().setFromCollideMask(segmentCollisionMask)
        cnodePath.node().setIntoCollideMask(0)
        cnodePath.show()
        base.cTrav.addCollider(cnodePath, self.collisionHandlerEvent)

        self.setupBoxCollider(self.mario, 7, 0, -4.5, 0.5, 5, 0.5,
                              'marioHitBox', self.collisionHandlerEvent,
                              marioBodyCollisionMask, marioBodyCollisionMask)

        stairs1 = self.scene.find("bottomstair")
        self.setupBoxCollider(stairs1, -6.8, 0, -3.0, 0.5, 5, 2.5,
                              'stairs1HitBox', self.collisionHandlerEvent,
                              stairsCollisionMask, stairsCollisionMask)

        stairs2 = self.scene.find("middlestair")
        self.setupBoxCollider(stairs2, -0.86, 0, .1, 0.5, 5, 2.1,
                              'stairs2HitBox', self.collisionHandlerEvent,
                              stairsCollisionMask, stairsCollisionMask)

        stairs3 = self.scene.find("topstair")
        self.setupBoxCollider(stairs3, -6.8, 0, 3.1, 0.5, 5, 2.2,
                              'stairs3HitBox', self.collisionHandlerEvent,
                              stairsCollisionMask, stairsCollisionMask)

        hammer = self.scene.find("MainGroup")  # hammer
        self.setupBoxCollider(hammer, 5.5, 0, -1.5, 0.5, 5, 0.5,
                              'hammer1HitBox', self.collisionHandlerEvent,
                              stairsCollisionMask, stairsCollisionMask)

        dk = self.scene.find("hammer1")
        self.setupBoxCollider(dk, 8.7, 0, 5, 1, 5, 1, 'dkHitBox',
                              self.collisionHandlerEvent, stairsCollisionMask,
                              stairsCollisionMask)

        floor0 = self.scene.find("floor0")
        self.setupBoxCollider(floor0,
                              -2.5,
                              0,
                              -5.5,
                              10,
                              5,
                              0.5,
                              'floor0HitBox',
                              self.collisionHandlerEvent,
                              intoCollisionMask=segmentCollisionMask)

        floor1 = self.scene.find("floor1")
        self.setupBoxCollider(floor1,
                              2,
                              0,
                              -2.5,
                              8.4,
                              5,
                              0.5,
                              'floor1HitBox',
                              self.collisionHandlerEvent,
                              intoCollisionMask=segmentCollisionMask)
        floor2_1 = self.scene.find("floor2")
        self.setupBoxCollider(floor2_1,
                              3.6,
                              0,
                              0.5,
                              3.8,
                              5,
                              0.5,
                              'floor21HitBox',
                              self.collisionHandlerEvent,
                              intoCollisionMask=segmentCollisionMask)
        floor2_2 = self.scene.find("pCube4")
        self.setupBoxCollider(floor2_2,
                              -6.3,
                              0,
                              0.5,
                              5.0,
                              5,
                              0.5,
                              'floor22HitBox',
                              self.collisionHandlerEvent,
                              intoCollisionMask=segmentCollisionMask)
        floor3 = self.scene.find("floors")
        self.setupBoxCollider(floor3,
                              1.8,
                              0,
                              3.5,
                              8,
                              5,
                              0.5,
                              'floor3HitBox',
                              self.collisionHandlerEvent,
                              intoCollisionMask=segmentCollisionMask)

        rightWall = self.scene.find("rightWall")
        self.setupBoxCollider(rightWall,
                              -12,
                              0,
                              0,
                              1,
                              5,
                              10,
                              'rightWallHitBox',
                              self.collisionHandlerEvent,
                              fromCollisionMask=collisionWallsForBarrels,
                              intoCollisionMask=collisionWallsForBarrels)

        leftWall = self.scene.find("walls")
        self.setupBoxCollider(leftWall,
                              11.5,
                              0,
                              0,
                              1,
                              5,
                              10,
                              'leftWallHitBox',
                              self.collisionHandlerEvent,
                              fromCollisionMask=collisionWallsForBarrels,
                              intoCollisionMask=collisionWallsForBarrels)

        barrelFixer = self.scene.attachNewNode("barrelFixer")
        self.setupBoxCollider(barrelFixer,
                              -3,
                              0,
                              0.505,
                              10,
                              5,
                              0.5,
                              'barrelFixerHitBox',
                              self.collisionHandlerEvent,
                              fromCollisionMask=collisionWallsForBarrels,
                              intoCollisionMask=collisionWallsForBarrels)

        barrelDestroyer = self.scene.attachNewNode("barrelDestroyer")
        self.setupBoxCollider(barrelDestroyer,
                              0,
                              0,
                              -8,
                              15,
                              5,
                              0.5,
                              'barrelDestroyerHitBox',
                              self.collisionHandlerEvent,
                              fromCollisionMask=collisionWallsForBarrels,
                              intoCollisionMask=collisionWallsForBarrels)

        self.accept('into-stairs1HitBox', self.enableStair)
        self.accept('outof-stairs1HitBox', self.disableStair)
        self.accept('into-stairs2HitBox', self.enableStair)
        self.accept('outof-stairs2HitBox', self.disableStair)
        self.accept('into-stairs3HitBox', self.enableStair)
        self.accept('outof-stairs3HitBox', self.disableStair)
        self.accept('into-hammer1HitBox', self.enableHammer)
        self.accept('into-dkHitBox', self.dkArrived)

        self.accept('into-floor0HitBox', self.enableJump)
        self.accept('outof-floor0HitBox', self.disableJump)
        self.accept('into-floor1HitBox', self.enableJump)
        self.accept('outof-floor1HitBox', self.disableJump)
        self.accept('into-floor21HitBox', self.enableJump)
        self.accept('outof-floor21HitBox', self.disableJump)
        self.accept('into-floor22HitBox', self.enableJump)
        self.accept('outof-floor22HitBox', self.disableJump)
        self.accept('into-floor3HitBox', self.enableJump)
        self.accept('outof-floor3HitBox', self.disableJump)

        self.accept("into-barrelCollider", self.barrelCrash)

        base.cTrav.showCollisions(self.render)
コード例 #30
0
    def __init__(self, charId, charNr, controls):
        FSM.__init__(self, "FSM-Player{}".format(charNr))
        self.charId = charId
        charPath = "characters/character{}/".format(charNr)
        self.character = Actor(
            charPath + "char", {
                "Idle": charPath + "idle",
                "Walk": charPath + "walk",
                "Walk_back": charPath + "walk_back",
                "Punch_l": charPath + "punch_l",
                "Punch_r": charPath + "punch_r",
                "Kick_l": charPath + "kick_l",
                "Kick_r": charPath + "kick_r",
                "Defend": charPath + "defend",
                "Hit": charPath + "hit",
                "Defeated": charPath + "defeated"
            })
        self.character.reparentTo(render)
        self.character.hide()
        self.walkSpeed = 2.0  # units per second
        if controls == "p1":
            self.character.setH(90)
            self.leftButton = KeyboardButton.asciiKey(b"d")
            self.rightButton = KeyboardButton.asciiKey(b"f")
            self.punchLButton = KeyboardButton.asciiKey(b"q")
            self.punchRButton = KeyboardButton.asciiKey(b"w")
            self.kickLButton = KeyboardButton.asciiKey(b"a")
            self.kickRButton = KeyboardButton.asciiKey(b"s")
            self.defendButton = KeyboardButton.asciiKey(b"e")
        elif controls == "p2":
            self.character.setH(-90)
            self.leftButton = KeyboardButton.right()
            self.rightButton = KeyboardButton.left()
            self.punchLButton = KeyboardButton.asciiKey(b"i")
            self.punchRButton = KeyboardButton.asciiKey(b"o")
            self.kickLButton = KeyboardButton.asciiKey(b"k")
            self.kickRButton = KeyboardButton.asciiKey(b"l")
            self.defendButton = KeyboardButton.asciiKey(b"p")

        self.getPos = self.character.getPos
        self.getX = self.character.getX

        characterSphere = CollisionSphere(0, 0, 1.0, 0.5)
        self.collisionNodeName = "character{}Collision".format(charId)
        characterColNode = CollisionNode(self.collisionNodeName)
        characterColNode.addSolid(characterSphere)
        self.characterCollision = self.character.attachNewNode(
            characterColNode)
        # Uncomment this line to show collision solids
        #self.characterCollision.show()
        base.pusher.addCollider(self.characterCollision, self.character)
        base.cTrav.addCollider(self.characterCollision, base.pusher)

        characterHitRay = CollisionSegment(0, -0.5, 1.0, 0, -0.8, 1.0)
        characterColNode.addSolid(characterHitRay)

        self.audioStep = base.audio3d.loadSfx("assets/audio/step.ogg")
        self.audioStep.setLoop(True)
        base.audio3d.attachSoundToObject(self.audioStep, self.character)

        self.audioHit = base.audio3d.loadSfx("assets/audio/hit.ogg")
        self.audioHit.setLoop(False)
        base.audio3d.attachSoundToObject(self.audioStep, self.character)
コード例 #31
0
ファイル: bulletCamera.py プロジェクト: Wully616/Swifter
class Camera:
    
    """A floating 3rd person camera that follows an actor around, and can be
    turned left or right around the actor.

    Public fields:
    self.controlMap -- The camera's movement controls.
    actor -- The Actor object that the camera will follow.
    
    Public functions:
    init(actor) -- Initialise the camera.
    move(task) -- Move the camera each frame, following the assigned actor.
                  This task is called every frame to update the camera.
    setControl -- Set the camera's turn left or turn right control on or off.
    
    """

    def __init__(self,bController):
        """Initialise the camera, setting it to follow 'actor'.
        
        Arguments:
        bController -- The bullet character controller that the camera will initially follow.
        
        """
        #Get the node path for the CC
        self.bController = bController
        self.actor = bController.capsuleNP
        self.prevtime = 0
        self.setUpCamera()
        taskMgr.add(self.mouseUpdate, 'mouse-task')
        
    def setUpCamera(self):
        """ puts camera behind the player in third person """
        
        
        # Set up the camera
        # Adding the camera to actor is a simple way to keep the camera locked
        # in behind actor regardless of actor's movement.
        base.camera.reparentTo(self.actor)
        # We don't actually want to point the camera at actors's feet.
        # This value will serve as a vertical offset so we can look over the actor
        self.cameraTargetHeight = 0.5
        # How far should the camera be from the actor
        self.cameraDistance = 10
        # Initialize the pitch of the camera
        self.cameraPitch = 45
        
        # The mouse moves rotates the camera so lets get rid of the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        
        #set up FOV
        pl =  base.cam.node().getLens()
        pl.setFov(70)
        base.cam.node().setLens(pl)
        
        # A CollisionRay beginning above the camera and going down toward the
        # ground is used to detect camera collisions and the height of the
        # camera above the ground. A ray may hit the terrain, or it may hit a
        # rock or a tree.  If it hits the terrain, we detect the camera's
        # height.  If it hits anything else, the camera is in an illegal
        # position.
        """
TODO::        This will need to be changed to bullet
        """
        self.cTrav = CollisionTraverser()
        self.groundRay = CollisionRay()
        self.groundRay.setOrigin(0,0,1000)
        self.groundRay.setDirection(0,0,-1)
        self.groundCol = CollisionNode('camRay')
        self.groundCol.addSolid(self.groundRay)
        self.groundCol.setFromCollideMask(BitMask32.bit(1))
        self.groundCol.setIntoCollideMask(BitMask32.allOff())
        self.groundColNp = base.camera.attachNewNode(self.groundCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)
        
        # We will detect anything obstructing the camera's view of the player

        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.actor.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
        # Uncomment this line to see the collision rays
        #self.groundColNp.show()  
        
         
    def mouseUpdate(self,task):
        """ this task updates the mouse """
        
        elapsed = task.time - self.prevtime
        startpos = self.actor.getPos()
        #get the camera to look at the actor
        #base.camera.lookAt(self.actor)

        #Move the camera left/right
        md = base.win.getPointer(0)
        x = md.getX()
        y = md.getY()
        if base.win.movePointer(0, base.win.getXSize()/2, base.win.getYSize()/2):
            
            #turns the actor
            """
            Needs to be changed to move the bullet CC node
            """
            #turns the camera
            self.bController.setH(self.bController.getH() -  (x - base.win.getXSize()/2)*0.1)
            
            #calculate camera pitch
            self.cameraPitch = self.cameraPitch + (y - base.win.getYSize()/2)*0.1
            if (self.cameraPitch < -60): self.cameraPitch = -60
            if (self.cameraPitch >  80): self.cameraPitch =  80
            base.camera.setHpr(0,self.cameraPitch,0)
               
            """
            # set the camera at around actor's middle
            # We should pivot around here instead of the view target which is noticebly higher
            
            """
            #What should the camera pivot around?
            
            base.camera.setPos(0,0,self.cameraTargetHeight) #target head
            #base.camera.setPos(0,0,self.cameraTargetHeight/2) #target body
            
            # back the camera out to its proper distance
            base.camera.setY(base.camera,self.cameraDistance)
            
        # point the camera at the view target
        viewTarget = Point3(0,0,self.cameraTargetHeight)
        base.camera.lookAt(viewTarget)
        # reposition the end of the  camera's obstruction ray trace
        self.cameraRay.setPointB(base.camera.getPos())    

        # Now check for collisions.

        self.cTrav.traverse(render)
        
        # Keep the camera at one foot above the terrain,
        # or two feet above the actor, whichever is greater.
        entries = []
        for i in range(self.groundHandler.getNumEntries()):
            entry = self.groundHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                     x.getSurfacePoint(render).getZ()))
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
            self.actor.setZ(entries[0].getSurfacePoint(render).getZ())
        else:
            self.actor.setPos(startpos)
            
        # We will detect anything obstructing the camera via a ray trace
        # from the view target around the avatar's head, to the desired camera
        # position. If the ray intersects anything, we move the camera to the
        # the first intersection point, This brings the camera in between its
        # ideal position, and any present obstructions.  
        """
TODO::        This will need to be changed to bullet
        """ 
        entries = []
        for i in range(self.cameraColHandler.getNumEntries()):
            entry = self.cameraColHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(-y.getSurfacePoint(self.actor).getY(),
                                     -x.getSurfacePoint(self.actor).getY()))
        if (len(entries)>0):
            collisionPoint =  entries[0].getSurfacePoint(self.actor)
            collisionVec = ( viewTarget - collisionPoint)
            if ( collisionVec.lengthSquared() < self.cameraDistance * self.cameraDistance ):
                base.camera.setPos(collisionPoint)
                if (entries[0].getIntoNode().getName() == "terrain"):
                    base.camera.setZ(base.camera, 0.2)
                base.camera.setY(base.camera, 0.3)
        
        
        return task.cont
コード例 #32
0
    def __init__(self, shipSpec):
        GameObject.__init__(self, Vec3(0, 0,
                                       0), None, None, shipSpec.maxShields,
                            shipSpec.maxSpeed, "player", MASK_INTO_PLAYER, 2)
        ArmedObject.__init__(self)

        self.acceleration = shipSpec.acceleration
        self.turnRate = shipSpec.turnRate

        self.numGuns = len(shipSpec.gunPositions)
        self.numMissiles = shipSpec.numMissiles
        self.maxEnergy = shipSpec.maxEnergy
        self.energyRechargeRate = shipSpec.energyRechargeRate
        self.shieldRechargeRate = shipSpec.shieldRechargeRate

        self.energy = shipSpec.maxEnergy

        for gunPos in shipSpec.gunPositions:
            np = self.actor.attachNewNode(PandaNode("gun node"))
            np.setPos(gunPos)

            gun = BlasterWeapon()
            self.addWeapon(gun, 0, np)

        missileSetCounter = 1
        for missilePos in shipSpec.missilePositions:
            np = self.actor.attachNewNode(PandaNode("missile node"))
            np.setPos(missilePos)

            gun = RocketWeapon()
            self.addWeapon(gun, missileSetCounter, np)
            missileSetCounter += 1

        self.numMissileSets = missileSetCounter - 1
        self.missileSetIndex = 0

        light = PointLight("basic light")
        light.setColor(Vec4(1, 1, 1, 1))
        light.setAttenuation((1, 0.01, 0.001))
        self.lightNP = self.root.attachNewNode(light)
        self.lightNP.setZ(1)
        Common.framework.showBase.render.setLight(self.lightNP)

        self.colliderNP.node().setFromCollideMask(MASK_WALLS
                                                  | MASK_FROM_PLAYER)

        Common.framework.pusher.addCollider(self.colliderNP, self.root)
        Common.framework.traverser.addCollider(self.colliderNP,
                                               Common.framework.pusher)

        Common.framework.showBase.camera.reparentTo(self.actor)
        Common.framework.showBase.camera.setPos(0, 0, 0)
        Common.framework.showBase.camera.setHpr(0, 0, 0)

        lens = Common.framework.showBase.camLens

        lens.setNear(0.03)

        ratio = lens.getAspectRatio()

        lens.setFov(75 * ratio)

        self.lastMousePos = Vec2(0, 0)
        self.mouseSpeedHori = 50.0
        self.mouseSpeedVert = 30.0
        self.mouseSensitivity = 1.0

        self.targetingRay = CollisionSegment(0, 0, 0, 0, 100, 0)
        self.targetingRayNode = CollisionNode("lock ray")
        self.targetingRayNode.addSolid(self.targetingRay)
        self.targetingRayNode.setFromCollideMask(MASK_ENEMY_LOCK_SPHERE)
        self.targetingRayNode.setIntoCollideMask(0)
        self.targetingRayNP = self.actor.attachNewNode(self.targetingRayNode)
        self.targetingQueue = CollisionHandlerQueue()

        self.prospectiveLockTarget = None
        self.lockTargetTimer = 0
        self.lockDuration = 1

        Common.framework.traverser.addCollider(self.targetingRayNP,
                                               self.targetingQueue)

        #rayNodePath.show()

        self.uiRoot = aspect2d.attachNewNode(PandaNode("player UI"))

        cardMaker = CardMaker("UI maker")
        cardMaker.setFrame(-1, 1, -1, 1)

        self.centreSpot = self.uiRoot.attachNewNode(cardMaker.generate())
        self.centreSpot.setTexture(
            Common.framework.showBase.loader.loadTexture(
                "../Section2SpaceflightDocking/UI/spot.png"))
        self.centreSpot.setTransparency(True)
        self.centreSpot.setPos(0, 0, 0)
        self.centreSpot.setScale(0.01)
        self.centreSpot.setAlphaScale(0.5)

        self.directionIndicator = self.uiRoot.attachNewNode(
            cardMaker.generate())
        self.directionIndicator.setTexture(
            Common.framework.showBase.loader.loadTexture(
                "../Section2SpaceflightDocking/UI/directionIndicator.png"))
        self.directionIndicator.setTransparency(True)
        self.directionIndicator.setScale(0.05)
        self.directionIndicator.hide()

        self.lockMarkerRoot = self.uiRoot.attachNewNode(
            PandaNode("lock marker root"))
        for i in range(4):
            markerRotationNP = self.lockMarkerRoot.attachNewNode(
                PandaNode("lock marker rotation"))
            marker = markerRotationNP.attachNewNode(cardMaker.generate())
            marker.setTexture(
                Common.framework.showBase.loader.loadTexture(
                    "../Section2SpaceflightDocking/UI/lockMarker.png"))
            marker.setTransparency(True)
            markerRotationNP.setScale(0.04)
            markerRotationNP.setR(i * 90)
        self.lockMarkerRoot.hide()

        self.lockBar = Common.framework.showBase.loader.loadModel(
            "../Section2SpaceflightDocking/UI/uiLockBar")
        self.lockBar.reparentTo(self.uiRoot)
        self.lockBar.setScale(0.15)
        #self.lockBar.hide()

        cardMaker.setFrame(-1, 1, 0, 1)

        self.cockpit = Common.framework.showBase.loader.loadModel(
            "../Section2SpaceflightDocking/Models/{0}".format(
                shipSpec.cockpitModelFile))
        self.cockpit.reparentTo(self.actor)

        healthBarRoot = self.cockpit.find("**/healthBar")
        if healthBarRoot is None or healthBarRoot.isEmpty():
            healthBarRoot = self.uiRoot.attachNewNode(
                PandaNode("health bar root"))
            print("No health bar root found!")

        energyBarRoot = self.cockpit.find("**/energyBar")
        if energyBarRoot is None or energyBarRoot.isEmpty():
            energyBarRoot = self.uiRoot.attachNewNode(
                PandaNode("energy bar root"))
            print("No energy bar root found!")

        missileCounterRoot = self.cockpit.find("**/missileCounter")
        if missileCounterRoot is None or missileCounterRoot.isEmpty():
            missileCounterRoot = self.uiRoot.attachNewNode(
                PandaNode("missile counter root"))
            print("No missile counter root found!")

        radarRoot = self.cockpit.find("**/radar")
        if radarRoot is None or radarRoot.isEmpty():
            radarRoot = self.uiRoot.attachNewNode(PandaNode("radar root"))
            print("No radar root found!")

        speedometerRoot = self.cockpit.find("**/speedometer")
        if speedometerRoot is None or speedometerRoot.isEmpty():
            speedometerRoot = self.uiRoot.attachNewNode(
                PandaNode("speedometer root"))
            print("No speedometer root found!")

        self.radarDrawer = MeshDrawer()
        self.radarDrawer.setBudget(4096)

        self.radarDrawerNP = self.radarDrawer.getRoot()
        self.radarDrawerNP.reparentTo(radarRoot)
        self.radarDrawerNP.setTwoSided(True)
        self.radarDrawerNP.setLightOff()
        self.radarDrawerNP.setDepthWrite(False)
        self.radarDrawerNP.setTransparency(True)

        self.healthBar = healthBarRoot.attachNewNode(cardMaker.generate())
        self.healthBar.setSx(0.05)

        self.energyBar = energyBarRoot.attachNewNode(cardMaker.generate())
        self.energyBar.setSx(0.05)

        self.healthBarScalar = 0.00175
        self.energyBarScalar = 0.00175

        self.missileCounter = DirectLabel(text="",
                                          text_mayChange=True,
                                          scale=0.09,
                                          relief=None,
                                          parent=missileCounterRoot)

        self.maxRadarRange = 700
        self.radarSize = 0.3

        self.speedometer = DirectLabel(text="",
                                       text_mayChange=True,
                                       scale=0.09,
                                       relief=None,
                                       parent=speedometerRoot)

        self.updateHealthUI()
        self.updateEnergyUI()
        self.updateMissileUI()
        self.updateRadar()
        self.updateSpeedometer()

        self.updatingEffects = []
コード例 #33
0
class PositionExaminer(DirectObject, NodePath):

    def __init__(self):
        try:
            self.__initialized
            return
        except:
            self.__initialized = 1

        NodePath.__init__(self, hidden.attachNewNode('PositionExaminer'))
        self.cRay = CollisionRay(0.0, 0.0, 6.0, 0.0, 0.0, -1.0)
        self.cRayNode = CollisionNode('cRayNode')
        self.cRayNode.addSolid(self.cRay)
        self.cRayNodePath = self.attachNewNode(self.cRayNode)
        self.cRayNodePath.hide()
        self.cRayBitMask = CIGlobals.FloorBitmask
        self.cRayNode.setFromCollideMask(self.cRayBitMask)
        self.cRayNode.setIntoCollideMask(BitMask32.allOff())
        self.cSphere = CollisionSphere(0.0, 0.0, 0.0, 1.5)
        self.cSphereNode = CollisionNode('cSphereNode')
        self.cSphereNode.addSolid(self.cSphere)
        self.cSphereNodePath = self.attachNewNode(self.cSphereNode)
        self.cSphereNodePath.hide()
        self.cSphereBitMask = CIGlobals.WallBitmask
        self.cSphereNode.setFromCollideMask(self.cSphereBitMask)
        self.cSphereNode.setIntoCollideMask(BitMask32.allOff())
        self.ccLine = CollisionSegment(0.0, 0.0, 0.0, 1.0, 0.0, 0.0)
        self.ccLineNode = CollisionNode('ccLineNode')
        self.ccLineNode.addSolid(self.ccLine)
        self.ccLineNodePath = self.attachNewNode(self.ccLineNode)
        self.ccLineNodePath.hide()
        self.ccLineBitMask = CIGlobals.CameraBitmask
        self.ccLineNode.setFromCollideMask(self.ccLineBitMask)
        self.ccLineNode.setIntoCollideMask(BitMask32.allOff())
        self.cRayTrav = CollisionTraverser('PositionExaminer.cRayTrav')
        self.cRayTrav.setRespectPrevTransform(False)
        self.cRayQueue = CollisionHandlerQueue()
        self.cRayTrav.addCollider(self.cRayNodePath, self.cRayQueue)
        self.cSphereTrav = CollisionTraverser('PositionExaminer.cSphereTrav')
        self.cSphereTrav.setRespectPrevTransform(False)
        self.cSphereQueue = CollisionHandlerQueue()
        self.cSphereTrav.addCollider(self.cSphereNodePath, self.cSphereQueue)
        self.ccLineTrav = CollisionTraverser('PositionExaminer.ccLineTrav')
        self.ccLineTrav.setRespectPrevTransform(False)
        self.ccLineQueue = CollisionHandlerQueue()
        self.ccLineTrav.addCollider(self.ccLineNodePath, self.ccLineQueue)

    def delete(self):
        del self.cRay
        del self.cRayNode
        self.cRayNodePath.removeNode()
        del self.cRayNodePath
        del self.cSphere
        del self.cSphereNode
        self.cSphereNodePath.removeNode()
        del self.cSphereNodePath
        del self.ccLine
        del self.ccLineNode
        self.ccLineNodePath.removeNode()
        del self.ccLineNodePath
        del self.cRayTrav
        del self.cRayQueue
        del self.cSphereTrav
        del self.cSphereQueue
        del self.ccLineTrav
        del self.ccLineQueue

    def consider(self, node, pos, eyeHeight):
        self.reparentTo(node)
        self.setPos(pos)
        result = None
        self.cRayTrav.traverse(render)
        if self.cRayQueue.getNumEntries() != 0:
            self.cRayQueue.sortEntries()
            floorPoint = self.cRayQueue.getEntry(0).getSurfacePoint(self.cRayNodePath)
            if abs(floorPoint[2]) <= 4.0:
                pos += floorPoint
                self.setPos(pos)
                self.cSphereTrav.traverse(render)
                if self.cSphereQueue.getNumEntries() == 0:
                    self.ccLine.setPointA(0, 0, eyeHeight)
                    self.ccLine.setPointB(-pos[0], -pos[1], eyeHeight)
                    self.ccLineTrav.traverse(render)
                    if self.ccLineQueue.getNumEntries() == 0:
                        result = pos
        self.reparentTo(hidden)
        self.cRayQueue.clearEntries()
        self.cSphereQueue.clearEntries()
        self.ccLineQueue.clearEntries()
        return result
コード例 #34
0
ファイル: fg.py プロジェクト: imelendez/TheAmazeingRace
class World(DirectObject):

    def __init__(self):

        self.controlMap = {"left":0, "right":0, "forward":0, "backward":0,
            "zoom-in":0, "zoom-out":0, "wheel-in":0, "wheel-out":0}
        self.mousebtn = [0,0,0]
        base.win.setClearColor(Vec4(0,0,0,1))

        # Post the instructions

        self.title = addTitle("Panda3D Tutorial: Better Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "W A S D keys move Ralph forward, left, back, and right, respectively.")
        self.inst3 = addInstructions(0.85, "Use the mouse to look around and steer Ralph.")
        self.inst4 = addInstructions(0.80, "Zoom in and out using the mouse wheel, or page up and page down keys.")

        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        self.environ = loader.loadModel("models/world")
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)

        # Create the main character, Ralph

        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("w", self.setControl, ["forward",1])
        self.accept("a", self.setControl, ["left",1])
        self.accept("s", self.setControl, ["backward",1])
        self.accept("d", self.setControl, ["right",1])
        self.accept("w-up", self.setControl, ["forward",0])
        self.accept("a-up", self.setControl, ["left",0])
        self.accept("s-up", self.setControl, ["backward",0])
        self.accept("d-up", self.setControl, ["right",0])
#        self.accept("mouse1", self.setControl, ["zoom-in", 1])
#        self.accept("mouse1-up", self.setControl, ["zoom-in", 0])
#        self.accept("mouse3", self.setControl, ["zoom-out", 1])
#        self.accept("mouse3-up", self.setControl, ["zoom-out", 0])
        self.accept("wheel_up", self.setControl, ["wheel-in", 1])
        self.accept("wheel_down", self.setControl, ["wheel-out", 1])
        self.accept("page_up", self.setControl, ["zoom-in", 1])
        self.accept("page_up-up", self.setControl, ["zoom-in", 0])
        self.accept("page_down", self.setControl, ["zoom-out", 1])
        self.accept("page_down-up", self.setControl, ["zoom-out", 0])

        taskMgr.add(self.move,"moveTask")

        # Game state variables
        self.isMoving = False

        # Set up the camera
        # Adding the camera to Ralph is a simple way to keep the camera locked
        # in behind Ralph regardless of ralph's movement.
        base.camera.reparentTo(self.ralph)
        # We don't actually want to point the camera at Ralph's feet.
        # This value will serve as a vertical offset so we can look over Ralph
        self.cameraTargetHeight = 6.0
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        # This just disables the built in camera controls; we're using our own.
        base.disableMouse()
        # The mouse moves rotates the camera so lets get rid of the cursor
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)
        

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        self.cTrav = CollisionTraverser()

        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        # We will detect anything obstructing the camera's view of the player

        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)

############## CollisionTube doesn't seem to be working
#        self.cameraRay = CollisionTube( (0,0,self.cameraTargetHeight),
#                                        (0,25,25),
#                                        (self.cameraTargetHeight/2))
#        self.cameraCol = CollisionNode('cameraRay')
#        self.cameraCol.addSolid(self.cameraRay)
#        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
#        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
#        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
#        self.cameraColHandler = CollisionHandlerQueue()
#        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
############

        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
        #self.cameraColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        # lets add hdr lighting for fun
        render.setShaderAuto()
        render.setAttrib(LightRampAttrib.makeHdr1())
        ambientLight = AmbientLight("ambientLight")
        # existing lighting is effectively darkened so boost ambient a bit
        ambientLight.setColor(Vec4(.4, .4, .4, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        # hdr can handle any amount of lighting
        # lets make things nice and sunny
        directionalLight.setColor(Vec4(2.0, 2.0, 2.0, 1.0))
        directionalLight.setSpecularColor(Vec4(2.0, 2.0, 2.0, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

    #Records the state of the arrow keys
    def setControl(self, key, value):
        self.controlMap[key] = value


    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.
        if (self.controlMap["forward"]!=0):
            self.ralph.setY(self.ralph, -25 * globalClock.getDt())
        if (self.controlMap["backward"]!=0):
            self.ralph.setY(self.ralph, 25 * globalClock.getDt())
        if (self.controlMap["left"]!=0):
            self.ralph.setX(self.ralph, 25 * globalClock.getDt())
        if (self.controlMap["right"]!=0):
            self.ralph.setX(self.ralph, -25 * globalClock.getDt())

        # If a zoom button is pressed, zoom in or out
        if (self.controlMap["wheel-in"]!=0):
            self.cameraDistance -= 0.1 * self.cameraDistance;
            if (self.cameraDistance < 5):
                self.cameraDistance = 5
            self.controlMap["wheel-in"] = 0
        elif (self.controlMap["wheel-out"]!=0):
            self.cameraDistance += 0.1 * self.cameraDistance;
            if (self.cameraDistance > 250):
                self.cameraDistance = 250
            self.controlMap["wheel-out"] = 0
        if (self.controlMap["zoom-in"]!=0):
            self.cameraDistance -= globalClock.getDt() * self.cameraDistance;
            if (self.cameraDistance < 5):
                self.cameraDistance = 5
        elif (self.controlMap["zoom-out"]!=0):
            self.cameraDistance += globalClock.getDt() * self.cameraDistance;
            if (self.cameraDistance > 250):
                self.cameraDistance = 250

        # Use mouse input to turn both Ralph and the Camera
        if base.mouseWatcherNode.hasMouse():
            # get changes in mouse position
            md = base.win.getPointer(0)
            x = md.getX()
            y = md.getY()
            deltaX = md.getX() - 200
            deltaY = md.getY() - 200
            # reset mouse cursor position
            base.win.movePointer(0, 200, 200)
            # alter ralph's yaw by an amount proportionate to deltaX
            self.ralph.setH(self.ralph.getH() - 0.3* deltaX)
            # find the new camera pitch and clamp it to a reasonable range
            self.cameraPitch = self.cameraPitch + 0.1 * deltaY
            if (self.cameraPitch < -60): self.cameraPitch = -60
            if (self.cameraPitch >  80): self.cameraPitch =  80
            base.camera.setHpr(0,self.cameraPitch,0)
            # set the camera at around ralph's middle
            # We should pivot around here instead of the view target which is noticebly higher
            base.camera.setPos(0,0,self.cameraTargetHeight/2)
            # back the camera out to its proper distance
            base.camera.setY(base.camera,self.cameraDistance)

        # point the camera at the view target
        viewTarget = Point3(0,0,self.cameraTargetHeight)
        base.camera.lookAt(viewTarget)
        # reposition the end of the  camera's obstruction ray trace
        self.cameraRay.setPointB(base.camera.getPos())


        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if (self.controlMap["forward"]!=0) or (self.controlMap["left"]!=0) or (self.controlMap["right"]!=0) or (self.controlMap["backward"]!=0):
            if self.isMoving is False:
                self.ralph.loop("run")
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.ralph.pose("walk",5)
                self.isMoving = False

        # Now check for collisions.

        self.cTrav.traverse(render)

        # Adjust ralph's Z coordinate.  If ralph's ray hit terrain,
        # update his Z. If it hit anything else, or didn't hit anything, put
        # him back where he was last frame.

        entries = []
        for i in range(self.ralphGroundHandler.getNumEntries()):
            entry = self.ralphGroundHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(y.getSurfacePoint(render).getZ(),
                                     x.getSurfacePoint(render).getZ()))
        if (len(entries)>0) and (entries[0].getIntoNode().getName() == "terrain"):
            self.ralph.setZ(entries[0].getSurfacePoint(render).getZ())
        else:
            self.ralph.setPos(startpos)

        # We will detect anything obstructing the camera via a ray trace
        # from the view target around the avatar's head, to the desired camera
        # podition. If the ray intersects anything, we move the camera to the
        # the first intersection point, This brings the camera in between its
        # ideal position, and any present obstructions.

        entries = []
        for i in range(self.cameraColHandler.getNumEntries()):
            entry = self.cameraColHandler.getEntry(i)
            entries.append(entry)
        entries.sort(lambda x,y: cmp(-y.getSurfacePoint(self.ralph).getY(),
                                     -x.getSurfacePoint(self.ralph).getY()))
        if (len(entries)>0):
            collisionPoint =  entries[0].getSurfacePoint(self.ralph)
            collisionVec = ( viewTarget - collisionPoint)
            if ( collisionVec.lengthSquared() < self.cameraDistance * self.cameraDistance ):
                base.camera.setPos(collisionPoint)
                if (entries[0].getIntoNode().getName() == "terrain"):
                    base.camera.setZ(base.camera, 0.2)
                base.camera.setY(base.camera, 0.3)

        return task.cont
コード例 #35
0
ファイル: weapon.py プロジェクト: grimfang/owp_shooter
class Weapon(DirectObject):
    def __init__(self, _main, _name, _fireRate, _dmg=20,_mountSlot=0, weaponType="Pistol"):
        self.main = _main
        self.name = _name
        self.fireRate = _fireRate
        self.dmg = _dmg
        self.weaponType = weaponType
        self.mountSlot = _mountSlot

        self.muzzleFlash = loader.loadModel("muzzleflash")
        if weaponType == "Pistol":
            self.style = "OneHand"
            self.model = loader.loadModel("Pistol")
            self.muzzleFlash.setZ(0.65)
            self.muzzleFlash.setX(-0.04)
            self.muzzleFlash.setScale(0.25)
            self.muzzleFlash.find('**/+SequenceNode').node().setFrameRate(20)
        else:
            self.style = "TwoHand"
            self.model = loader.loadModel("MG")
            self.muzzleFlash.setZ(0.65)
            self.muzzleFlash.setX(0.08)
            self.muzzleFlash.setScale(0.3)
            self.muzzleFlash.find('**/+SequenceNode').node().setFrameRate(20)
        self.model.setY(2)
        self.muzzleFlash.reparentTo(self.model)
        self.muzzleFlash.find('**/+SequenceNode').node().stop()
        self.muzzleFlash.hide()

        # Load bullet model
        self.bullet = loader.loadModel("Bullet")
        self.bullet.setP(-90)
        self.bullet.setH(180)
        #self.bullet.setPos(0, 0.5, 0)

        # Control
        self.isFiring = False

        # Collision Stuff
        self.wepRay = None
        # Make weapon ray
        self.setupRay()
        self.model.show()

    def setAmmo(self):
        pass

    def setupRay(self):
        self.shootTraverser = CollisionTraverser()
        self.shootingQH = CollisionHandlerQueue()
        #self.shootingEH = CollisionHandlerEvent()
        #self.shootingEH.addInPattern('into-%in')
        # Create a collision Node
        shootNode = CollisionNode('WeaponRay')
        # set the nodes collision bitmask
        shootNode.setFromCollideMask(BitMask32.bit(1))
        # create a collision segment (ray like)
        self.shootRay = CollisionSegment()
        shootNode.addSolid(self.shootRay)
        #self.pickerNP = self.main.player.model.attachNewNode(pickerNode)
        self.shootNP = render.attachNewNode(shootNode)
        #self.shootTraverser.addCollider(self.shootNP, self.shootingEH)
        self.shootTraverser.addCollider(self.shootNP, self.shootingQH)
        #self.shootNP.show()

    def doFire(self, _toPos=(0, 0, 0)):
        self.isFiring = True

        if self.weaponType == "Pistol":
            self.muzzleFlash.find('**/+SequenceNode').node().play(0, 1)
        else:
            self.muzzleFlash.find('**/+SequenceNode').node().loop(True)
        self.muzzleFlash.show()

        # For some reason the mouse ray end up at posZ -1 (which causes a problem when we make the enemy spheres smaller in radius)
        # so here for now.. ill make a quick fix.
        adjustedZ = (_toPos[0], _toPos[1], 0)

        self.shootRay.setPointA(self.main.player.model.getPos())
        self.shootRay.setPointB(adjustedZ)

        fromPos = self.main.player.model.getPos() #self.model.getPos()
        #self.setProjectile(fromPos, adjustedZ)#_toPos)

        self.shootTraverser.traverse(self.main.enemyParent)
        if self.shootingQH.getNumEntries() > 0:
            self.shootingQH.sortEntries()
            enemyCol = self.shootingQH.getEntry(0).getIntoNodePath().node().getName()
            base.messenger.send("into-" + enemyCol, [self.dmg])

    def stopFire(self):
        if self.weaponType == "Pistol" and \
               self.muzzleFlash.find('**/+SequenceNode').node().isPlaying():
            taskMgr.add(self.waitForFrame, "waitForFrame")
            return
        self.muzzleFlash.find('**/+SequenceNode').node().stop()
        self.muzzleFlash.hide()

    def waitForFrame(self, task):
        if self.muzzleFlash.find('**/+SequenceNode').node().isPlaying():
            return task.cont
        self.muzzleFlash.find('**/+SequenceNode').node().stop()
        self.muzzleFlash.hide()

    def reload(self):
        pass

    def setProjectile(self, _from, _to):
        self.bullet.reparentTo(render)#self.model)
        # setup the projectile interval
        #self.bulletProjectile = ProjectileInterval(self.bullet,
        #                                startPos = Point3(_from),
        #                                duration = 1,
        #                                endPos = Point3(_to))
        #self.bulletProjectile = self.bullet.posInterval(1.0, Point3(_to), startPos=Point3(_from))
        #self.bulletProjectile = LerpPosInterval(self.bullet, 2.0, _to, _from)
        print "POSITIONS:"
        print _to
        print _from
        frm = render.getPos(self.main.player.model)
        print frm

        self.bulletProjectile = LerpPosInterval(self.bullet, 1.0, _to, _from)
        self.bulletProjectile.start()
コード例 #36
0
    def __init__(self):
        # Set up the window, camera, etc.
        ShowBase.__init__(self)

        # Set the background color to black
        self.win.setClearColor((0.6, 0.6, 1.0, 1.0))

        # This is used to store which keys are currently pressed.
        self.keyMap = {
            "left": 0, "right": 0, "forward": 0,"cam-left":0,"cam-right":0, "zoom-in":0, "zoom-out":0, "wheel-in":0,"wheel-out":0,
            "c":0, "back":0, "space":0}
        self.mousebtn = [0,0,0];

        # Post the instructions
        #self.title = addTitle(
        #   "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        self.inst1 = addInstructions(0.06, "[ESC]: Quit")
        self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward")
        #self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left")
        #self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right")


        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.

        #self.environ = loader.loadModel("models/world")
        #self.environ.reparentTo(render)

        self.room = loader.loadModel("models/room2.egg")
        self.room.reparentTo(render)
        #self.room.setScale(.1)
        self.room.setPos(0,0,-5)
        self.room.setShaderAuto()
        #self.room.writeBamFile("myRoom1.bam")
        #self.room.setColor(1,.3,.3,1)

        self.room2 = loader.loadModel("models/abstractroom2")
        self.room2.reparentTo(render)
        self.room2.setScale(.1)
        self.room2.setPos(-12,0,0)

        # Create the main character, Ralph

        #ralphStartPos = LVecBase3F(0,0,0) #self.room.find("**/start_point").getPos()

        self.ralph = Actor("models/chik"
                          )
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0,0,0)
    
        self.gianteye = loader.loadModel("models/gianteye")
        self.gianteye.reparentTo(render)
        self.gianteye.setScale(.1)
        self.gianteye.setPos(10,10,0)   
    
    #self.blue = loader.loadModel("models/blue1")
    #self.blue.reparentTo(render)
    #self.blue.setScale(.1)
    #self.blue.setPos(10,5,0)
    
        self.chik = loader.loadModel("models/chik")
        self.chik.reparentTo(render)
        self.chik.setScale(.1)
        self.chik.setPos(3,13,0)    

        self.pawn = loader.loadModel("pawn")
        self.pawn.reparentTo(render)
        self.pawn.setPos(0,0,0)

        self.shot = loader.loadModel("models/icosphere.egg")
        self.shot.reparentTo(render)
        self.shot.setScale(.5)
        self.shot.setPos(0,0,1)
        self.shot.setColor(1,.3,.3,1)

        self.myShot = loader.loadModel("models/icosphere.egg")
        #self.myShot.reparentTo(render)
        self.myShot.setScale(.1)
        self.myShot.setPos(0,0,1)
        self.myShotVec = LVector3(0,0,0)

        self.lightpivot3 = render.attachNewNode("lightpivot3")
        self.lightpivot3.setPos(0, 0, 0)
        self.lightpivot3.hprInterval(10, LPoint3(0, 0, 0)).loop()
        plight3 = PointLight('plight2')
        plight3.setColor((0, .3,0, 1))
        plight3.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp3 = self.lightpivot3.attachNewNode(plight3)
        plnp3.setPos(0, 0, 0)
        self.room2.setLight(plnp3)
        self.room.setLight(plnp3)
        sphere3 = loader.loadModel("models/icosphere")
        sphere3.reparentTo(plnp3)
        sphere3.setScale(0.1)
        sphere3.setColor((0,1,0,1))

        # Create a floater object, which floats 2 units above ralph.  We
        # use this as a target for the camera to look at.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(self.ralph)
        self.floater.setZ(8.0)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("arrow_down", self.setKey, ["back", 1])
        self.accept("a", self.setKey, ["cam-left", True])
        self.accept("s", self.setKey, ["cam-right", True])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("arrow_down-up", self.setKey, ["back", 0])
        self.accept("a-up", self.setKey, ["cam-left", False])
        self.accept("s-up", self.setKey, ["cam-right", False])
        self.accept("wheel_up", self.setKey, ["wheel-in", 1])
        self.accept("wheel_down", self.setKey, ["wheel-out", 1])
        #self.accept("page_up", self.setKey, ["zoom-in", 1])
        #self.accept("page_up-up", self.setKey, ["zoom-in", 0])
        #self.accept("page_down", self.setKey, ["zoom-out", 1])
        #self.accept("page_down-up", self.setKey, ["zoom-out", 0])
    

        self.accept("space", self.setKey, ["space", True])
        self.accept("space-up", self.setKey, ["space", False])

        self.accept("c",self.setKey,["c",True])
        self.accept("c-up",self.setKey,["c",False])

        taskMgr.add(self.move, "moveTask")

        # Game state variables
        self.isMoving = False
        self.jumping = False
        self.vz = 0

        # Set up the camera
        base.camera.reparentTo(self.ralph)
        self.cameraTargetHeight = 6.0
        # How far should the camera be from Ralph
        self.cameraDistance = 30
        # Initialize the pitch of the camera
        self.cameraPitch = 10
        self.disableMouse()
        self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 7, 3)
        self.camLens.setFov(60)
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.

        #def setupCollision(self):
        #cs = CollisionSphere(0,0,2,1)
        #cnodePath = self.ralph.attachNewNode(CollisionNode('cnode'))
        #cnodePath.node().addSolid(cs)
        #cnodePath.show()

        #for o in self.OBS:
        #   ct = CollisionTube(0,0,0, 0,0,1, 0.5)
        #   cn = o.attachNewNode(CollisionNode('ocnode'))
        #   cn.node().addSolid(ct)
        #   cn.show()

        #pusher = CollisionHandlerPusher()
        #pusher.addCollider(cnodePath, self.player)
        #self.cTrav = CollisionTraverser()
        #self.cTrav.add_collider(cnodePath,pusher)
        #self.cTrav.showCollisions(render)


        self.cTrav = CollisionTraverser()



        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0, 0, 9)
        self.ralphGroundRay.setDirection(0, 0, -1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()

        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)

        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0, 0, 9)
        self.camGroundRay.setDirection(0, 0, -1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(CollideMask.bit(0))
        self.camGroundCol.setIntoCollideMask(CollideMask.allOff())
        self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()

        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)

        self.sphere = CollisionSphere(0,0,4,2)
        self.sphere2 = CollisionSphere(0,0,2,2)
        self.cnodePath = self.ralph.attachNewNode((CollisionNode('cnode')))
        self.cnodePath.node().addSolid(self.sphere)
        self.cnodePath.node().addSolid(self.sphere2)
        self.cnodePath.show()
        self.pusher = CollisionHandlerPusher()
        self.pusher.addCollider(self.cnodePath, self.ralph)
        self.cTrav.add_collider(self.cnodePath, self.pusher)

        
        self.cameraRay = CollisionSegment((0,0,self.cameraTargetHeight),(0,5,5))
        self.cameraCol = CollisionNode('cameraRay')
        self.cameraCol.addSolid(self.cameraRay)
        self.cameraCol.setFromCollideMask(BitMask32.bit(0))
        self.cameraCol.setIntoCollideMask(BitMask32.allOff())
        self.cameraColNp = self.ralph.attachNewNode(self.cameraCol)
        self.cameraColHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)


        # Uncomment this line to see the collision rays
        self.ralphGroundColNp.show()
        self.camGroundColNp.show()

        # Uncomment this line to show a visual representation of the
        # collisions occuring
        #self.cTrav.showCollisions(render)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor((.3, .3, .3, .4))
        ambientLight2 = AmbientLight("ambientLight2")
        ambientLight2.setColor((1, 1, 1, 10))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection((0, 0, -2))
        directionalLight.setColor((1, 1, 1, 1))
        directionalLight.setSpecularColor((1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        #self.environ.setLight(self.environ.attachNewNode(ambientLight2))
        render.setLight(render.attachNewNode(directionalLight))

        # Add a light to the scene.
        self.lightpivot = render.attachNewNode("lightpivot")
        self.lightpivot.setPos(0, 0, 1.6)
        self.lightpivot.hprInterval(20, LPoint3(360, 0, 0)).loop()
        plight = PointLight('plight')
        plight.setColor((.7, .3, 0, 1))
        plight.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp = self.lightpivot.attachNewNode(plight)
        plnp.setPos(5, 0, 0)
        self.room.setLight(plnp)
        sphere = loader.loadModel("models/icosphere")
        sphere.reparentTo(plnp)
        sphere.setScale(0.1)
        sphere.setColor((1,1,0,1))

        self.lightpivot2 = render.attachNewNode("lightpivot")
        self.lightpivot2.setPos(-16, 0, 1.6)
        self.lightpivot2.hprInterval(20, LPoint3(360, 0, 0)).loop()
        plight2 = PointLight('plight2')
        plight2.setColor((0, .4,.8, 1))
        plight2.setAttenuation(LVector3(0.7, 0.05, 0))
        plnp2 = self.lightpivot2.attachNewNode(plight2)
        plnp2.setPos(5, 0, 0)
        self.room2.setLight(plnp2)
        sphere2 = loader.loadModel("models/icosphere")
        sphere2.reparentTo(plnp2)
        sphere2.setScale(0.2)
        sphere2.setColor((0,0,1,1))

        self.vec = LVector3(0,1,0)
コード例 #37
0
ファイル: camera.py プロジェクト: Vetrik/python-utils
class FollowCamera(TerrainCamera):
	def __init__(self, fulcrum, terrain):
		TerrainCamera.__init__(self)
		
		self.terrain = terrain
		self.fulcrum = fulcrum
		
		self.camNode.reparentTo(fulcrum)
		# How far should the camera be from character
		self.cameraDistance = 30
		# Initialize pitch of camera
		self.cameraPitch = 10
		self.focus = self.fulcrum.attachNewNode("focus")
		
		self.maxDistance = 500.0
		self.minDistance = 2
		self.maxPitch = 80
		self.minPitch = -70
		
		# We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
		self.cTrav = CollisionTraverser()
		self.cameraRay = CollisionSegment(self.fulcrum.getPos(), (0, 5, 5))
		self.cameraCol = CollisionNode('cameraRay')
		self.cameraCol.addSolid(self.cameraRay)
		self.cameraCol.setFromCollideMask(BitMask32.bit(0))
		self.cameraCol.setIntoCollideMask(BitMask32.allOff())
		self.cameraColNp = self.fulcrum.attachNewNode(self.cameraCol)
		self.cameraColHandler = CollisionHandlerQueue()
		self.cTrav.addCollider(self.cameraColNp, self.cameraColHandler)
		
	def zoom(self, zoomIn):
		if (zoomIn):
			self.cameraDistance += 0.1 * self.cameraDistance;
		else:
			self.cameraDistance -= 0.1 * self.cameraDistance;
		if self.cameraDistance < self.minDistance:
			self.cameraDistance = self.minDistance
		if self.cameraDistance > self.maxDistance:
			self.cameraDistance = self.maxDistance
			
	def update(self, x, y):
		# alter characters yaw by an amount proportionate to deltaX
		self.fulcrum.setH(self.fulcrum.getH() - 0.3 * x)
		# find the new camera pitch and clamp it to a reasonable range
		self.cameraPitch = self.cameraPitch + 0.1 * y
		if (self.cameraPitch < self.minPitch):
			self.cameraPitch = self.minPitch
		if (self.cameraPitch > self.maxPitch):
			self.cameraPitch = self.maxPitch
		self.cameraNode.setHpr(0, self.cameraPitch, 0)
		# set the camera at characters middle
		# should pivot around here instead of the view target which is noticeably higher
		self.camNode.setPos(0,0,0)
		# back the camera out to its proper distance
		self.camNode.setY(self.camNode, self.cameraDistance)
		self.fixHeight()
		correctedDistance = self.camNode.getPos().length()
		
		# point the camera at the view target
		forwardOffset = -math.sin(math.radians(self.cameraPitch))
		verticalOffset = 1 - math.sin(math.radians(self.cameraPitch))
		self.focus.setPos(0, forwardOffset, verticalOffset + correctedDistance / 8.0)
		# keep camera from flipping over
		if self.focus.getY() > self.camNode.getY() * 0.9:
			self.focus.setY(self.camNode.getY() * 0.9
		self.camNode.lookAt(self.focus)
		# reposition the end of the cameras obstruction ray trace
		self.cameraRay.setPointB(self.camNode.getPos())
		
	def fixHeight(self):
		pos = self.camNode.getPos(render)
		minz = self.terrain.getElevation(pos.x, pos.y) + 1.2
		if pos.z = minZ:
			pos.z = minZ
		self.camNode.setPos(render, pos)
	
コード例 #38
0
ファイル: raycaster.py プロジェクト: marhone/ursina
    def raycast(self,
                origin,
                direction=(0, 0, 1),
                distance=math.inf,
                traverse_target=scene,
                ignore=list(),
                debug=False):
        self.position = origin
        self.look_at(self.position + direction)
        self._pickerNode.clearSolids()
        # if thickness == (0,0):
        if distance == math.inf:
            ray = CollisionRay()
            ray.setOrigin(Vec3(0, 0, 0))
            ray.setDirection(Vec3(0, 1, 0))
        else:
            ray = CollisionSegment(Vec3(0, 0, 0), Vec3(0, distance, 0))

        self._pickerNode.addSolid(ray)

        if debug:
            self._pickerNP.show()
        else:
            self._pickerNP.hide()

        self._picker.traverse(traverse_target)

        if self._pq.get_num_entries() == 0:
            self.hit = Hit(hit=False)
            return self.hit

        ignore += tuple([e for e in scene.entities if not e.collision])

        self._pq.sort_entries()
        self.entries = [  # filter out ignored entities
            e for e in self._pq.getEntries()
            if e.get_into_node_path().parent not in ignore
        ]

        if len(self.entries) == 0:
            self.hit = Hit(hit=False)
            return self.hit

        self.collision = self.entries[0]
        nP = self.collision.get_into_node_path().parent
        point = self.collision.get_surface_point(nP)
        point = Vec3(point[0], point[2], point[1])
        world_point = self.collision.get_surface_point(render)
        world_point = Vec3(world_point[0], world_point[2], world_point[1])
        hit_dist = self.distance(self.world_position, world_point)

        if nP.name.endswith('.egg'):
            nP = nP.parent

        self.hit = Hit(hit=True)
        for e in scene.entities:
            if e == nP:
                # print('cast nP to Entity')
                self.hit.entity = e

        self.hit.point = point
        self.hit.world_point = world_point
        self.hit.distance = hit_dist

        normal = self.collision.get_surface_normal(
            self.collision.get_into_node_path().parent)
        self.hit.normal = (normal[0], normal[2], normal[1])

        normal = self.collision.get_surface_normal(render)
        self.hit.world_normal = (normal[0], normal[2], normal[1])
        return self.hit

        self.hit = Hit(hit=False)
        return self.hit
コード例 #39
0
    def setup(self,task):
        lens = OrthographicLens()
        lens.setFilmSize(23,19)
        base.camNode.setLens(lens)
        
        self.player = self.scene.attachNewNode("Player")
        
        self.marioGfx = self.scene.find('root/mario')
        self.marioGfx.reparentTo(self.player)
        self.marioGfx.setTwoSided(True)
        
        self.lifes = [
        self.scene.attachNewNode("life1"),
        self.scene.attachNewNode("life2"),
        self.scene.attachNewNode("life3")
        ]
        self.marioGfx.instanceTo(self.lifes[0])
        self.marioGfx.instanceTo(self.lifes[1])
        self.marioGfx.instanceTo(self.lifes[2])
        
        self.lifes[0].setPos(-9,0,7.5)
        self.lifes[1].setPos(-10,0,7.5)
        self.lifes[2].setPos(-11,0,7.5)

        
        self.hammerTime = False
        
        self.hammerDown = self.scene.find('root/hammerdowm')
        self.hammerDown.reparentTo(self.marioGfx)
        self.hammerDown.setPos(1,0,0)
        
        self.hammerUp = self.scene.find('root/hammerup')
        self.hammerUp.reparentTo(self.marioGfx)
        self.hammerUp.setPos(0,0,1)
        
        frame1 = Func(self.hammerFrame1)
        frame2 = Func(self.hammerFrame2)
        delay = Wait(0.1)
        self.hammerSequence = Sequence(frame1, delay, frame2, delay)
        # self.hammerSequence.loop()
        
        self.hammerUp.hide()
        self.hammerDown.hide()
        
        self.scene.find('root/walls').hide()
        self.scene.find('root/rightWall').hide()
        self.scene.find('root/barrel').setPos(0,100,0)
        
        self.jumpAvailable = False
        self.gravity = -.5
        self.verticalTime = 0
        self.v0 = 0
        self.floorZ = 0
        self.onStairs = False
        self.jumpCounter = 1
        # input setup 
        
        self.input = {
        'up':False,
        'down': False,
        'left': False , 
        'right': False,
        'space': False
        }
        
        key_list = ['up','down','left','right']
        for k in key_list:
            self.accept(f'raw-arrow_{k}' , self.buildPress(k) )
            self.accept(f'raw-arrow_{k}-up', self.buildRelease(k) )
        
        self.accept(f'raw-space' , self.buildPress('space') )
        self.accept(f'raw-space-up', self.buildRelease('space') )
        
        
        # collision set up
        base.cTrav = CollisionTraverser()
        self.collisionHandlerEvent = CollisionHandlerEvent()
        self.collisionHandlerEvent.addInPattern('into-%in')
        self.collisionHandlerEvent.addOutPattern('outof-%in')

        ray = CollisionSegment(0,0,0,0,0,-.6)
        cNodePath = self.player.attachNewNode( CollisionNode('marioRay') )
        cNodePath.node().addSolid(ray)
        cNodePath.node().setIntoCollideMask(0x03)
        cNodePath.node().setFromCollideMask(0x03)
        #cNodePath.show()
        base.cTrav.addCollider(cNodePath, self.collisionHandlerEvent)

        self.donkeykong = self.scene.find('root/donkeykong')
        self.donkeykonghit = self.createSquareCollider(8.7,5,1,1,'donkeykong','dkhitbox', 'DK' , self.reachedDK, self.exitDK , self.arcadeTexture, 0x02)
        self.createDkSequence()
        self.dk_sequence.start()
        
        self.floor1 = self.createSquareCollider(-1.8, -5.5 , 9.3, .5, 'floor0' , 'floor1HitBox', 'Floor1', self.enableJump, self.disableJump , self.blocksTexture, 0x1)
        self.floor2 = self.createSquareCollider(2.08, -2.5 , 8.0, .5, 'floor1' , 'floor2HitBox', 'Floor2', self.enableJump, self.disableJump , self.blocksTexture, 0x1)
        self.floor3_1 = self.createSquareCollider(3.6, 0.5 , 3.8, .5, 'floor2' , 'floor3_1HitBox', 'Floor3_1', self.enableJump, self.disableJump , self.blocksTexture, 0x1)
        self.floor3_2 = self.createSquareCollider(-6.3, 0.5 , 5, .5, 'pCube4' , 'floor3_2HitBox', 'Floor3_2', self.enableJump, self.disableJump , self.blocksTexture, 0x1)
        self.floor4 = self.createSquareCollider(1.8, 3.5 , 8.0, .5, 'floors' , 'floor4HitBox', 'Floor4', self.enableJump, self.disableJump , self.blocksTexture, 0x1)
        
        self.hammer = self.createSquareCollider(6,1.5,0.5,0.5,'hammer', 'hammerHitBox', 'hammer', self.enableHammer, self.disableHammer, self.arcadeTexture, 0x02) 
        self.topStair = self.createSquareCollider(-6.8, 3.5 , 0.5, 2.5, 'topstair' , 'topStairHitBox', 'TopStair', self.enableStairs, self.disableStairs , self.stairsTexture, 0x2)
        self.middleStair= self.createSquareCollider(-0.86, 0.1 , 0.5, 2.5, 'middlestair' , 'middleStairHitBox', 'MiddleStair', self.enableStairs, self.disableStairs , self.stairsTexture, 0x2)
        self.bottomStair = self.createSquareCollider(-6.8, -2.5 , 0.5, 2.5, 'bottomstair' , 'bottomStairHitBox', 'BottomStair', self.enableStairs, self.disableStairs , self.stairsTexture, 0x2)
        
        self.leftWall = self.createInvisibleSquareCollider(-12.5, 0, 1, 10 , 'leftWallHitBox','leftWall',0x1)
        self.rightWall = self.createInvisibleSquareCollider(11.3, 0, 1, 20 , 'rightWallHitBox','rightWall',0x1)
        
        self.barrelDestroyer = self.createInvisibleSquareCollider(-.5,-10,10.5,1, 'barrelDestroyerHitBox' , 'barrelDestroyer'  ,0x1) 
        self.barrelBridge = self.createInvisibleSquareCollider(-0.4,0.5,2,0.5, 'barrelBridgeHitBox' , 'barrelBridge'  ,0x4)
        self.accept('into-barrelCollider', self.barrelCrash)
        base.enableParticles()
        
        self.physicsCollisionPusher = PhysicsCollisionHandler()
        gravity = ForceNode('world-forces')
        gravityP = render.attachNewNode(gravity)
        gravityForce = LinearVectorForce(0,0,-9.81)
        gravity.addForce(gravityForce)
        base.physicsMgr.addLinearForce(gravityForce)
        
        
        #self.createInvisibleSquareCollider(0,0,8,3,"NewCollision","NewNode")
        #self.createInvisibleSquareCollider(-6,0,4,5,"NewCollisio2","NewNode2")
        #base.cTrav.showCollisions(self.render)
        
        # self.accept('raw-a', self.throwBarrel)
        # self.player.setPos(3,0,-3.5)
        self.player.setPos(-8,0,-1.5)
        return Task.done
コード例 #40
0
    def setup(self, task):
        lens = OrthographicLens()
        lens.setFilmSize(25, 20)
        base.camNode.setLens(lens)

        self.player = self.scene.attachNewNode("Player")

        self.marioGfx = self.scene.find('root/mario')
        self.marioGfx.reparentTo(self.player)

        self.jumpAvailable = False
        self.gravity = -.5
        self.verticalTime = 0
        self.v0 = 0
        self.floorZ = 0
        self.onStairs = False
        self.jumpCounter = 1
        # input setup

        self.input = {
            'up': False,
            'down': False,
            'left': False,
            'right': False,
            'space': False
        }

        key_list = ['up', 'down', 'left', 'right']
        for k in key_list:
            self.accept(f'raw-arrow_{k}', self.buildPress(k))
            self.accept(f'raw-arrow_{k}-up', self.buildRelease(k))

        self.accept(f'raw-space', self.buildPress('space'))
        self.accept(f'raw-space-up', self.buildRelease('space'))

        # collision set up
        base.cTrav = CollisionTraverser()
        self.collisionHandlerEvent = CollisionHandlerEvent()
        self.collisionHandlerEvent.addInPattern('into-%in')
        self.collisionHandlerEvent.addOutPattern('outof-%in')

        ray = CollisionSegment(0, 0, 0, 0, 0, -.6)
        cNodePath = self.player.attachNewNode(CollisionNode('marioRay'))
        cNodePath.node().addSolid(ray)
        cNodePath.node().setIntoCollideMask(0x03)
        cNodePath.node().setFromCollideMask(0x03)
        cNodePath.show()
        base.cTrav.addCollider(cNodePath, self.collisionHandlerEvent)

        self.floor1 = self.createSquareCollider(-1.8, -5.5, 9.3, .5, 'floor0',
                                                'floor1HitBox', 'Floor1',
                                                self.enableJump,
                                                self.disableJump,
                                                self.blocksTexture, 0x1)
        self.floor2 = self.createSquareCollider(2.08, -2.5, 8.0, .5, 'floor1',
                                                'floor2HitBox', 'Floor2',
                                                self.enableJump,
                                                self.disableJump,
                                                self.blocksTexture, 0x1)
        self.floor3_1 = self.createSquareCollider(3.6, 0.5, 3.8, .5, 'floor2',
                                                  'floor3_1HitBox', 'Floor3_1',
                                                  self.enableJump,
                                                  self.disableJump,
                                                  self.blocksTexture, 0x1)
        self.floor3_2 = self.createSquareCollider(-6.3, 0.5, 5, .5, 'pCube4',
                                                  'floor3_2HitBox', 'Floor3_2',
                                                  self.enableJump,
                                                  self.disableJump,
                                                  self.blocksTexture, 0x1)
        self.floor4 = self.createSquareCollider(1.8, 3.5, 8.0, .5, 'floors',
                                                'floor4HitBox', 'Floor4',
                                                self.enableJump,
                                                self.disableJump,
                                                self.blocksTexture, 0x1)

        self.topStair = self.createSquareCollider(
            -6.8, 3.5, 0.5, 2.5, 'topstair', 'topStairHitBox', 'TopStair',
            self.enableStairs, self.disableStairs, self.stairsTexture, 0x2)
        self.middleStair = self.createSquareCollider(
            -0.86, 0.1, 0.5, 2.5, 'middlestair', 'middleStairHitBox',
            'MiddleStair', self.enableStairs, self.disableStairs,
            self.stairsTexture, 0x2)
        self.bottomStair = self.createSquareCollider(
            -6.8, -2.5, 0.5, 2.5, 'bottomstair', 'bottomStairHitBox',
            'BottomStair', self.enableStairs, self.disableStairs,
            self.stairsTexture, 0x2)

        #self.createInvisibleSquareCollider(0,0,8,3,"NewCollision","NewNode")
        #self.createInvisibleSquareCollider(-6,0,4,5,"NewCollisio2","NewNode2")
        base.cTrav.showCollisions(self.render)

        # self.player.setPos(3,0,-3.5)
        self.player.setPos(-8, 0, -1.5)
        return Task.done
コード例 #41
0
class Physics:
    def __init__(self):
        self.rayCTrav = CollisionTraverser("collision traverser for ray tests")
        #self.pusher = PhysicsCollisionHandler()
        self.pusher = CollisionHandlerPusher()
        self.pusher.addInPattern('%fn-in-%in')
        self.pusher.addOutPattern('%fn-out-%in')
        self.pusher.addInPattern('%fn-in')
        self.pusher.addOutPattern('%fn-out')

    def startPhysics(self):
        #self.actorNode = ActorNode("playerPhysicsControler")
        #base.physicsMgr.attachPhysicalNode(self.actorNode)
        #self.actorNode.getPhysicsObject().setMass(self.player_mass)
        #self.mainNode = render.attachNewNode(self.actorNode)
        self.mainNode = render.attachNewNode("CharacterColliders")
        self.reparentTo(self.mainNode)

        charCollisions = self.mainNode.attachNewNode(
            CollisionNode(self.char_collision_name))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0, self.player_height/4.0))
        #charCollisions.node().addSolid(CollisionSphere(0, 0, self.player_height/4.0*3.05, self.player_height/4.0))
        charCollisions.node().addSolid(
            CollisionSphere(0, 0, self.player_height / 2.0,
                            self.player_height / 4.0))
        charCollisions.node().setIntoCollideMask(BitMask32(0x80))  # 1000 0000
        if self.show_collisions:
            charCollisions.show()
        self.pusher.addCollider(charCollisions, self.mainNode)
        base.cTrav.addCollider(charCollisions, self.pusher)

        charFFootCollisions = self.attachNewNode(CollisionNode("floor_ray"))
        charFFootCollisions.node().addSolid(CollisionRay(0, 0, 0.5, 0, 0, -1))
        #charFFootCollisions.node().addSolid(CollisionSegment((0, 0, 0.2), (0, 0, -1)))
        charFFootCollisions.node().setIntoCollideMask(BitMask32.allOff())
        charFFootCollisions.node().setFromCollideMask(
            BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            charFFootCollisions.show()

        self.floor_handler = CollisionHandlerFloor()
        self.floor_handler.addCollider(charFFootCollisions, self.mainNode)
        #self.floor_handler.setOffset(0)
        self.floor_handler.setMaxVelocity(5)
        base.cTrav.addCollider(charFFootCollisions, self.floor_handler)

        self.accept("{}-in".format(self.char_collision_name),
                    self.checkCharCollisions)

        self.raytest_segment = CollisionSegment(0, 1)
        self.raytest_np = render.attachNewNode(CollisionNode("testRay"))
        self.raytest_np.node().addSolid(self.raytest_segment)
        self.raytest_np.node().setIntoCollideMask(BitMask32.allOff())
        self.raytest_np.node().setFromCollideMask(BitMask32(0x7f))  # 0111 1111
        if self.show_collisions:
            self.raytest_np.show()

        self.raytest_queue = CollisionHandlerQueue()
        self.rayCTrav.addCollider(self.raytest_np, self.raytest_queue)

    def stopPhysics(self):
        self.raytest_segment.removeNode()
        self.pusher.clearColliders()
        self.floor_handler.clearColliders()
        self.rayCTrav.clearColliders()

    def updatePlayerPos(self, speed, heading, dt):
        if heading is not None:
            self.mainNode.setH(camera, heading)
            self.mainNode.setP(0)
            self.mainNode.setR(0)
        self.mainNode.setFluidPos(self.mainNode, speed)
        self.doStep()

    def checkCharCollisions(self, args):
        self.doStep()

    def doStep(self):
        # do the step height check
        tmpNP = self.mainNode.attachNewNode("temporary")
        tmpNP.setPos(self.mainNode, 0, 0, -self.stepheight)
        pointA = self.mainNode.getPos(render)
        pointA.setZ(pointA.getZ() + self.player_height / 1.8)
        pointB = tmpNP.getPos(render)
        if pointA == pointB: return
        char_step_collision = self.getFirstCollisionInLine(pointA, pointB)
        tmpNP.removeNode()
        if char_step_collision is not None:
            self.mainNode.setFluidZ(char_step_collision.getZ())
            return True
        return False

    def getFirstCollisionInLine(self, pointA, pointB):
        """A simple raycast check which will return the first collision point as
        seen from point A towards pointB"""
        self.raytest_segment.setPointA(pointA)
        self.raytest_segment.setPointB(pointB)
        self.rayCTrav.traverse(render)
        self.raytest_queue.sortEntries()
        pos = None
        if self.raytest_queue.getNumEntries() > 0:
            pos = self.raytest_queue.getEntry(0).getSurfacePoint(render)
        return pos
コード例 #42
0
class SmartCamera:
    UPDATE_TASK_NAME = 'update_smartcamera'
    notify = directNotify.newCategory('SmartCamera')

    def __init__(self):
        self.cTrav = CollisionTraverser('cam_traverser')
        base.pushCTrav(self.cTrav)
        self.cTrav.setRespectPrevTransform(1)
        self.default_pos = None
        self.parent = None
        self.initialized = False
        self.started = False
        self.camFloorRayNode = None
        self.ccRay2 = None
        self.ccRay2Node = None
        self.ccRay2NodePath = None
        self.ccRay2BitMask = None
        self.ccRay2MoveNodePath = None
        self.camFloorCollisionBroadcaster = None
        self.notify.debug('SmartCamera initialized!')
        return

    def lerpCameraFov(self, fov, time):
        taskMgr.remove('cam-fov-lerp-play')
        oldFov = base.camLens.getHfov()
        if abs(fov - oldFov) > 0.1:

            def setCamFov(fov):
                base.camLens.setMinFov(fov / (4.0 / 3.0))

            self.camLerpInterval = LerpFunctionInterval(setCamFov, fromData=oldFov, toData=fov, duration=time, name='cam-fov-lerp')
            self.camLerpInterval.start()

    def setCameraFov(self, fov):
        self.fov = fov
        if not (self.isPageDown or self.isPageUp):
            base.camLens.setMinFov(self.fov / (4.0 / 3.0))

    def initCameraPositions(self):
        camHeight = max(base.localAvatar.getHeight(), 3.0)
        nrCamHeight = base.localAvatar.getHeight()
        heightScaleFactor = camHeight * 0.3333333333
        defLookAt = Point3(0.0, 1.5, camHeight)
        self.firstPersonCamPos = Point3(0.0, 0.7, nrCamHeight * 5.0)
        scXoffset = 3.0
        scPosition = (Point3(scXoffset - 1, -10.0, camHeight + 5.0), Point3(scXoffset, 2.0, camHeight))
        self.cameraPositions = [
         (Point3(0.0, -9.0 * heightScaleFactor, camHeight),
          defLookAt,
          Point3(0.0, camHeight, camHeight * 4.0),
          Point3(0.0, camHeight, camHeight * -1.0),
          0),
         (
          Point3(0.0, 0.7, camHeight),
          defLookAt,
          Point3(0.0, camHeight, camHeight * 1.33),
          Point3(0.0, camHeight, camHeight * 0.66),
          1),
         (
          Point3(5.7 * heightScaleFactor, 7.65 * heightScaleFactor, camHeight + 2.0),
          Point3(0.0, 1.0, camHeight),
          Point3(0.0, 1.0, camHeight * 4.0),
          Point3(0.0, 1.0, camHeight * -1.0),
          0),
         (
          Point3(0.0, 8.65 * heightScaleFactor, camHeight),
          Point3(0.0, 1.0, camHeight),
          Point3(0.0, 1.0, camHeight * 4.0),
          Point3(0.0, 1.0, camHeight * -1.0),
          0),
         (
          Point3(0.0, -24.0 * heightScaleFactor, camHeight + 4.0),
          defLookAt,
          Point3(0.0, 1.5, camHeight * 4.0),
          Point3(0.0, 1.5, camHeight * -1.0),
          0),
         (
          Point3(0.0, -12.0 * heightScaleFactor, camHeight + 4.0),
          defLookAt,
          Point3(0.0, 1.5, camHeight * 4.0),
          Point3(0.0, 1.5, camHeight * -1.0),
          0)]

    def pageUp(self):
        if not base.localAvatar.avatarMovementEnabled:
            return
        if not self.isPageUp:
            self.isPageDown = 0
            self.isPageUp = 1
            self.lerpCameraFov(70, 0.6)
            self.setCameraPositionByIndex(self.cameraIndex)
        else:
            self.clearPageUpDown()

    def pageDown(self):
        if not base.localAvatar.avatarMovementEnabled:
            return
        if not self.isPageDown:
            self.isPageUp = 0
            self.isPageDown = 1
            self.lerpCameraFov(70, 0.6)
            self.setCameraPositionByIndex(self.cameraIndex)
        else:
            self.clearPageUpDown()

    def clearPageUpDown(self):
        if self.isPageDown or self.isPageUp:
            self.lerpCameraFov(self.fov, 0.6)
            self.isPageDown = 0
            self.isPageUp = 0
            self.setCameraPositionByIndex(self.cameraIndex)

    def nextCameraPos(self, forward):
        if not base.localAvatar.avatarMovementEnabled:
            return
        self.__cameraHasBeenMoved = 1
        if forward:
            self.cameraIndex += 1
            if self.cameraIndex > len(self.cameraPositions) - 1:
                self.cameraIndex = 0
        else:
            self.cameraIndex -= 1
            if self.cameraIndex < 0:
                self.cameraIndex = len(self.cameraPositions) - 1
        self.setCameraPositionByIndex(self.cameraIndex)

    def setCameraPositionByIndex(self, index):
        self.notify.debug('switching to camera position %s' % index)
        self.setCameraSettings(self.cameraPositions[index])

    def setCameraSettings(self, camSettings):
        self.setIdealCameraPos(camSettings[0])
        if self.isPageUp and self.isPageDown or not self.isPageUp and not self.isPageDown:
            self.__cameraHasBeenMoved = 1
            self.setLookAtPoint(camSettings[1])
        else:
            if self.isPageUp:
                self.__cameraHasBeenMoved = 1
                self.setLookAtPoint(camSettings[2])
            else:
                if self.isPageDown:
                    self.__cameraHasBeenMoved = 1
                    self.setLookAtPoint(camSettings[3])
                else:
                    self.notify.error('This case should be impossible.')
        self.__disableSmartCam = camSettings[4]
        if self.__disableSmartCam:
            self.putCameraFloorRayOnAvatar()
            self.cameraZOffset = 0.0

    def set_default_pos(self, pos):
        self.default_pos = pos

    def get_default_pos(self):
        return self.default_pos

    def set_parent(self, parent):
        self.parent = parent

    def get_parent(self):
        return self.parent

    def getVisibilityPoint(self):
        return Point3(0.0, 0.0, base.localAvatar.getHeight())

    def setLookAtPoint(self, la):
        self.__curLookAt = Point3(la)

    def getLookAtPoint(self):
        return Point3(self.__curLookAt)

    def setIdealCameraPos(self, pos):
        self.__idealCameraPos = Point3(pos)
        self.updateSmartCameraCollisionLineSegment()

    def getIdealCameraPos(self):
        return Point3(self.__idealCameraPos)

    def getCompromiseCameraPos(self):
        if self.__idealCameraObstructed == 0:
            compromisePos = self.getIdealCameraPos()
        else:
            visPnt = self.getVisibilityPoint()
            idealPos = self.getIdealCameraPos()
            distance = Vec3(idealPos - visPnt).length()
            ratio = self.closestObstructionDistance / distance
            compromisePos = idealPos * ratio + visPnt * (1 - ratio)
            liftMult = 1.0 - ratio * ratio
            compromisePos = Point3(compromisePos[0], compromisePos[1], compromisePos[2] + base.localAvatar.getHeight() * 0.4 * liftMult)
        compromisePos.setZ(compromisePos[2] + self.cameraZOffset)
        return compromisePos

    def updateSmartCameraCollisionLineSegment(self):
        pointB = self.getIdealCameraPos()
        pointA = self.getVisibilityPoint()
        vectorAB = Vec3(pointB - pointA)
        lengthAB = vectorAB.length()
        if lengthAB > 0.001:
            self.ccLine.setPointA(pointA)
            self.ccLine.setPointB(pointB)

    def initializeSmartCamera(self):
        self.__idealCameraObstructed = 0
        self.closestObstructionDistance = 0.0
        self.cameraIndex = 0
        self.cameraPositions = []
        self.auxCameraPositions = []
        self.cameraZOffset = 0.0
        self.setGeom(render)
        self.__onLevelGround = 0
        self.__camCollCanMove = 0
        self.__disableSmartCam = 0
        self.initializeSmartCameraCollisions()
        self._smartCamEnabled = False
        self.isPageUp = 0
        self.isPageDown = 0
        self.fov = CIGlobals.DefaultCameraFov

    def enterFirstPerson(self):
        self.stop_smartcamera()
        if hasattr(self.get_parent(), 'toon_head'):
            head = self.get_parent().toon_head
            camera.reparentTo(head)
        camera.setPos(0, -0.35, 0)
        camera.setHpr(0, 0, 0)

    def exitFirstPerson(self):
        self.initialize_smartcamera()
        self.initialize_smartcamera_collisions()
        self.start_smartcamera()

    def putCameraFloorRayOnAvatar(self):
        self.camFloorRayNode.setPos(base.localAvatar, 0, 0, 5)

    def putCameraFloorRayOnCamera(self):
        self.camFloorRayNode.setPos(self.ccSphereNodePath, 0, 0, 0)

    def recalcCameraSphere(self):
        nearPlaneDist = base.camLens.getNear()
        hFov = base.camLens.getHfov()
        vFov = base.camLens.getVfov()
        hOff = nearPlaneDist * math.tan(deg2Rad(hFov / 2.0))
        vOff = nearPlaneDist * math.tan(deg2Rad(vFov / 2.0))
        camPnts = [Point3(hOff, nearPlaneDist, vOff),
         Point3(-hOff, nearPlaneDist, vOff),
         Point3(hOff, nearPlaneDist, -vOff),
         Point3(-hOff, nearPlaneDist, -vOff),
         Point3(0.0, 0.0, 0.0)]
        avgPnt = Point3(0.0, 0.0, 0.0)
        for camPnt in camPnts:
            avgPnt = avgPnt + camPnt

        avgPnt = avgPnt / len(camPnts)
        sphereRadius = 0.0
        for camPnt in camPnts:
            dist = Vec3(camPnt - avgPnt).length()
            if dist > sphereRadius:
                sphereRadius = dist

        avgPnt = Point3(avgPnt)
        self.ccSphereNodePath.setPos(avgPnt)
        self.ccSphereNodePath2.setPos(avgPnt)
        self.ccSphere.setRadius(sphereRadius)

    def setGeom(self, geom):
        self.__geom = geom

    def initializeSmartCameraCollisions(self):
        if self.initialized:
            return
        self.ccTrav = CollisionTraverser('LocalAvatar.ccTrav')
        self.ccLine = CollisionSegment(0.0, 0.0, 0.0, 1.0, 0.0, 0.0)
        self.ccLineNode = CollisionNode('ccLineNode')
        self.ccLineNode.addSolid(self.ccLine)
        self.ccLineNodePath = base.localAvatar.attachNewNode(self.ccLineNode)
        self.ccLineBitMask = CIGlobals.CameraBitmask
        self.ccLineNode.setFromCollideMask(self.ccLineBitMask)
        self.ccLineNode.setIntoCollideMask(BitMask32.allOff())
        self.camCollisionQueue = CollisionHandlerQueue()
        self.ccTrav.addCollider(self.ccLineNodePath, self.camCollisionQueue)
        self.ccSphere = CollisionSphere(0, 0, 0, 1)
        self.ccSphereNode = CollisionNode('ccSphereNode')
        self.ccSphereNode.addSolid(self.ccSphere)
        self.ccSphereNodePath = base.camera.attachNewNode(self.ccSphereNode)
        self.ccSphereNode.setFromCollideMask(CIGlobals.CameraBitmask)
        self.ccSphereNode.setIntoCollideMask(BitMask32.allOff())
        self.camPusher = CollisionHandlerPusher()
        self.camPusher.addCollider(self.ccSphereNodePath, base.camera)
        self.camPusher.setCenter(base.localAvatar)
        self.ccPusherTrav = CollisionTraverser('LocalAvatar.ccPusherTrav')
        self.ccSphere2 = self.ccSphere
        self.ccSphereNode2 = CollisionNode('ccSphereNode2')
        self.ccSphereNode2.addSolid(self.ccSphere2)
        self.ccSphereNodePath2 = base.camera.attachNewNode(self.ccSphereNode2)
        self.ccSphereNode2.setFromCollideMask(CIGlobals.CameraBitmask)
        self.ccSphereNode2.setIntoCollideMask(BitMask32.allOff())
        self.camPusher2 = CollisionHandlerPusher()
        self.ccPusherTrav.addCollider(self.ccSphereNodePath2, self.camPusher2)
        self.camPusher2.addCollider(self.ccSphereNodePath2, base.camera)
        self.camPusher2.setCenter(base.localAvatar)
        self.camFloorRayNode = base.localAvatar.attachNewNode('camFloorRayNode')
        self.ccRay = CollisionRay(0.0, 0.0, 0.0, 0.0, 0.0, -1.0)
        self.ccRayNode = CollisionNode('ccRayNode')
        self.ccRayNode.addSolid(self.ccRay)
        self.ccRayNodePath = self.camFloorRayNode.attachNewNode(self.ccRayNode)
        self.ccRayBitMask = CIGlobals.FloorBitmask
        self.ccRayNode.setFromCollideMask(self.ccRayBitMask)
        self.ccRayNode.setIntoCollideMask(BitMask32.allOff())
        self.ccTravFloor = CollisionTraverser('LocalAvatar.ccTravFloor')
        self.camFloorCollisionQueue = CollisionHandlerQueue()
        self.ccTravFloor.addCollider(self.ccRayNodePath, self.camFloorCollisionQueue)
        self.ccTravOnFloor = CollisionTraverser('LocalAvatar.ccTravOnFloor')
        self.ccRay2 = CollisionRay(0.0, 0.0, 0.0, 0.0, 0.0, -1.0)
        self.ccRay2Node = CollisionNode('ccRay2Node')
        self.ccRay2Node.addSolid(self.ccRay2)
        self.ccRay2NodePath = self.camFloorRayNode.attachNewNode(self.ccRay2Node)
        self.ccRay2BitMask = CIGlobals.FloorBitmask
        self.ccRay2Node.setFromCollideMask(self.ccRay2BitMask)
        self.ccRay2Node.setIntoCollideMask(BitMask32.allOff())
        self.ccRay2MoveNodePath = hidden.attachNewNode('ccRay2MoveNode')
        self.camFloorCollisionBroadcaster = CollisionHandlerFloor()
        self.camFloorCollisionBroadcaster.setInPattern('on-floor')
        self.camFloorCollisionBroadcaster.setOutPattern('off-floor')
        self.camFloorCollisionBroadcaster.addCollider(self.ccRay2NodePath, self.ccRay2MoveNodePath)
        self.cTrav.addCollider(self.ccRay2NodePath, self.camFloorCollisionBroadcaster)
        self.initialized = True

    def deleteSmartCameraCollisions(self):
        del self.ccTrav
        del self.ccLine
        del self.ccLineNode
        self.ccLineNodePath.removeNode()
        del self.ccLineNodePath
        del self.camCollisionQueue
        del self.ccRay
        del self.ccRayNode
        self.ccRayNodePath.removeNode()
        del self.ccRayNodePath
        del self.ccRay2
        del self.ccRay2Node
        self.ccRay2NodePath.removeNode()
        del self.ccRay2NodePath
        self.ccRay2MoveNodePath.removeNode()
        del self.ccRay2MoveNodePath
        del self.ccTravOnFloor
        del self.ccTravFloor
        del self.camFloorCollisionQueue
        del self.camFloorCollisionBroadcaster
        del self.ccSphere
        del self.ccSphereNode
        self.ccSphereNodePath.removeNode()
        del self.ccSphereNodePath
        del self.camPusher
        del self.ccPusherTrav
        del self.ccSphere2
        del self.ccSphereNode2
        self.ccSphereNodePath2.removeNode()
        del self.ccSphereNodePath2
        del self.camPusher2
        self.initialized = False

    def startUpdateSmartCamera(self):
        if self.started:
            return
        self.__floorDetected = 0
        self.__cameraHasBeenMoved = 1
        self.recalcCameraSphere()
        self.__instantaneousCamPos = camera.getPos()
        self.cTrav.addCollider(self.ccSphereNodePath, self.camPusher)
        self.ccTravOnFloor.addCollider(self.ccRay2NodePath, self.camFloorCollisionBroadcaster)
        self.__disableSmartCam = 0
        self.__lastPosWrtRender = camera.getPos(render) + 1
        self.__lastHprWrtRender = camera.getHpr(render) + 1
        taskName = base.localAvatar.taskName('updateSmartCamera')
        taskMgr.remove(taskName)
        taskMgr.add(self.updateSmartCamera, taskName, priority=47)
        self.started = True

    def stopUpdateSmartCamera(self):
        self.cTrav.removeCollider(self.ccSphereNodePath)
        self.ccTravOnFloor.removeCollider(self.ccRay2NodePath)
        taskName = base.localAvatar.taskName('updateSmartCamera')
        taskMgr.remove(taskName)
        camera.setPos(self.getIdealCameraPos())
        self.started = False

    def updateSmartCamera(self, task):
        if not self.__camCollCanMove and not self.__cameraHasBeenMoved:
            if self.__lastPosWrtRender == camera.getPos(render):
                if self.__lastHprWrtRender == camera.getHpr(render):
                    return Task.cont
        self.__cameraHasBeenMoved = 0
        self.__lastPosWrtRender = camera.getPos(render)
        self.__lastHprWrtRender = camera.getHpr(render)
        self.__idealCameraObstructed = 0
        if not self.__disableSmartCam:
            self.ccTrav.traverse(self.__geom)
            if self.camCollisionQueue.getNumEntries() > 0:
                try:
                    self.camCollisionQueue.sortEntries()
                    self.handleCameraObstruction(self.camCollisionQueue.getEntry(0))
                except AssertionError:
                    pass

            if not self.__onLevelGround:
                self.handleCameraFloorInteraction()
        if not self.__idealCameraObstructed:
            self.nudgeCamera()
        if not self.__disableSmartCam:
            self.ccPusherTrav.traverse(self.__geom)
            self.putCameraFloorRayOnCamera()
        self.ccTravOnFloor.traverse(self.__geom)
        return Task.cont

    def positionCameraWithPusher(self, pos, lookAt):
        camera.setPos(pos)
        self.ccPusherTrav.traverse(self.__geom)
        camera.lookAt(lookAt)

    def nudgeCamera(self):
        CLOSE_ENOUGH = 0.1
        curCamPos = self.__instantaneousCamPos
        curCamHpr = camera.getHpr()
        targetCamPos = self.getCompromiseCameraPos()
        targetCamLookAt = self.getLookAtPoint()
        posDone = 0
        if Vec3(curCamPos - targetCamPos).length() <= CLOSE_ENOUGH:
            camera.setPos(targetCamPos)
            posDone = 1
        camera.setPos(targetCamPos)
        camera.lookAt(targetCamLookAt)
        targetCamHpr = camera.getHpr()
        hprDone = 0
        if Vec3(curCamHpr - targetCamHpr).length() <= CLOSE_ENOUGH:
            hprDone = 1
        if posDone and hprDone:
            return
        lerpRatio = 0.15
        lerpRatio = 1 - pow(1 - lerpRatio, globalClock.getDt() * 30.0)
        self.__instantaneousCamPos = targetCamPos * lerpRatio + curCamPos * (1 - lerpRatio)
        if self.__disableSmartCam or not self.__idealCameraObstructed:
            newHpr = targetCamHpr * lerpRatio + curCamHpr * (1 - lerpRatio)
        else:
            newHpr = targetCamHpr
        camera.setPos(self.__instantaneousCamPos)
        camera.setHpr(newHpr)

    def popCameraToDest(self):
        newCamPos = self.getCompromiseCameraPos()
        newCamLookAt = self.getLookAtPoint()
        self.positionCameraWithPusher(newCamPos, newCamLookAt)
        self.__instantaneousCamPos = camera.getPos()

    def handleCameraObstruction(self, camObstrCollisionEntry):
        collisionPoint = camObstrCollisionEntry.getSurfacePoint(self.ccLineNodePath)
        collisionVec = Vec3(collisionPoint - self.ccLine.getPointA())
        distance = collisionVec.length()
        self.__idealCameraObstructed = 1
        self.closestObstructionDistance = distance
        self.popCameraToDest()

    def handleCameraFloorInteraction(self):
        self.putCameraFloorRayOnCamera()
        self.ccTravFloor.traverse(self.__geom)
        if self.__onLevelGround:
            return
        if self.camFloorCollisionQueue.getNumEntries() == 0:
            return
        self.camFloorCollisionQueue.sortEntries()
        camObstrCollisionEntry = self.camFloorCollisionQueue.getEntry(0)
        camHeightFromFloor = camObstrCollisionEntry.getSurfacePoint(self.ccRayNodePath)[2]
        self.cameraZOffset = camera.getPos()[2] + camHeightFromFloor
        if self.cameraZOffset < 0:
            self.cameraZOffset = 0
        if self.__floorDetected == 0:
            self.__floorDetected = 1
            self.popCameraToDest()
コード例 #43
0
    def __init__(self):
        GameObject.__init__(self, Vec3(0, 0, 0), None, None, 100, 15, "player",
                            1, MASK_INTO_PLAYER)
        Walker.__init__(self)
        ArmedObject.__init__(self)

        self.weaponNP = self.actor

        light = PointLight("basic light")
        light.setColor(Vec4(1, 1, 1, 1))
        light.setAttenuation((1, 0.01, 0.005))
        self.lightNP = self.root.attachNewNode(light)
        self.lightNP.setZ(1)
        render.setLight(self.lightNP)

        self.collider.node().setFromCollideMask(MASK_WALLS | MASK_FROM_PLAYER)

        self.actor.setZ(self.height)

        base.camera.reparentTo(self.actor)
        base.camera.setPos(0, 0, 0)
        base.camera.setHpr(0, 0, 0)

        lens = base.camLens
        ratio = lens.getAspectRatio()

        lens.setFov(80 * ratio)
        lens.setNear(0.03)

        self.lastMousePos = Vec2(0, 0)
        self.mouseSpeedHori = 50.0
        self.mouseSpeedVert = 30.0
        self.mouseSensitivity = 1.0

        self.healthLeft = -0.9
        self.healthRight = 0.9
        self.healthWidth = self.healthRight - self.healthLeft

        self.uiRoot = base.a2dBottomCenter.attachNewNode(
            PandaNode("player UI"))

        self.healthBar = loader.loadModel("UI/healthBar")
        self.healthBar.reparentTo(self.uiRoot)
        self.healthBar.setZ(0.05)
        self.healthBar.setX(self.healthLeft)
        self.healthBar.getChild(0).setScale(self.healthWidth / 6.0)

        self.weaponUIRoot = self.uiRoot.attachNewNode(
            PandaNode("player weapon UI"))
        self.weaponUIRoot.setPos(0, 0, 0.1)

        self.addWeapon(RapidShotgunWeapon(self.weaponUIRoot))
        self.addWeapon(BlasterWeapon(self.weaponUIRoot))

        self.weapons[0].setAvailable(True)

        self.setCurrentWeapon(0)

        self.updateHealthUI()

        self.inventory = []

        self.updatingEffects = []

        self.interactionSegment = CollisionSegment(0, 0, 0, 0, 1.5, 0)

        rayNode = CollisionNode("player interaction ray")
        rayNode.addSolid(self.interactionSegment)

        rayNode.setFromCollideMask(MASK_WALLS | MASK_FLOORS | MASK_INTO_ENEMY)
        rayNode.setIntoCollideMask(0)

        self.interactionSegmentNodePath = self.actor.attachNewNode(rayNode)
        #self.interactionSegmentNodePath.show()
        self.interactionSegmentQueue = CollisionHandlerQueue()

        self.interactionSegmentTraverser = CollisionTraverser()
        self.interactionSegmentTraverser.addCollider(
            self.interactionSegmentNodePath, self.interactionSegmentQueue)