Exemplo n.º 1
0
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()
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)
Exemplo n.º 3
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)
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
0
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)
	
Exemplo n.º 7
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)
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
Exemplo n.º 9
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)
Exemplo n.º 10
0
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
Exemplo n.º 11
0
class Camera(object):
    '''
        Controle da camera
    '''
    def __init__(self):

        self.keyMap = {
            "mouse1": EVENT_up,
            "wheel-in": EVENT_up,
            "wheel-out": EVENT_up
        }

        self.__camSeg = None
        self.__camColHandler = None
        self.__mousex = 0
        self.__mousey = 0
        self.__click = False

        self.__camDistancia = 200
        self.__camP = 10
        self.__camRef = 2.0

        self.ponto = render.attachNewNode('ponto')
        self.ponto.reparentTo(vinerWorld.usuario.modelo)
        self.ponto.setPos(0, 0, self.__camRef)
        #self.ponto.show()

        base.camera.reparentTo(self.ponto)
        base.camera.setY(base.camera, self.__camDistancia)

        self.__setup_collision()

        taskMgr.add(self.__task_movimentar_camera, "Task Camera", sort=3)

    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)

        #cameraColNp.show()
        #self.cTrav.showCollisions(render)

    def __task_movimentar_camera(self, task):

        if base.mouseWatcherNode.hasMouse():

            # Se rodar o botao do mouse, zoom-in ou zoom-out
            if self.keyMap["wheel-in"] != EVENT_up:
                self.__camDistancia -= 0.1 * self.__camDistancia
                if self.__camDistancia < 10:
                    self.__camDistancia = 10

                self.keyMap["wheel-in"] = EVENT_up

            elif self.keyMap["wheel-out"] != EVENT_up:
                self.__camDistancia += 0.1 * self.__camDistancia
                if self.__camDistancia > 400:
                    self.__camDistancia = 400

                self.keyMap["wheel-out"] = EVENT_up
            # Se rodar o botao do mouse, zoom-in ou zoom-out

            if self.keyMap["mouse1"] != EVENT_up:
                hidden_mouse(True)

                if not self.__click:
                    self.__click = True
                    self.__mousex = base.win.getPointer(0).getX()
                    self.__mousey = base.win.getPointer(0).getY()

                mousex_atual = base.win.getPointer(0).getX()
                mousey_atual = base.win.getPointer(0).getY()

                deltaX = mousex_atual - self.__mousex
                deltaY = mousey_atual - self.__mousey

                #movimenta cam esquerda e direita
                self.ponto.setH(self.ponto, (0.5 * deltaX))
                #movimenta cam esquerda direita

                #movimenta cam cima e baixo
                self.__camP += (0.5 * deltaY)

                if (self.__camP < -60): self.__camP = -60
                elif (self.__camP > 80): self.__camP = 80
                #movimenta cam cima e baixo

                base.win.movePointer(0, self.__mousex, self.__mousey)
            else:
                hidden_mouse(False)
                self.__click = False

                if vinerWorld.usuario.estaMovendo:
                    #corrige cam automaticamente
                    ponto_h = int(self.ponto.getH())
                    if (ponto_h > 0): self.ponto.setH(self.ponto, -1)
                    elif (ponto_h < 0): self.ponto.setH(self.ponto, +1)
                    #else:               self.ponto.setH(0)

                    comera_p = round(self.__camP, 1)
                    if (comera_p > 30.1): self.__camP -= 0.2
                    elif (comera_p < -0.1): self.__camP += 0.2
                    #corrige cam automaticamente

        #atualiza posicao camera
        base.camera.setHpr(0, self.__camP, 0)
        base.camera.setPos(0, 0, 0)
        base.camera.setY(base.camera, self.__camDistancia)
        base.camera.lookAt(self.ponto)

        self.__camSeg.setPointB(base.camera.getPos())
        #atualiza posicao camera

        #sistema de colisao
        self.cTrav.traverse(render)

        entries = []
        for i in range(self.__camColHandler.getNumEntries()):
            entry = self.__camColHandler.getEntry(i)
            entries.append(entry)

        entries.sort(lambda x, y: cmp(-y.getSurfacePoint(self.ponto).getY(), -x
                                      .getSurfacePoint(self.ponto).getY()))
        if (len(entries) > 0):

            pColision = entries[0].getSurfacePoint(self.ponto)
            base.camera.setPos(pColision[0], pColision[1], pColision[2])

            if (entries[0].getIntoNode().getName() == "terrain"):
                base.camera.setZ(base.camera, 0.3)
        #sistema de colisao

        return task.cont
Exemplo n.º 12
0
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
Exemplo n.º 13
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
Exemplo n.º 14
0
class Player():
    def __init__(self, camera, accept, render, loader, maxJPHeight):
        #initial variables and sounds

        self.developer = True  # Developer tools (building tools) will be accessible if this is turned on.
        self.gameMode = self.mode0  # the current playerUpdate function that is in use
        # self.playerModeParameters = () # the parameters being fed into the function above.
        self.groundContact = False  # if the player is on the ground or a surface, gravity will not pull the player below the surface
        self.jetPack_energy = 100
        self.maximumHeight = maxJPHeight  # maximum height in which the jetpack can fly to, this is dependent on the map loaded.
        self.jetPack_AUDIO = loader.loadSfx("assets/base/sounds/jetpack2.wav")
        self.jetPack_AUDIO.setLoop(True)
        self.vertical_velocity = 0  # Current Z velocity, positive = Upwards.
        self.z_velocity = 0  # Current Y velocity
        self.x_velocity = 0
        self.movingZ = False
        self.movingX = False

        #initiate GUI
        self.HUD = GUI()
        self.playerHolder = render.attachNewNode('player')

        # camera control - Hiding mouse and using it to rotate the camera
        props = WindowProperties()
        props.setCursorHidden(True)
        props.setMouseMode(WindowProperties.M_relative)
        base.win.requestProperties(props)

        # PLAYER MODEL SCENE GRAPH
        self.thirdPersonCamera_ZOOM = -50  # initial distance of third person camera.
        self.character = loader.loadModel(
            'assets/base/models/playerModel/player.bam')
        self.toggleFPCam = False  # Whether first person camera is on, this is initially off.
        self.character.setPos(0, 0, 0)
        self.character.reparentTo(self.playerHolder)
        self.playerBase = self.playerHolder.attachNewNode('camParent')
        self.thirdPersonNode = self.playerBase.attachNewNode('thirdPersonCam')
        camera.reparentTo(self.thirdPersonNode)
        self.mouseSeconds = []
        self.playerHolder.setScale(4)
        self.monitor = loader.loadModel(
            'assets/base/models/faces/playerMonitor.bam')
        self.monitor.reparentTo(self.playerHolder)
        self.cTrav = CollisionTraverser()

        # Horizontal collisions
        self.pusher = CollisionHandlerPusher()
        self.pusher.horizontal = True
        self.colliderNode = CollisionNode("player")
        self.colliderNode.addSolid(CollisionSphere(0, 0, 0, 2))
        self.colliderNode.setFromCollideMask(CollideMask.bit(1))
        self.colliderNode.setFromCollideMask(CollideMask.bit(0))
        self.colliderNode.setIntoCollideMask(BitMask32.allOff())
        collider = self.playerHolder.attachNewNode(self.colliderNode)
        collider.show()
        self.pusher.addCollider(collider, self.playerHolder)
        self.cTrav.addCollider(collider, self.pusher)

        # Vertical collisions - Downwards
        self.groundRay = CollisionRay()
        self.groundRay.setDirection(0, 0, -1)
        self.groundRayCol = CollisionNode('playerRay')
        self.groundRayCol.addSolid(self.groundRay)
        self.groundRayCol.setFromCollideMask(CollideMask.bit(1))
        self.groundRayCol.setIntoCollideMask(CollideMask.allOff())
        self.groundColNp = self.playerHolder.attachNewNode(self.groundRayCol)
        self.groundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.groundColNp, self.groundHandler)

        # Third Person Camera Collision
        self.cameraRay = CollisionSegment()
        self.cameraRayNode = CollisionNode('camerRay')
        self.cameraRayNode.addSolid(self.cameraRay)
        self.cameraRayNodePath = render.attachNewNode(self.cameraRayNode)
        self.cameraCollisionHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.cameraRayNodePath,
                               self.cameraCollisionHandler)

        # Vertical collisions - Upwards
        self.upwardsRay = CollisionRay()
        self.upwardsRay.setDirection(0, 0, 1)
        self.upwardsRayCol = CollisionNode('playerupRay')
        self.upwardsRayCol.addSolid(self.upwardsRay)
        self.upwardsRayCol.setFromCollideMask(CollideMask.bit(1))
        self.upwardsRayCol.setIntoCollideMask(CollideMask.allOff())
        self.upwardsColNp = self.playerHolder.attachNewNode(self.upwardsRayCol)
        self.upwardsHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.upwardsColNp, self.upwardsHandler)
        #self.cTrav.showCollisions(render)

        if self.developer == True:
            self.tool = buildingTool(
                "newbuildings", self.playerHolder, loader,
                accept)  # Load up building tool if developer modee is on.

        #self.setupLighting() # light
        #initial position
        self.playerHolder.setPos(45178.3, 43109.3, 0)
        self.keyMap = {
            "left": False,
            "right": False,
            "forward": False,
            "backwards": False,
            "change_camera": False,
            "leftClick": False,
            "space": False,
            "p": False,
            "scrollup": False,
            "scrolldown": False
        }

        accept("escape", sys.exit)
        accept("w", self.updateKey, ["forward", True])  #
        accept("w-up", self.updateKey, ["forward", False])

        accept("a", self.updateKey, ["left", True])
        accept("a-up", self.updateKey, ["left", False])

        accept("s", self.updateKey, ["backwards", True])
        accept("s-up", self.updateKey, ["backwards", False])

        accept("d", self.updateKey, ["right", True])
        accept("d-up", self.updateKey, ["right", False])

        accept("c", self.updateKey, ["change_camera", True])

        accept("wheel_up", self.updateKey, ["scrollup", True])

        accept("wheel_down", self.updateKey, ["scrolldown", True])

        accept("p", self.updateKey, ["p", True])
        accept("p-up", self.updateKey, ["p", False])

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

        self.playerMode = playerModes(
            self.playerBase, self.playerHolder, self.character,
            self.vertical_velocity, self.z_velocity, self.x_velocity,
            self.keyMap, self.monitor, self.thirdPersonNode,
            self.jetPack_energy, self.jetPack_AUDIO,
            self.thirdPersonCamera_ZOOM, self.toggleFPCam, self.HUD,
            self.cTrav, self.groundHandler, self.upwardsHandler,
            self.maximumHeight)

    def playerUpdate(self, task):  # our UPDATE TASK
        self.gameMode()
        return task.cont

    def updateKey(self, key, value):
        self.keyMap[key] = value
        if key == "change_camera":
            self.changeCamera()
        self.scrollFactor = 10
        if key == "scrollup":  # third person zoom in/out
            self.thirdPersonCamera_ZOOM += self.scrollFactor
        if key == "scrolldown":
            self.thirdPersonCamera_ZOOM -= self.scrollFactor

    def changeCamera(self):  # Toggle first person camera.
        if self.toggleFPCam == False:
            self.toggleFPCam = True
        else:
            self.toggleFPCam = False

    def recenterMouse(self):
        base.win.movePointer(0, int(base.win.getProperties().getXSize() / 2),
                             int(base.win.getProperties().getYSize() / 2))

    def setupLighting(self):
        plight = PointLight('plight')
        plight.setColor((1, 1, 1, 1))
        plnp = self.playerHolder.attachNewNode(plight)
        plnp.setPos(0, 1, 7)
        render.setLight(plnp)

# PLAYER MODES, HOW THE USER INTERACTS AND CONTROLS WITH THE USER

#   MODE 0
# Mode 0 is the default update mode, it allows WASD movement,
# mouse controlled camera rotations, first person and third
# person switching, it also has GUI display and player physics.

    def mode0(self):

        #THIRD PERSON CAMERA COLLISION

        # print("thirdpersonnode")
        # print(self.playerBase.getHpr())
        # print("pb")
        # print(self.character.getHpr())

        deltaTime = globalClock.getDt()
        self.movingZ = False
        self.movingX = False
        self.walkConstant = 25
        self.rotateConstant = 750

        # Keyboard controls
        # LEVITATION STUFF (FORMERLY CALLED JETPACK)

        if self.keyMap["space"] and self.jetPack_energy > 0:
            jetpack = 0.00001 * ((
                (self.playerHolder.getZ()) - self.maximumHeight)**2) + 9.81
            self.playerHolder.setZ(self.playerBase, jetpack)
            self.jetPack_energy -= 15 * deltaTime
            self.walkConstant = 70
            self.jetPack_AUDIO.play()
        else:
            self.jetPack_AUDIO.stop()
        if self.jetPack_energy < 100:
            self.jetPack_energy += 10 * deltaTime
        if self.jetPack_energy > 100:
            self.jetPack_energy = 100

        self.HUD.jetpackStatus.text = "Levitation Battery: " + str(
            int(self.jetPack_energy)) + "%"

        if (self.keyMap["forward"]
                or self.keyMap["backwards"]) and (self.keyMap["right"]
                                                  or self.keyMap["left"]):
            self.walkConstant = int(((self.walkConstant**2) / 2)**0.5)

        # WASD MOVEMENT
        if self.keyMap["forward"]:
            self.monitor.setH(self.playerBase.getH() - 90)
            self.movingZ = True
            self.z_velocity += 5
            if self.z_velocity > self.walkConstant:
                self.z_velocity = self.walkConstant

        if self.keyMap["right"]:
            self.monitor.setH(self.playerBase.getH() - 180)
            self.movingX = True
            self.x_velocity += 5
            if self.x_velocity > self.walkConstant:
                self.x_velocity = self.walkConstant
        if self.keyMap["p"]:
            print(self.playerHolder.getPos())
            print(self.thirdPersonCamera_ZOOM)
            self.gameMode = self.mode1
        if self.keyMap["left"]:
            self.monitor.setH(self.playerBase.getH())
            self.movingX = True
            self.x_velocity -= 5
            if self.x_velocity < -self.walkConstant:
                self.x_velocity = -self.walkConstant
        if self.keyMap["backwards"]:
            self.monitor.setH(self.playerBase.getH() + 90)
            self.movingZ = True
            self.z_velocity -= 20
            if self.z_velocity < -self.walkConstant:
                self.z_velocity = -self.walkConstant

        if self.movingZ == False:
            if self.z_velocity <= 7 or (
                    self.z_velocity >= -5
                    and self.z_velocity < 0):  # Shaking bug fix
                self.z_velocity = 0
            if self.z_velocity > 0:
                self.z_velocity -= 10
            elif self.z_velocity < 0:
                self.z_velocity += 10
        if self.movingX == False:
            if self.x_velocity <= 5 or (
                    self.x_velocity >= -5
                    and self.x_velocity < 0):  # Shaking bug fix
                self.x_velocity = 0
            if self.x_velocity > 0:
                self.x_velocity -= 10
            elif self.x_velocity < 0:
                self.x_velocity += 10
        # MONITOR HEADINGS FOR DOUBLE INPUT
        if self.keyMap["forward"] and self.keyMap["right"]:
            self.monitor.setH(self.playerBase.getH() - 135)
        elif self.keyMap["forward"] and self.keyMap["left"]:
            self.monitor.setH(self.playerBase.getH() - 45)
        elif self.keyMap["backwards"] and self.keyMap["left"]:
            self.monitor.setH(self.playerBase.getH() + 45)
        elif self.keyMap["backwards"] and self.keyMap["right"]:
            self.monitor.setH(self.playerBase.getH() + 135)

        # third person camera control
        if (self.toggleFPCam == False):  # third person camera controls
            if (base.mouseWatcherNode.hasMouse() == True):
                mouseposition = base.mouseWatcherNode.getMouse()
                self.thirdPersonNode.setP(mouseposition.getY() * 30)
                self.playerBase.setH(mouseposition.getX() * -50)
                if (mouseposition.getX() < 0.1
                        and mouseposition.getX() > -0.1):
                    self.playerBase.setH(self.playerBase.getH())

            if self.thirdPersonNode.getP() > 90:
                self.recenterMouse()
                self.thirdPersonNode.setP(90)  # TRACK MOUSE
            elif self.thirdPersonNode.getP() < -90:
                self.recenterMouse()
                self.thirdPersonNode.setP(-90)
            if self.thirdPersonCamera_ZOOM > -20:  # validate zoom
                self.thirdPersonCamera_ZOOM = -20
            elif self.thirdPersonCamera_ZOOM < -390:
                self.thirdPersonCamera_ZOOM = -390
        # CAMERA STUFF
        # FIRST PERSON CAMERA
        if self.toggleFPCam:  # first person camera controls
            camera.setPos(self.character.getPos())  # 0,-50,-10
            camera.setZ(camera.getZ() + 6)
            self.playerHolder.hide()
            if (base.mouseWatcherNode.hasMouse() == True):
                mouseposition = base.mouseWatcherNode.getMouse()
                camera.setP(mouseposition.getY() * 20)
                self.playerBase.setH(mouseposition.getX() * -50)
                if (mouseposition.getX() < 0.1
                        and mouseposition.getX() > -0.1):
                    self.playerBase.setH(self.playerBase.getH())
            if camera.getP() > 90:
                self.recenterMouse()
                camera.setP(90)  # TRACK MOUSE
            elif camera.getP() < -90:
                self.recenterMouse()
                camera.setP(-90)
        else:  # takes out of first person perspective if toggleFPS is turned off.
            self.playerHolder.show()
            camera.setPos(0, self.thirdPersonCamera_ZOOM, 0)  # 0,-50,-4
            camera.lookAt(self.character)
        # movement updates
        self.playerHolder.setY(self.playerBase, (self.z_velocity * deltaTime))
        self.playerHolder.setX(self.playerBase, (self.x_velocity * deltaTime))

        # forward/backward rolling
        axis = self.playerBase.getQuat().getRight()
        angle = (self.z_velocity * deltaTime * -8)
        quat = Quat()
        quat.setFromAxisAngle(angle, axis)
        newVec = self.character.getQuat() * quat
        # print(newVec.getHpr())
        self.character.setQuat(newVec)

        # sideways rolling
        axis = self.playerBase.getQuat().getForward()
        angle = (self.x_velocity * deltaTime * 8)
        quat = Quat()
        quat.setFromAxisAngle(angle, axis)
        newVec = self.character.getQuat() * quat
        # print(self.playerBase.getPos())
        self.character.setQuat(newVec)
        self.cameraRay.setPointA(self.playerBase.getPos())
        if camera.getPos() != (0, 0, 0):
            self.cameraRay.setPointB(camera.getPos(base.render))

        self.cTrav.traverse(render)

        # checking for camera collisions
        entries = list(self.cameraCollisionHandler.entries)
        for entry in entries:
            if str(entry.getIntoNodePath())[:19] != "render/worldTerrain":
                #camera.setPos(entry.getSurfacePoint(self.thirdPersonNode))
                self.thirdPersonCamera_ZOOM += 1

        # if len(entries) > 0:
        #     if (self.playerHolder.getZ() < entries[-1].getSurfacePoint(render).getZ() + 8):
        #         self.playerHolder.setZ(entries[-1].getSurfacePoint(render).getZ() + 8)
        #         self.vertical_velocity = 0

        # checking for collisions - downwards
        entries = list(self.groundHandler.entries)
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
        self.performGravity = True
        if self.performGravity == True:
            self.vertical_velocity -= (deltaTime * 9.81)
            if self.vertical_velocity <= -15:
                self.vertical_velocity = -15
            self.playerHolder.setPos(self.playerHolder,
                                     Vec3(0, 0,
                                          self.vertical_velocity))  # Gravity
        if len(entries) > 0:
            if (self.playerHolder.getZ() <
                    entries[-1].getSurfacePoint(render).getZ() + 8):
                self.playerHolder.setZ(
                    entries[-1].getSurfacePoint(render).getZ() + 8)
                self.vertical_velocity = 0

        # checking for collisions - upwards
        entries = list(self.upwardsHandler.entries)
        entries.sort(key=lambda x: x.getSurfacePoint(render).getZ())
        if len(entries) > 0:
            for entry in entries:
                if (self.playerHolder.getZ() >
                        entry.getSurfacePoint(render).getZ() - 70):
                    self.playerHolder.setZ(
                        entry.getSurfacePoint(render).getZ() - 130)

    # PLAYER MODES, HOW THE USER INTERACTS AND CONTROLS WITH THE USER
    #   MODE 1
    # Mode 1 is a test update loop used to test player loop switching.
    # it simply freezes the controls.

    def mode1(self):
        self.playerHolder.hide()
        self.playerHolder.setHpr(0, 0, 0)
        if self.keyMap["backwards"]:
            self.playerHolder.show()
            self.gameMode = self.mode0