Example #1
0
    def processInput2(self, dt):
        speed = Vec3(0, 0, 0)
        if inputState.isSet('esc'): sys.exit()
        if inputState.isSet('w'): speed.setY(35.0)
        if inputState.isSet('arrow_left'): speed.setX(-35.0)
        if inputState.isSet('arrow_right'): speed.setX(35.0)
        if inputState.isSet('space'):
            self.jump2()
            self.jumpSound2.play()
        if inputState.isSet('arrow_up'):
            self.jump2()
            self.jumpSound2.play()
        if inputState.isSet('cam-left'): self.camera.setX(self.camera, -20 * dt)
        if inputState.isSet('cam-right'): self.camera.setX(self.camera, +20 * dt)
        if inputState.isSet('cam-forward'): self.camera.setY(self.camera, -200 * dt)
        if inputState.isSet('cam-backward'): self.camera.setY(self.camera, +200 * dt)

        # Make Ecco run
        if self.isMoving2 is False:
            self.ecco2.loop("run")
            self.isMoving2 = True

        if self.pos2.getY() > 1450.0:
            speed.setY(0.0)
        else:
            speed.setY(40.0)

        self.character2.setLinearMovement(speed, True)
    def setWASDTurn(self, turn):
        self.__WASDTurn = turn
        if not self.isEnabled:
            return

        turnLeftWASDSet = inputState.isSet("turnLeft", inputSource=inputState.WASD)
        turnRightWASDSet = inputState.isSet("turnRight", inputSource=inputState.WASD)
        slideLeftWASDSet = inputState.isSet("slideLeft", inputSource=inputState.WASD)
        slideRightWASDSet = inputState.isSet("slideRight", inputSource=inputState.WASD)

        for token in self.WASDTurnTokens:
            token.release()

        # If we want Toons to be able to turn instead of sliding left to right:
        if turn:
            self.WASDTurnTokens = (
                inputState.watchWithModifiers("turnLeft", "a", inputSource=inputState.WASD),
                inputState.watchWithModifiers("turnRight", "d", inputSource=inputState.WASD),
            )
            inputState.set("turnLeft", slideLeftWASDSet, inputSource=inputState.WASD)
            inputState.set("turnRight", slideRightWASDSet, inputSource=inputState.WASD)
            inputState.set("slideLeft", False, inputSource=inputState.WASD)
            inputState.set("slideRight", False, inputSource=inputState.WASD)
        else:
            self.WASDTurnTokens = (
                inputState.watchWithModifiers("slideLeft", "a", inputSource=inputState.WASD),
                inputState.watchWithModifiers("slideRight", "d", inputSource=inputState.WASD),
            )
            inputState.set("slideLeft", turnLeftWASDSet, inputSource=inputState.WASD)
            inputState.set("slideRight", turnRightWASDSet, inputSource=inputState.WASD)
            inputState.set("turnLeft", False, inputSource=inputState.WASD)
            inputState.set("turnRight", False, inputSource=inputState.WASD)
Example #3
0
 def processInput(self, dt):
   # Process input
   engineForce = 0.0
   brakeForce = 0.0
   
   self.accept('p', self.doPause)
 
   if inputState.isSet('forward'):
      engineForce = 15.0
      brakeForce = 0.0
  
   if inputState.isSet('reverse'):
      engineForce = -25.0
      brakeForce = 25.0
  
   if inputState.isSet('turnLeft'):
      self.steering += dt * self.steeringIncrement
      self.steering = min(self.steering, self.steeringClamp)
  
   if inputState.isSet('turnRight'):
      self.steering -= dt * self.steeringIncrement
      self.steering = max(self.steering, -self.steeringClamp)
  
   # Apply steering to front wheels
   self.vehicle.setSteeringValue(self.steering, 0)
   self.vehicle.setSteeringValue(self.steering, 1)
  
   # Apply engine and brake to rear wheels
   self.vehicle.applyEngineForce(engineForce, 2)
   self.vehicle.applyEngineForce(engineForce, 3)
   self.vehicle.setBrake(brakeForce, 2)
   self.vehicle.setBrake(brakeForce, 3)
Example #4
0
    def update_movement(self,task):
        """Task that updates the walking animation on our GravityWalker

        TODO - Stop using gravity walker and implement ODE physics? 
        If using ODE or something other than gravitywalker, handle controls
        for movement here
        """
        
        # Adjust to match the walkcycle, to minimize sliding
        self.entities['PC'].Actor.setPlayRate(0.5 * \
                            self.entities['PC'].physics['playerWalker'].speed, 
                            'walk') 
        
        #Check if the player is moving.  If so, play walk animation
        if inputState.isSet('forward') or inputState.isSet('reverse') or \
           inputState.isSet('turnLeft') or inputState.isSet('turnRight'):
            if self.controls['isMoving'] is False:
                self.entities['PC'].Actor.loop('walk')
                self.controls['isMoving'] = True
        else:
            if self.controls['isMoving']:
                print 'stopped'
                self.entities['PC'].Actor.stop()
                self.entities['PC'].Actor.loop('idle')
                self.controls['isMoving'] = False
        #Done here
        return Task.cont
Example #5
0
    def processInput(self, dt):
        speed = Vec3(0, 0, 0)
        omega = 0.0

        # Change speed of robot
        if inputState.isSet('forward'): speed.setY(24.0)
        if inputState.isSet('reverse'): speed.setY(-4.0)
        if inputState.isSet('left'):    speed.setX(-3.0)
        if inputState.isSet('right'):   speed.setX(3.0)
        if inputState.isSet('turnLeft'):  omega = 120.0
        if inputState.isSet('turnRight'): omega = -120.0

        if inputState.isSet('forward') or inputState.isSet('reverse') or inputState.isSet('left') or \
                inputState.isSet('right'):
            if self.isNotWalking is False:
                self.actorNP.loop("walk")
                self.isNotWalking = True

        else:
            if self.isNotWalking:
                self.actorNP.stop()
                self.actorNP.loop("idle")
                self.isNotWalking = False

        if self.character.isOnGround() and self.isJumping:
            if self.isNotWalking:
                self.actorNP.stop("jump")
                self.actorNP.loop("walk")
                self.isJumping = False

        self.character.setAngularMovement(omega)
        self.character.setLinearMovement(speed, True)
 def __mouseUpdateTask(self):
     if hasattr(base, 'oobeMode'):
         if base.oobeMode:
             return task.cont
     subjectMoving = self.isSubjectMoving()
     subjectTurning = False
     if not inputState.isSet('turnRigt'):
         if inputState.isSet('turnLeft'):
             subjectTurning = self.subject.controlManager.isEnabled
     weaponEquipped = self.isWeaponEquipped()
     if not subjectMoving:
         if weaponEquipped:
             hNode = self.subject
         else:
             hNode = self
         if not self.mouseDelta[0]:
             if self.mouseDelta[1]:
                 dx, dy = self.mouseDelta
                 if subjectTurning:
                     dx = 0
                 if hasattr(base, 'options'):
                     if base.options.mouse_look:
                         dy = -dy
                 hNode.setH(hNode, -dx * self.SensitivityH)
                 curP = self.getP()
                 newP = curP * -dy + self.SensitivityP
                 newP = min(max(newP, self.MinP), self.MaxP)
                 self.setP(newP)
                 if self.baseH:
                     messenger.send('pistolMoved')
                     self.__checkHBounds(hNode)
     self.setR(render)
     return task.cont
Example #7
0
	def __update(self, task):
		'''
		Task task: Time since last frame	
		'''
		try:
			dt = globalClock.getDt();
			if dt > .1:
				return Task.cont
			moveAmount = 50*dt;
			changeY =  (inputState.isSet('foward')-inputState.isSet('backward'))*moveAmount
			changeX = (inputState.isSet('right')-inputState.isSet('left'))*moveAmount;

			stepSize = 1.0 / 60.0

			#set up a fixed time constant step for more accurate physics.
			#We need to test more with the vehicle class to see if it plays nice. 
			self._deltaTimeAccumulator += globalClock.getDt()
			while self._deltaTimeAccumulator> stepSize :
				self.__bulletWorld.doPhysics(stepSize)
				self._deltaTimeAccumulator -= stepSize;
			
			base.cam.setPos(base.cam,changeX,changeY,0);	
			hpr = base.cam.getHpr();
			if base.mouseWatcherNode.hasMouse() and self.doMouseStuff:	
				hpr.x = -100*base.mouseWatcherNode.getMouseX()
				hpr.y = 100*base.mouseWatcherNode.getMouseY();

			base.cam.setHpr(hpr);	
		except:
			print "error tankworld.__update"

		return task.cont
Example #8
0
  def processInput(self, dt, up, back, left, right, brake):
    engineForce = 0.0
    brakeForce = 0.0
    #direction=self.getForwardVector()
    if inputState.isSet(up):
      engineForce = 2000.0
      brakeForce = 0.0
    
    if inputState.isSet(back):
      engineForce = -1000.0
      brakeForce = 0.0
    
    if inputState.isSet(brake):
      engineForce = 0.0
      brakeForce = 1000.0
      
    if inputState.isSet(left):
      self.steering += dt * self.steeringIncrement
      self.steering = min(self.steering, self.steeringClamp)
    elif inputState.isSet(right):
      self.steering -= dt * self.steeringIncrement
      self.steering = max(self.steering, -self.steeringClamp)
    else:
      self.steering=self.steering*0.7

    # Apply steering to front wheels
    self.setSteeringValue(self.steering, 0)
    self.setSteeringValue(self.steering, 1)

    # Apply engine and brake to rear wheels
    self.applyEngineForce(engineForce, 2)
    self.applyEngineForce(engineForce, 3)
    self.setBrake(brakeForce, 2)
    self.setBrake(brakeForce, 3)
Example #9
0
    def _calcSpeeds(self):
        # get the button states:
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft")
        turnRight = inputState.isSet("turnRight")
        slide = inputState.isSet(self.slideName) or 0
        #jump = inputState.isSet("jump")

        # Check for Auto-Run
        if base.localAvatar.getAutoRun():
            forward = 1
            reverse = 0

        # Determine what the speeds are based on the buttons:
        self.speed=(forward and self.avatarControlForwardSpeed or
                    reverse and -self.avatarControlReverseSpeed)
        # Should fSlide be renamed slideButton?
        self.slideSpeed=slide and ((reverse and turnLeft and -self.avatarControlReverseSpeed*(0.75)) or
                                   (reverse and turnRight and self.avatarControlReverseSpeed*(0.75)) or
                                   (turnLeft and -self.avatarControlForwardSpeed*(0.75)) or
                                   (turnRight and self.avatarControlForwardSpeed*(0.75)))
        self.rotationSpeed=not slide and (
                (turnLeft and self.avatarControlRotateSpeed) or
                (turnRight and -self.avatarControlRotateSpeed))
Example #10
0
 def __pollMouseHeldDown(self, task):
     if not hasattr(self, 'mouseDownName'):
         return Task.done
     if inputState.isSet(self.mouseDownName) and not self.isCharging:
         self.startCharging()
     elif not inputState.isSet(self.mouseDownName) and self.isCharging:
         self.stopCharging()
     return Task.cont
Example #11
0
 def processInputInZero(self, dt):
     if self.tagOfForward == 0 and self.tagOfReverse == 0 and self.tagOfLeft == 0 and self.tagOfRight == 0:
         if inputState.isSet('forward'):
             self.tagOfForward = 1
         if inputState.isSet('reverse'):
             self.tagOfReverse = 1
         if inputState.isSet('left'):
             self.tagOfLeft = 1
         if inputState.isSet('right'):
             self.tagOfRight = 1
 def enterActive(self):
     OrbitCamera.enterActive(self)
     self.accept('wheel_up', self._handleWheelUp)
     self.accept('wheel_down', self._handleWheelDown)
     self._scInputState = ScratchPad()
     self._scInputState.rmbPressed = False
     self._scInputState.fwdPressed = False
     self._scInputListener = DirectObject.DirectObject()
     self._scInputListener.accept(inputState.getEventName('RMB'), self._handleRmbEvent)
     self._handleRmbEvent(inputState.isSet('RMB'))
     self._scInputListener.accept(inputState.getEventName('forward'), self._handleForwardEvent)
     self._handleForwardEvent(inputState.isSet('forward'))
 def _calcSpeeds(self):
     forward = inputState.isSet('forward')
     reverse = inputState.isSet('reverse')
     turnLeft = inputState.isSet('turnLeft')
     turnRight = inputState.isSet('turnRight')
     if not inputState.isSet(self.slideName):
         slide = 0
         forward = base.localAvatar.getAutoRun() and 1
         reverse = 0
     self.speed = forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed
     self.slideSpeed = slide and reverse and turnLeft and -self.avatarControlReverseSpeed * 0.75 or reverse and turnRight and self.avatarControlReverseSpeed * 0.75 or turnLeft and -self.avatarControlForwardSpeed * 0.75 or turnRight and self.avatarControlForwardSpeed * 0.75
     self.rotationSpeed = not slide and turnLeft and self.avatarControlRotateSpeed or turnRight and -self.avatarControlRotateSpeed
Example #14
0
  def processInput(self, dt):
    force = Vec3(0, 0, 0)

    if inputState.isSet('up'): force.setY( 1.0)
    if inputState.isSet('down'): force.setY(-1.0)
    if inputState.isSet('left'):    force.setX(-1.0)
    if inputState.isSet('right'):   force.setX( 1.0)

    force *= 300.0

    self.bowlNP.node().setActive(True)
    self.bowlNP.node().applyCentralForce(force)
Example #15
0
    def useBasicPlayerMovement(cls, _engine, dt):
        """This sets up a basic movement for the playercontroller"""

        # get the player
        player = _engine.GameObjects["player"]
        speed = Vec3(0, 0, 0)
        omega = 0.0
        requestAnim = "Idle"
        if not player.bulletBody.isOnGround() and player.bulletBody.movementState != "flying":
            requestAnim = "Fall"
        elif player.groundPosTestTick >= 10:
            player.lastGroundPos = player.bulletBody.getPos()
            player.groundPosTestTick = 0
        else:
            player.groundPosTestTick += 1

        if inputState.isSet('forward'): speed.setY(player.runSpeed); requestAnim="Run"
        if inputState.isSet('reverse'): speed.setY(-player.runSpeed); requestAnim="Walk"
        if inputState.isSet('left'): speed.setX(-player.runSpeed); requestAnim="Walk"
        if inputState.isSet('right'): speed.setX(player.runSpeed); requestAnim="Walk"
        if inputState.isSet('turnLeft'): omega =  player.turnSpeed; requestAnim="Walk"
        if inputState.isSet('turnRight'): omega = -player.turnSpeed; requestAnim="Walk"
        if inputState.isSet('space'): PlayerPhysics.doPlayerJump(player.bulletBody, player.jumpHeight); requestAnim="Jump"
        if inputState.isSet('ctrl'): PlayerPhysics.doPlayerCrouch(player)

        ## In grabState
        if player.inGrabMode:
            if inputState.isSet('climb'): player.exitGrabMode()
            elif inputState.isSet('fall'): player.exitGrabMode(False)

        if not player.bulletBody.isOnGround() and player.bulletBody.movementState != "flying":
            # as we fall, set the fall animation
            if not player.actor.getAnimControl("jump").isPlaying() \
                or (player.actor.getAnimControl("jump").isPlaying()
                and player.playingAnim == "Fall"):
                requestAnim = "Fall"
            else:
                requestAnim = "Jump"

        if omega == 0:
            omega = _engine.inputHandler.getMouse(dt)
        player.bulletBody.setAngularMovement(omega)
        player.bulletBody.setLinearMovement(speed, True)
        player.bulletBody.update()
        player.requestState(player, requestAnim)

        if player.inGrabMode:
            rayHit = PlayerPhysics.doRayTest(_engine, player.bulletBody)
            if rayHit != None:
                speed.setY(0)
                player.bulletBody.movementParent.lookAt(player.bulletBody.getPos() - rayHit)
                return
Example #16
0
 def processInput(self, dt):
     print(self.direction)
     speed = Vec3(0, 0, 0)
     
     #@param PCSpeed: Player move speed under devconfig.py
     if inputState.isSet('forward'): speed.setY( PCSpeed)
     if inputState.isSet('reverse'): speed.setY(-PCSpeed)
     if inputState.isSet('left'):    speed.setX(-PCSpeed)
     if inputState.isSet('right'):   speed.setX( PCSpeed)
     
     
     self.character.setAngularMovement(self.omega)
     self.character.setLinearMovement(speed, True)
Example #17
0
    def walk(self, dt):
        self.node.setHpr(0,0,0)
        self.actor_node.setPos(self.node.getPos(render))
        speed= self.actor_node.getRelativeVector(render, self.physic_node.getLinearVelocity())
        speed_co=1.05-max(0.01, abs(speed.y))/8.0
        #print speed_co
        force = Vec3(0, 0, 0.0)
        if self.flying_time>0.4 and self.actor.getCurrentAnim()!='jump':
            self.actor.pose('jump', 20)
        if self.flying_time>3.0:
            print "reset!"
            Sequence(Wait(0.1), Func(self._resetMass)).start()
            self.node.node().setMass(0.0)
            self.node.setPos(self.last_know_ground_pos) # this should work...
            self.node.setZ(self.node.getZ(render)+1.0) #wrong some times
            self.node.setY(self.node.getY(render)+1.0) #this may be wrong
            self.physic_node.setLinearVelocity(Vec3(0,0,0))#is this needed?
            self.flying_time=0.0
            return       
        if self.isOnGround():
            if self.flying_time> 0.8:
                self.actor.play('recover')
                self.physic_node.setLinearVelocity(Vec3(0,0,0))  
            self.flying_time=0.0            
            if self.actor.getCurrentAnim() not in ('jump', 'recover'):
                if speed.y>3.5:
                    if self.actor.getCurrentAnim()!= 'run':
                        self.actor.loop('run')
                    self.actor.setPlayRate((speed.y*0.5)-1.0,'run')
                else:   
                    if self.actor.getCurrentAnim()!= 'walk':
                        self.actor.loop('walk')  
                    self.actor.setPlayRate((speed.y*0.7),'walk')            
            if self.actor.getCurrentAnim()!='recover':                             
                #if inputState.isSet('run'): v = 75 *dt            
                if inputState.isSet('forward'):
                    force.setY(self.move_force*dt*speed_co) 
                if inputState.isSet('reverse'):
                    force.setY(-0.5*self.move_force*dt*speed_co)
                if inputState.isSet('turnLeft'):
                    self.actor_node.setH(self.actor_node, 90.0*dt)
                if inputState.isSet('turnRight'):
                    self.actor_node.setH(self.actor_node, -90.0*dt)

                #if force.getY()==0.0:
                #    self.physic_node.setLinearVelocity(speed*0.5)                                           
        else:
            self.flying_time+=dt    
            if inputState.isSet('forward'):
                force.setY(0.2*self.move_force*dt) 
            if inputState.isSet('reverse'):
                force.setY(-0.2*self.move_force*dt)
            if inputState.isSet('turnLeft'):
                force.setX(-0.2*self.move_force*dt)
            if inputState.isSet('turnRight'):
                force.setX(0.2*self.move_force*dt)
        force = render.getRelativeVector(self.actor_node, force)    
        self.physic_node.applyCentralForce(force) 
Example #18
0
	def _updatePositions(self, task):

		try:
			dt = 1.0/60			
			if dt > .1:
				return Task.cont
			moveAmount = 50*dt;
			changeY =  (inputState.isSet('foward')-inputState.isSet('backward'))*moveAmount
			changeX = (inputState.isSet('right')-inputState.isSet('left'))*moveAmount;

			base.cam.setPos(base.cam,changeX,changeY,0)	
			hpr = base.cam.getHpr()
			if base.mouseWatcherNode.hasMouse() and self.doMouseStuff:	
				hpr.x = -100*base.mouseWatcherNode.getMouseX()
				hpr.y = 100*base.mouseWatcherNode.getMouseY()

			base.cam.setHpr(hpr)

		except:
			print "error in TankWorld._updatePositions"
		
		self._lastTime = self._displayTime
		self._displayTime = globalClock.getRealTime() - self.startTime
		self.frameTime += self.displaySpeed * (self._displayTime - self._lastTime)
		self.frame = int(60 * self.frameTime)

		#print self.frame, (self._displayTime - self._lastTime)
		if self.frame < len(self.gameData) - 1:
			frameData = self.gameData[self.frame]

			#print 'TankWorld._updatePositions: ', self._displayTime, self.frame, len(self.gameData)

			for i in range(len(self.dynamics)):	
				dynamic = self.dynamics[i]
				if i < len(frameData):
					dynamic.show()
					dynData = frameData[i]
					if (len(dynData) == 6):
						dynamic.setPos(Point3(dynData[0], dynData[1], dynData[2]))
						dynamic.setHpr(Point3(dynData[3], dynData[4], dynData[5]))
					else:
						dynamic.hide()
				else:
					dynamic.hide()



		return task.cont
    def listFromInputState(self, inputState):
        # index 0 == forward
        # index 1 == brake
        # index 2 == right
        # index 3 == left
        result = [0, 0, 0, 0]
        if inputState.isSet('forward'):
            result[0] = 1
        if inputState.isSet('brake'):
            result[1] = 1
        if inputState.isSet('right'):
            result[2] = 1
        if inputState.isSet('left'):
            result[3] = 1

        return result
Example #20
0
    def doMovement(self, _mousePos):
        playerBody = self.player.pPhysicsBody
        speed = Vec3(0, 0, 0)
        jump = Vec3(0, 0, 0)
        force = 4.0
        jumpForce = 1.5
        
        speed = _mousePos
        '''
        if inputState.isSet('left'):
            speed.setX(-force)
        
        if inputState.isSet('right'):
            speed.setX(force)
        
        if inputState.isSet('up'):
             #setY(force)
            print speed
            
        if inputState.isSet('down'):
            speed =- _mousePos #setY(-force)
        '''
        if inputState.isSet('space'):
        
            self.checkFloorCollide()
            if self.isFloating != True:
                jump.setZ(jumpForce)
                self.isFloating = True
            elif self.isFloating == True:
                jump.setZ(0.0)
                #self.game.isFloating = False

        playerBody.node().setActive(True)
        playerBody.node().applyCentralForce(speed)
        playerBody.node().applyCentralImpulse(jump)
Example #21
0
	def contact_made(self):
		result = self.__game.world.contactTestPair(self.np.node(),self.__game.eve.currentControllerNode)
		if inputState.isSet('forward') and self.name.find('Fall') < 0:
			self.__game.taskMgr.remove(self.name)
			return
		if len(result.getContacts()) > 0:
			if len(self.__game.taskMgr.getTasksNamed(self.name)) == 0 and self.name.find('Fall') < 0:
				p_x = self.np.getX()
				p_y = self.np.getY()
				p_z = self.np.getZ()
				a_x = self.__game.eve.currentNP.getX()
				a_y = self.__game.eve.currentNP.getY()
				a_z = self.__game.eve.currentNP.getZ()

				dx = a_x - p_x
				dy = a_y - p_y
				dz = a_z - p_z
				self.__game.taskMgr.add(self.sync_movement,self.name, extraArgs=[dx,dy,dz],appendTask=True)
				self.__game.tasks.append(self.name)
			elif len(self.__game.taskMgr.getTasksNamed(self.name)) == 0 and self.name.find('Fall') >= 0:
				start = globalClock.getRealTime()
				self.__game.taskMgr.add(self.fall_countdown,self.name, extraArgs=[start],appendTask=True)
				self.__game.tasks.append(self.name)
				
		elif self.name.find('Fall') < 0:
			self.__game.taskMgr.remove(self.name)
Example #22
0
 def movementTask(self, task):
     if not inputState.isSet('jump') and not base.localAvatar.walkControls.isAirborne and inputState.isSet('forward') or inputState.isSet('reverse') or inputState.isSet('slideLeft') or inputState.isSet('slideRight'):
         if base.localAvatar.getAnimState() != 'run':
             base.localAvatar.setAnimState('run')
             base.localAvatar.playMovementSfx('run')
             self.mg.sendUpdate('runningAvatar', [base.localAvatar.doId])
     elif inputState.isSet('jump') or base.localAvatar.walkControls.isAirborne:
         if base.localAvatar.getAnimState() != 'jump':
             base.localAvatar.setAnimState('jump')
             base.localAvatar.playMovementSfx(None)
             self.mg.sendUpdate('jumpingAvatar', [base.localAvatar.doId])
     elif base.localAvatar.getAnimState() != 'neutral':
         base.localAvatar.setAnimState('neutral')
         base.localAvatar.playMovementSfx(None)
         self.mg.sendUpdate('standingAvatar', [base.localAvatar.doId])
     return Task.cont
Example #23
0
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        if not self.lifter.hasContact():
            # hack fix for falling through the floor:
            messenger.send("walkerIsOutOfWorld", [self.avatarNodePath])

        self._calcSpeeds()

        if __debug__:
            debugRunning = inputState.isSet("debugRunning")
            if debugRunning:
                self.speed*=4.0
                self.slideSpeed*=4.0
                self.rotationSpeed*=1.25

        if self.wantDebugIndicator:
            self.displayDebugInfo()
        # How far did we move based on the amount of time elapsed?
        dt=ClockObject.getGlobalClock().getDt()
        # Check to see if we're moving at all:
        if self.speed or self.slideSpeed or self.rotationSpeed:
            if self.stopThisFrame:
                distance = 0.0
                slideDistance = 0.0
                rotation = 0.0
                self.stopThisFrame = 0
            else:
                distance = dt * self.speed
                slideDistance = dt * self.slideSpeed
                rotation = dt * self.rotationSpeed

            # Take a step in the direction of our previous heading.
            self.vel=Vec3(Vec3.forward() * distance +
                          Vec3.right() * slideDistance)
            if self.vel != Vec3.zero():
                # rotMat is the rotation matrix corresponding to
                # our previous heading.
                rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
                step=rotMat.xform(self.vel)
                self.avatarNodePath.setFluidPos(Point3(self.avatarNodePath.getPos()+step))
            self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
            messenger.send("avatarMoving")
        else:
            self.vel.set(0.0, 0.0, 0.0)

        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
        self.__oldDt = dt

        try:
            self.worldVelocity = self.__oldPosDelta*(1/self.__oldDt)
        except:
            # divide by zero
            self.worldVelocity = 0

        return Task.cont
Example #24
0
	def update_camera(self,task):
		if self.camera_views['normal'] is True:
			self.normal_view()
		elif self.camera_views['top'] is True:
			self.top_view()
		elif self.camera_views['right'] is True:
			self.right_view()
		elif self.camera_views['left'] is True:
			self.left_view()
		elif self.camera_views['first_person'] is True:
			self.first_person()
			if inputState.isSet('camera_up'):
				if base.camera.getP() < 45:
					base.camera.setP(base.camera.getP() + 1)
			if inputState.isSet('camera_down'):
				if base.camera.getP() > -90:
					base.camera.setP(base.camera.getP() - 1)
		return task.cont
Example #25
0
 def trackAnimToSpeed(self, task):
     speed, rotSpeed, slideSpeed = self.controlManager.getSpeeds()
     if speed != 0.0 or rotSpeed != 0.0 or inputState.isSet('jump'):
         if not self.movingFlag:
             self.movingFlag = 1
             self.stopLookAround()
     elif self.movingFlag:
         self.movingFlag = 0
         self.startLookAround()
     if self.movingFlag or self.hp <= 0:
         self.wakeUp()
     elif not self.sleepFlag:
         now = globalClock.getFrameTime()
         if now - self.lastMoved > self.sleepTimeout:
             self.gotoSleep()
     state = None
     if self.sleepFlag:
         state = 'Sleep'
     elif self.hp > 0:
         state = 'Happy'
     else:
         state = 'Sad'
     if state != self.lastState:
         self.lastState = state
         self.b_setAnimState(state, self.animMultiplier)
         if state == 'Sad':
             self.setWalkSpeedSlow()
         else:
             self.setWalkSpeedNormal()
     if self.cheesyEffect == OTPGlobals.CEFlatProfile or self.cheesyEffect == OTPGlobals.CEFlatPortrait:
         needH = None
         if rotSpeed > 0.0:
             needH = -10
         elif rotSpeed < 0.0:
             needH = 10
         elif speed != 0.0:
             needH = 0
         if needH != None and self.lastNeedH != needH:
             node = self.getGeomNode().getChild(0)
             lerp = Sequence(LerpHprInterval(node, 0.5, Vec3(needH, 0, 0), blendType='easeInOut'), name='cheesy-lerp-hpr', autoPause=1)
             lerp.start()
             self.lastNeedH = needH
     else:
         self.lastNeedH = None
     action = self.setSpeed(speed, rotSpeed)
     if action != self.lastAction:
         self.lastAction = action
         if self.emoteTrack:
             self.emoteTrack.finish()
             self.emoteTrack = None
         if action == OTPGlobals.WALK_INDEX or action == OTPGlobals.REVERSE_INDEX:
             self.walkSound()
         elif action == OTPGlobals.RUN_INDEX:
             self.runSound()
         else:
             self.stopSound()
     return Task.cont
Example #26
0
 def trackAnimToSpeed(self, task):
     speed, rotSpeed, slideSpeed = self.controlManager.getSpeeds()
     if (speed != 0.0) or (rotSpeed != 0.0):
         if inputState.isSet('jump') and (not self.movingFlag):
             self.movingFlag = 1
             self.stopLookAround()
         elif (not inputState.isSet('jump')) and self.movingFlag:
             self.movingFlag = 0
             self.startLookAround()
     action = self.setSpeed(speed, rotSpeed)
     if action != self.lastAction:
         self.lastAction = action
         self.stopSound()
         if (action == WALK_INDEX) or (action == REVERSE_INDEX):
             self.walkSound()
         elif action == RUN_INDEX:
             self.runSound()
     return Task.cont
Example #27
0
	def processEveInput(self):
		if self.currentControllerNode.isOnGround() is True:	
			self.speed = Vec3(0, 0, 0)
        		self.omega = 0.0
		
        		if inputState.isSet('forward'):
				if self.state['rolling'] == True:
					self.speed.setY( Eve.INITIAL_ROLL_SPEED)
				else:
					self.speed.setY( Eve.RUNNING_SPEED)
					self.currentNode.setP(15)
        		if inputState.isSet('backwards'):
				if self.state['rolling'] == True:
					self.speed.setY( Eve.INITIAL_ROLL_SPEED - 300)
				else:
					self.speed.setY(-1 * Eve.RUNNING_SPEED - 10)
        		if inputState.isSet('turnLeft'):
				self.omega = Eve.OMEGA
				if self.speed.getY() == 0:
					self.currentNode.setR(0)
				else:
					self.currentNode.setR(15)
        		if inputState.isSet('turnRight'): 
				self.omega = Eve.OMEGA * -1 
				if self.speed.getY() == 0:
					self.currentNode.setR(0)
				else:
					self.currentNode.setR(-15)
        	self.currentControllerNode.setAngularMovement(self.omega)

		if self.currentControllerNode.isOnGround() is False:
        		self.currentControllerNode.setAngularMovement(0.0)
			self.currentControllerNode.setLinearMovement(self.speed, True)
			self.currentNode.setR(0)

		if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() == 'jump':
			self.currentNode.setR(0)
			self.currentControllerNode.setAngularMovement(0.0)
        		self.currentControllerNode.setLinearMovement(0.0, True)

		if self.currentControllerNode.isOnGround() is True and self.currentNode.getCurrentAnim() != 'jump':
			self.currentControllerNode.setAngularMovement(self.omega)
        		self.currentControllerNode.setLinearMovement(self.speed, True)
 def processInput(self, dt):
   force = Vec3(0, 0, 0)
   torque = Vec3(0, 0, 0)
   #print self.pTo.getY()
   if inputState.isSet('forward'):
     if(self.pTo.getZ() < 40):
       self.pTo.addZ(0.5)
   if inputState.isSet('reverse'):
     if(self.pTo.getZ() > 0 ):
       self.pTo.addZ(-0.5)
   if inputState.isSet('left'):
     if(self.pTo.getY() < 100):
       self.pTo.addY(0.5)
       self.arrow.setScale(self.arrow.getSx(),self.arrow.getSy()-0.006,self.arrow.getSz())
   if inputState.isSet('right'):
     if(self.pTo.getY() > 60):
       self.pTo.addY(-0.5)
       self.arrow.setScale(self.arrow.getSx(),self.arrow.getSy()+0.006,self.arrow.getSz())
       
   self.arrow.lookAt(self.pTo)
Example #29
0
    def processInputOutZero(self, dt):
        speed = Vec3(0, 0, 0)
        # torque = Vec3(0, 0, 0)

        if inputState.isSet('forward'):
            speed.setX(1.0)
        if inputState.isSet('reverse'):
            speed.setX(-1.0)
        if inputState.isSet('left'):
            speed.setY(1.0)
        if inputState.isSet('right'):
            speed.setY(-1.0)

        speed *= 6.0
        # torque *= 10.0

        # speed = render.getRelativeVector(self.boxNP, speed)
        # torque = render.getRelativeVector(self.boxNP, torque)
        for i in range(100):
            # #print "a"
            self.characterNP.node().setLinearMovement(speed, True)
Example #30
0
    def postUpdate(self):
        planet = Point3.zero()
        normal = Vec3(self.playernp.getX() - planet.getX(), self.playernp.getY() - planet.getY(), self.playernp.getZ() - planet.getZ())
        normal.normalize()
        fwd = render.getRelativePoint(self.playernp, Vec3(0, 1, 0))
        self.playernp.headsUp(fwd, normal)

        self.__currentPos = self.playernp.getPos()

        #player movement
        #space physcis
        #speed = self.playernp.node().getLinearVelocity()
        #normal physcis
        speed = Vec3(0, 0, 0)
        omega = 0.0
        v = 5.8
        if inputState.isSet('forward'): speed.setY(v)
        if inputState.isSet('reverse'): speed.setY(-v)
        if inputState.isSet('left'):    speed.setX(-v)
        if inputState.isSet('right'):   speed.setX(v)

        if inputState.isSet('flyUp'):   speed.setZ( 2.0)
        if inputState.isSet('flyDown'):   speed.setZ( -2.0)

        if inputState.isSet('turnLeft'):  omega =  40.0
        if inputState.isSet('turnRight'): omega = -40.0

        self.playernp.setH(self.playernp, omega * globalClock.getDt())

        globalVel = self.playernp.getQuat(render).xform(speed) * globalClock.getDt()

        normalVel = Vec3(globalVel)
        normalVel.normalize()

        if globalVel != Vec3():
            globalVelDir = Vec3(globalVel)
            globalVelDir.normalize()

            fn = Vec3(0.0, 0.0, 0.0)
            fn.normalize()

            velDot = 1.0 - globalVelDir.angleDeg(fn) / 180.0
            if velDot < 0.5:
                self.__currentPos -= Vec3(fn.x * globalVel.x, fn.y * globalVel.y, globalVel.z * globalVel.y) * velDot

            globalVel *= velDot

        self.__currentPos += globalVel

        self.playernp.setPos(self.__currentPos)
Example #31
0
    def setWASDTurn(self, turn):
        self.__WASDTurn = turn

        if not self.isEnabled:
            return
        
        turnLeftWASDSet = inputState.isSet("turnLeft", inputSource=inputState.WASD)
        turnRightWASDSet = inputState.isSet("turnRight", inputSource=inputState.WASD)
        slideLeftWASDSet = inputState.isSet("slideLeft", inputSource=inputState.WASD)
        slideRightWASDSet = inputState.isSet("slideRight", inputSource=inputState.WASD)

        for token in self.WASDTurnTokens:
            token.release()

        if turn:
            self.WASDTurnTokens = (
                inputState.watchWithModifiers("turnLeft", "a", inputSource=inputState.WASD),
                inputState.watchWithModifiers("turnRight", "d", inputSource=inputState.WASD),
                )

            inputState.set("turnLeft", slideLeftWASDSet, inputSource=inputState.WASD)
            inputState.set("turnRight", slideRightWASDSet, inputSource=inputState.WASD)

            inputState.set("slideLeft", False, inputSource=inputState.WASD)
            inputState.set("slideRight", False, inputSource=inputState.WASD)

        else:
            self.WASDTurnTokens = (
                inputState.watchWithModifiers("slideLeft", "a", inputSource=inputState.WASD),
                inputState.watchWithModifiers("slideRight", "d", inputSource=inputState.WASD),
                )

            inputState.set("slideLeft", turnLeftWASDSet, inputSource=inputState.WASD)
            inputState.set("slideRight", turnRightWASDSet, inputSource=inputState.WASD)
                
            inputState.set("turnLeft", False, inputSource=inputState.WASD)
            inputState.set("turnRight", False, inputSource=inputState.WASD)
                
Example #32
0
    def update(self, task):

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

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

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

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

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

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

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

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

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

        return task.cont
    def setWASDTurn(self, turn):
        self.__WASDTurn = turn
        if not self.isEnabled:
            return
        keymap = settings.get('keymap', {})
        turnLeftWASDSet = inputState.isSet('turnLeft', inputSource=inputState.WASD)
        turnRightWASDSet = inputState.isSet('turnRight', inputSource=inputState.WASD)
        slideLeftWASDSet = inputState.isSet('slideLeft', inputSource=inputState.WASD)
        slideRightWASDSet = inputState.isSet('slideRight', inputSource=inputState.WASD)
        for token in self.WASDTurnTokens:
            token.release()

        if turn:
            self.WASDTurnTokens = (inputState.watchWithModifiers('turnLeft', keymap.get('MOVE_LEFT', base.MOVE_LEFT), inputSource=inputState.WASD), inputState.watchWithModifiers('turnRight', keymap.get('MOVE_RIGHT', base.MOVE_RIGHT), inputSource=inputState.WASD))
            inputState.set('turnLeft', slideLeftWASDSet, inputSource=inputState.WASD)
            inputState.set('turnRight', slideRightWASDSet, inputSource=inputState.WASD)
            inputState.set('slideLeft', False, inputSource=inputState.WASD)
            inputState.set('slideRight', False, inputSource=inputState.WASD)
        else:
            self.WASDTurnTokens = (inputState.watchWithModifiers('slideLeft', keymap.get('MOVE_LEFT', base.MOVE_LEFT), inputSource=inputState.WASD), inputState.watchWithModifiers('slideRight', keymap.get('MOVE_RIGHT', base.MOVE_RIGHT), inputSource=inputState.WASD))
            inputState.set('slideLeft', turnLeftWASDSet, inputSource=inputState.WASD)
            inputState.set('slideRight', turnRightWASDSet, inputSource=inputState.WASD)
            inputState.set('turnLeft', False, inputSource=inputState.WASD)
            inputState.set('turnRight', False, inputSource=inputState.WASD)
 def handleAvatarControls(self, task):
     if not self.lifter.hasContact():
         messenger.send('walkerIsOutOfWorld', [self.avatarNodePath])
     forward = inputState.isSet('forward')
     reverse = inputState.isSet('reverse')
     turnLeft = inputState.isSet('turnLeft') or inputState.isSet(
         'slideLeft')
     turnRight = inputState.isSet('turnRight') or inputState.isSet(
         'slideRight')
     slideLeft = inputState.isSet('slideLeft')
     slideRight = inputState.isSet('slideRight')
     if base.localAvatar.getAutoRun():
         forward = 1
         reverse = 0
     self.speed = forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed
     self.slideSpeed = reverse and slideLeft and -self.avatarControlReverseSpeed * 0.75 or reverse and slideRight and self.avatarControlReverseSpeed * 0.75 or slideLeft and -self.avatarControlForwardSpeed * 0.75 or slideRight and self.avatarControlForwardSpeed * 0.75
     self.rotationSpeed = not (slideLeft or slideRight) and (
         turnLeft and self.avatarControlRotateSpeed
         or turnRight and -self.avatarControlRotateSpeed)
     if self.wantDebugIndicator:
         self.displayDebugInfo()
     dt = ClockObject.getGlobalClock().getDt()
     self.moving = self.speed or self.slideSpeed or self.rotationSpeed
     if self.moving:
         if self.stopThisFrame:
             distance = 0.0
             slideDistance = 0.0
             rotation = 0.0
             self.stopThisFrame = 0
         else:
             distance = dt * self.speed
             slideDistance = dt * self.slideSpeed
             rotation = dt * self.rotationSpeed
         self.vel = Vec3(Vec3.forward() * distance +
                         Vec3.right() * slideDistance)
         if self.vel != Vec3.zero():
             rotMat = Mat3.rotateMatNormaxis(self.avatarNodePath.getH(),
                                             Vec3.up())
             step = rotMat.xform(self.vel)
             self.avatarNodePath.setFluidPos(
                 Point3(self.avatarNodePath.getPos() + step))
         self.avatarNodePath.setH(self.avatarNodePath.getH() + rotation)
         messenger.send('avatarMoving')
     else:
         self.vel.set(0.0, 0.0, 0.0)
     return task.cont
Example #35
0
 def isSubjectMoving(self):
     if 'localAvatar' in __builtins__:
         autoRun = localAvatar.getAutoRun()
     else:
         autoRun = False
     return (inputState.isSet('forward') or inputState.isSet('reverse') or
             inputState.isSet('turnRight') or inputState.isSet('turnLeft')
             or inputState.isSet('slideRight')
             or inputState.isSet('slideLeft')
             or autoRun) and self.subject.controlManager.isEnabled
Example #36
0
    def processInput(self, dt):
        speed = Vec3(0, 0, 0)
        omega = 0.0

        v = 5.0

        if inputState.isSet('run'): v = 15.0

        if inputState.isSet('forward'): speed.setY(v)
        if inputState.isSet('reverse'): speed.setY(-v)
        if inputState.isSet('left'): speed.setX(-v)
        if inputState.isSet('right'): speed.setX(v)

        if inputState.isSet('flyUp'): speed.setZ(2.0)
        if inputState.isSet('flyDown'): speed.setZ(-2.0)

        if inputState.isSet('turnLeft'): omega = 120.0
        if inputState.isSet('turnRight'): omega = -120.0

        self.character.setAngularMovement(omega)
        self.character.setLinearMovement(speed, True)
Example #37
0
 def sleepSwimTest(self, task):
     now = globalClock.getFrameTime()
     speed, rotSpeed, slideSpeed = self.controlManager.getSpeeds()
     if speed != 0.0 or rotSpeed != 0.0 or inputState.isSet('jump'):
         if not self.swimmingFlag:
             self.swimmingFlag = 1
     elif self.swimmingFlag:
         self.swimmingFlag = 0
     if self.swimmingFlag or self.hp <= 0:
         self.wakeUp()
     elif not self.sleepFlag:
         now = globalClock.getFrameTime()
         if now - self.lastMoved > self.swimTimeout:
             self.swimTimeoutAction()
             return Task.done
     return Task.cont
Example #38
0
 def _calcSpeeds(self):
     forward = inputState.isSet('forward')
     reverse = inputState.isSet('reverse')
     if not inputState.isSet('turnLeft'):
         turnLeft = inputState.isSet('slideLeft')
         turnRight = inputState.isSet('turnRight') or inputState.isSet('slideRight')
         forward = base.localAvatar.getAutoRun() and 1
         reverse = 0
     self.speed = forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed
     self.slideSpeed = 0.0
     self.rotationSpeed = turnLeft and self.avatarControlRotateSpeed or turnRight and -self.avatarControlRotateSpeed
Example #39
0
    def processInput(self):
        throttleChange = 0.0

        if inputState.isSet('forward'): self.gimbalY = 10
        if inputState.isSet('reverse'): self.gimbalY = -10
        if inputState.isSet('left'):    self.gimbalX = 10
        if inputState.isSet('right'):   self.gimbalX = -10
        if inputState.isSet('turnLeft'):  throttleChange = -1.0
        if inputState.isSet('turnRight'): throttleChange = 1.0

        self.throttle += throttleChange / 100.0
        self.throttle = min(max(self.throttle, 0), 1)
Example #40
0
    def inputProcessingTask(self, task):
        # Camera Control Keys
        if inputState.isSet('cameraHigher'):
            self.cameraHeight += 0.1
        if inputState.isSet('cameraLower'):
            self.cameraHeight -= 0.1

        move = Vec3(0, 0, 0)
        turningAngle = 0.0

        # Character Movements
        if inputState.isSet('forward'):
            move.setY(PLAYER_SPEED)
            self.isMoving = True
        elif inputState.isSet('reverse'):
            move.setY(-PLAYER_SPEED)
            self.isMoving = True

        if inputState.isSet('turnLeft'):
            turningAngle = 120.0
            self.isMoving = True
        elif inputState.isSet('turnRight'):
            turningAngle = -120.0
            self.isMoving = True

        if self.isMoving is False:
            self.player.setPose(STANDING)
        else:
            self.player.setPose(WALKING)
        self.isMoving = False

        if inputState.isSet('jump'):
            self.player.setPose(JUMPING)
            if self.booosted:
                self.player.getControllerNode().setMaxJumpHeight(JUMP_HEIGHT *
                                                                 2)
                self.player.getControllerNode().setJumpSpeed(JUMP_SPEED * 2)
            else:
                self.player.getControllerNode().setMaxJumpHeight(JUMP_HEIGHT)
                self.player.getControllerNode().setJumpSpeed(JUMP_SPEED)
            self.player.getControllerNode().doJump()

        if self.pushed:
            move.setY(TYPE_1_ENEMY_PUSH_DISTANCE)
            self.pushed = False
        self.player.getControllerNode().setLinearMovement(move, True)
        self.player.getControllerNode().setAngularMovement(turningAngle)
        return task.cont
 def handleAvatarControls(self, task):
     forward = inputState.isSet('forward')
     reverse = inputState.isSet('reverse')
     turnLeft = inputState.isSet('turnLeft')
     turnRight = inputState.isSet('turnRight')
     slideLeft = inputState.isSet('slideLeft')
     slideRight = inputState.isSet('slideRight')
     levitateUp = inputState.isSet('levitateUp')
     levitateDown = inputState.isSet('levitateDown')
     run = inputState.isSet('run') and self.runMultiplier or 1.0
     if base.localAvatar.getAutoRun():
         forward = 1
         reverse = 0
     self.speed = forward and self.avatarControlForwardSpeed or reverse and -self.avatarControlReverseSpeed
     self.liftSpeed = levitateUp and self.avatarControlForwardSpeed or levitateDown and -self.avatarControlReverseSpeed
     self.slideSpeed = slideLeft and -self.avatarControlForwardSpeed or slideRight and self.avatarControlForwardSpeed
     self.rotationSpeed = turnLeft and self.avatarControlRotateSpeed or turnRight and -self.avatarControlRotateSpeed
     if self.wantDebugIndicator:
         self.displayDebugInfo()
     if self.speed or self.liftSpeed or self.slideSpeed or self.rotationSpeed:
         dt = ClockObject.getGlobalClock().getDt()
         distance = dt * self.speed * run
         lift = dt * self.liftSpeed * run
         slideDistance = dt * self.slideSpeed * run
         rotation = dt * self.rotationSpeed
         self.vel = Vec3(Vec3.forward() * distance + Vec3.up() * lift +
                         Vec3.right() * slideDistance)
         if self.vel != Vec3.zero():
             rotMat = Mat3.rotateMatNormaxis(self.avatarNodePath.getH(),
                                             Vec3.up())
             step = rotMat.xform(self.vel)
             self.avatarNodePath.setFluidPos(
                 Point3(self.avatarNodePath.getPos() + step))
         self.avatarNodePath.setH(self.avatarNodePath.getH() + rotation)
         messenger.send('avatarMoving')
     else:
         self.vel.set(0.0, 0.0, 0.0)
     return Task.cont
    def processInput(self, dt):
        speed = Vec3(0, 0, 0)
        omega = 0.0

        if inputState.isSet('forward'): speed.setY( 3.0)
        if inputState.isSet('reverse'): speed.setY(-3.0)
        if inputState.isSet('left'):    speed.setX(-3.0)
        if inputState.isSet('right'):   speed.setX( 3.0)
        if inputState.isSet('turnLeft'):  omega =  120.0
        if inputState.isSet('turnRight'): omega = -120.0
		
	if (inputState.isSet('forward')!=0) or (inputState.isSet('reverse')!=0) or (inputState.isSet('left')!=0) or (inputState.isSet('right')!=0):
            if self.isMoving is False:
                self.actorNP.loop("walk")
                self.isMoving = True
        else:
            if self.isMoving:
                self.actorNP.stop()
                self.isMoving = False


        self.character.setAngularMovement(omega)
        self.character.setLinearMovement(speed, True)
Example #43
0
 def input2forces(
         self, car_input, joystick_mgr, is_drifting, player_car_idx,
         curr_time,
         #acc_key, brk_key,
         a_i):
     keys = ['forward', 'rear', 'left', 'right']
     keys = [key + str(player_car_idx) for key in keys]
     joystick = not any(inputState.isSet(key) for key in keys)
     if a_i or not joystick or not self.__is_player:
         return self.input2forces_discrete(
             car_input, joystick_mgr, is_drifting, player_car_idx,
             curr_time)
     else:
         return self.input2forces_analog(
             car_input, joystick_mgr, is_drifting, player_car_idx,
             curr_time,
             #acc_key, brk_key
         )
Example #44
0
    def useBasicPlayerMovement(self, dt):
        """This sets up a basic movement for the playercontroller"""

        # get the player
        player = self.engine.GameObjects["player"]
        speed = Vec3(0, 0, 0)
        omega = 0.0

        if inputState.isSet('forward'): speed.setY(player.runSpeed)
        if inputState.isSet('reverse'): speed.setY(-player.runSpeed)
        if inputState.isSet('left'): speed.setX(-player.runSpeed)
        if inputState.isSet('right'): speed.setX(player.runSpeed)
        if inputState.isSet('turnLeft'): omega = player.turnSpeed
        if inputState.isSet('turnRight'): omega = -player.turnSpeed
        if inputState.isSet('space'):
            self.doPlayerJump(player.bulletBody.node())
        if inputState.isSet('ctrl'): self.doPlayerCrouch(player)

        #player.bulletBody.node().setAngularMovement(omega)
        player.bulletBody.node().setLinearMovement(speed, True)
Example #45
0
 def monitor(self, foo):
     #assert self.debugPrint("monitor()")
     #if 1:
     #    airborneHeight=self.avatar.getAirborneHeight()
     #    onScreenDebug.add("airborneHeight", "% 10.4f"%(airborneHeight,))
     if 0:
         onScreenDebug.add("InputState forward", "%d"%(inputState.isSet("forward")))
         onScreenDebug.add("InputState reverse", "%d"%(inputState.isSet("reverse")))
         onScreenDebug.add("InputState turnLeft", "%d"%(inputState.isSet("turnLeft")))
         onScreenDebug.add("InputState turnRight", "%d"%(inputState.isSet("turnRight")))
         onScreenDebug.add("InputState slideLeft", "%d"%(inputState.isSet("slideLeft")))
         onScreenDebug.add("InputState slideRight", "%d"%(inputState.isSet("slideRight")))
     return Task.cont
Example #46
0
    def processInput(self, dt):
        speed = Vec3(0, 0, 0)
        omega = 0.0

        if inputState.isSet('forward'): speed.setY(2.0)
        if inputState.isSet('reverse'): speed.setY(-2.0)
        if inputState.isSet('left'): speed.setX(-2.0)
        if inputState.isSet('right'): speed.setX(2.0)
        if inputState.isSet('turnLeft'): omega = 120.0
        if inputState.isSet('turnRight'): omega = -120.0

        self.player.setAngularMovement(omega)
        self.player.setLinearMovement(speed, True)
Example #47
0
    def process_input(self, dt):
        speed = LVector3(0, 0, 0)
        omega = 0.0

        if inputState.isSet('forward'): speed.y = 2.0
        if inputState.isSet('reverse'): speed.y = -2.0
        if inputState.isSet('left'): speed.x = -2.0
        if inputState.isSet('right'): speed.x = 2.0
        if inputState.isSet('turnLeft'): omega = 120.0
        if inputState.isSet('turnRight'): omega = -120.0

        self.character.set_angular_movement(omega)
        self.character.set_linear_movement(speed, True)
Example #48
0
        def ProcessInput(dt):

            engineForce = 0.0
            self.steeringClamp = 35.0
            self.steeringIncrement = 70

            #Get the vehicle's current speed
            self.carspeed = self.Car_sim.getCurrentSpeedKmHour()

            #Reset the steering
            if not inputState.isSet("L") and not inputState.isSet("R"):

                if self.steering < 0.00:
                    self.steering = self.steering + 0.6
                    if self.steering > 0.00:
                        self.steering = self.steering - 0.6

                    if self.steering < 1.0 and self.steering > -1.0:
                        self.steering = 0

            if inputState.isSet("F"):
                engineForce = 35

            if inputState.isSet("B"):
                engineForce = -35

            #Left
            if inputState.isSet("L"):
                if self.steering < 0.0:
                    #This makes the steering reset at the correct speed when turning from right to left
                    self.steering += dt * self.steeringIncrement + 0.6
                    self.steering = min(self.steering, self.steeringClamp)
                else:
                    #Normal steering
                    self.steering += dt * self.steeringIncrement
                    self.steering = min(self.steering, self.steeringClamp)

#Right
            if inputState.isSet("R"):
                if self.steering > 0.0:
                    #This makes the steering reset at the correct speed when turning from left to right
                    self.steering -= dt * self.steeringIncrement + 0.6
                    self.steering = max(self.steering, -self.steeringClamp)
                else:
                    #Normal steering
                    self.steering -= dt * self.steeringIncrement
                    self.steering = max(self.steering, -self.steeringClamp)

            #Apply forces to wheels
            self.Car_sim.applyEngineForce(engineForce, 0)
            self.Car_sim.applyEngineForce(engineForce, 3)
Example #49
0
  def processInput(self, dt):
    force = Vec3(0, 0, 0)
    torque = Vec3(0, 0, 0)

    if inputState.isSet('forward'): force.setY( 1.0)
    if inputState.isSet('reverse'): force.setY(-1.0)
    if inputState.isSet('left'):    force.setX(-1.0)
    if inputState.isSet('right'):   force.setX( 1.0)
    if inputState.isSet('turnLeft'):  torque.setZ( 1.0)
    if inputState.isSet('turnRight'): torque.setZ(-1.0)

    force *= 30.0
    torque *= 10.0

    self.boxNP.node().applyCentralForce(force)
    self.boxNP.node().applyTorque(torque)
    def process_input(self, dt):
        force = LVector3(0, 0, 0)
        torque = LVector3(0, 0, 0)

        if inputState.isSet('forward'): force.y = 1.0
        if inputState.isSet('reverse'): force.y = -1.0
        if inputState.isSet('left'): force.x = -1.0
        if inputState.isSet('right'): force.x = 1.0
        if inputState.isSet('turnLeft'): torque.z = 1.0
        if inputState.isSet('turnRight'): torque.z = -1.0

        force *= 30.0
        torque *= 10.0

        self.boxNP.node().apply_central_force(force)
        self.boxNP.node().apply_torque(torque)
Example #51
0
    def keyboard_watcher(self, task):
        m = Vec3(0, 0, 0)
        if inputState.isSet('forward'):
            m.setY(1)
        elif inputState.isSet('back'):
            m.setY(-1)
        if inputState.isSet('left'):
            m.setX(-1)
        elif inputState.isSet('right'):
            m.setX(1)
        if inputState.isSet('up'):
            m.setZ(1)
        elif inputState.isSet('down'):
            m.setZ(-1)
        self.char.move(m)

        return task.cont
Example #52
0
    def _calcSpeeds(self):
        # get the button states:
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft") or inputState.isSet("slideLeft")
        turnRight = inputState.isSet("turnRight") or inputState.isSet("slideRight")

        # Check for Auto-Run
        if base.localAvatar.getAutoRun():
            forward = 1
            reverse = 0
        
        # Determine what the speeds are based on the buttons:
        self.speed=(forward and self.avatarControlForwardSpeed or
                    reverse and -self.avatarControlReverseSpeed)
        self.slideSpeed=0.
        self.rotationSpeed=(
            (turnLeft and self.avatarControlRotateSpeed) or
            (turnRight and -self.avatarControlRotateSpeed))
Example #53
0
    def processInput(self, dt):
        force = Vec3(0, 0, 0)
        torque = Vec3(0, 0, 0)

        if inputState.isSet('forward'): force.setY(1.0)
        if inputState.isSet('reverse'): force.setY(-1.0)
        if inputState.isSet('left'): force.setX(-1.0)
        if inputState.isSet('right'): force.setX(1.0)
        if inputState.isSet('turnLeft'): torque.setZ(1.0)
        if inputState.isSet('turnRight'): torque.setZ(-1.0)

        force *= 30.0
        torque *= 10.0

        force = render.getRelativeVector(self.allTheThingsNP[0], force)
        torque = render.getRelativeVector(self.allTheThingsNP[0], torque)

        self.allTheThingsNP[0].node().setActive(True)
        self.allTheThingsNP[0].node().applyCentralForce(force)
        self.allTheThingsNP[0].node().applyTorque(torque)
    def _calcSpeeds(self):
        forward = inputState.isSet('forward')
        reverse = inputState.isSet('reverse')
        if not inputState.isSet('turnLeft'):
            pass
        turnLeft = inputState.isSet('slideLeft')
        if not inputState.isSet('turnRight'):
            pass
        turnRight = inputState.isSet('slideRight')
        if base.localAvatar.getAutoRun():
            forward = 1
            reverse = 0

        if (forward or self.avatarControlForwardSpeed) and reverse:
            pass
        self.speed = -(self.avatarControlReverseSpeed)
        self.slideSpeed = 0.0
        if (turnLeft or self.avatarControlRotateSpeed) and turnRight:
            pass
        self.rotationSpeed = -(self.avatarControlRotateSpeed)
Example #55
0
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        # get the button states:
        run = inputState.isSet("run")
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft")
        turnRight = inputState.isSet("turnRight")
        slideLeft = inputState.isSet("slideLeft")
        slideRight = inputState.isSet("slideRight")
        jump = inputState.isSet("jump")

        # Check for Auto-Run
        #if 'localAvatar' in __builtins__:
        #    if base.localAvatar and base.localAvatar.getAutoRun():
        #        forward = 1
        #        reverse = 0

        # Determine what the speeds are based on the buttons:
        self.speed = (forward and self.avatarControlForwardSpeed
                      or reverse and -self.avatarControlReverseSpeed)
        # Slide speed is a scaled down version of forward speed
        # Note: you can multiply a factor in here if you want slide to
        # be slower than normal walk/run. Let's try full speed.
        #self.slideSpeed=(slideLeft and -self.avatarControlForwardSpeed*0.75 or
        #                 slideRight and self.avatarControlForwardSpeed*0.75)
        self.slideSpeed = (
            reverse and slideLeft and -self.avatarControlReverseSpeed * 0.75
            or reverse and slideRight and self.avatarControlReverseSpeed * 0.75
            or slideLeft and -self.avatarControlForwardSpeed * 0.75
            or slideRight and self.avatarControlForwardSpeed * 0.75)
        self.rotationSpeed = not (slideLeft or slideRight) and (
            (turnLeft and self.avatarControlRotateSpeed) or
            (turnRight and -self.avatarControlRotateSpeed))

        if self.speed and self.slideSpeed:
            self.speed *= GravityWalker.DiagonalFactor
            self.slideSpeed *= GravityWalker.DiagonalFactor

        debugRunning = inputState.isSet("debugRunning")
        if (debugRunning):
            self.speed *= base.debugRunningMultiplier
            self.slideSpeed *= base.debugRunningMultiplier
            self.rotationSpeed *= 1.25

        if self.needToDeltaPos:
            self.setPriorParentVector()
            self.needToDeltaPos = 0
        if self.wantDebugIndicator:
            self.displayDebugInfo()
        if self.lifter.isOnGround():
            if self.isAirborne:
                self.isAirborne = 0
                assert self.debugPrint("isAirborne 0 due to isOnGround() true")
                impact = self.lifter.getImpactVelocity()
                if impact < -30.0:
                    messenger.send("jumpHardLand")
                    self.startJumpDelay(0.3)
                else:
                    messenger.send("jumpLand")
                    if impact < -5.0:
                        self.startJumpDelay(0.2)
                    # else, ignore the little potholes.
            assert self.isAirborne == 0
            self.priorParent = Vec3.zero()
            if jump and self.mayJump:
                # The jump button is down and we're close
                # enough to the ground to jump.
                self.lifter.addVelocity(self.avatarControlJumpForce)
                messenger.send("jumpStart")
                self.isAirborne = 1
                assert self.debugPrint("isAirborne 1 due to jump")
        else:
            if self.isAirborne == 0:
                assert self.debugPrint(
                    "isAirborne 1 due to isOnGround() false")
            self.isAirborne = 1

        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
        # How far did we move based on the amount of time elapsed?
        self.__oldDt = ClockObject.getGlobalClock().getDt()
        dt = self.__oldDt

        # Check to see if we're moving at all:
        self.moving = self.speed or self.slideSpeed or self.rotationSpeed or (
            self.priorParent != Vec3.zero())
        if self.moving:
            distance = dt * self.speed
            slideDistance = dt * self.slideSpeed
            rotation = dt * self.rotationSpeed

            # Take a step in the direction of our previous heading.
            if distance or slideDistance or self.priorParent != Vec3.zero():
                # rotMat is the rotation matrix corresponding to
                # our previous heading.
                rotMat = Mat3.rotateMatNormaxis(self.avatarNodePath.getH(),
                                                Vec3.up())
                if self.isAirborne:
                    forward = Vec3.forward()
                else:
                    contact = self.lifter.getContactNormal()
                    forward = contact.cross(Vec3.right())
                    # Consider commenting out this normalize.  If you do so
                    # then going up and down slops is a touch slower and
                    # steeper terrain can cut the movement in half.  Without
                    # the normalize the movement is slowed by the cosine of
                    # the slope (i.e. it is multiplied by the sign as a
                    # side effect of the cross product above).
                    forward.normalize()
                self.vel = Vec3(forward * distance)
                if slideDistance:
                    if self.isAirborne:
                        right = Vec3.right()
                    else:
                        right = forward.cross(contact)
                        # See note above for forward.normalize()
                        right.normalize()
                    self.vel = Vec3(self.vel + (right * slideDistance))
                self.vel = Vec3(rotMat.xform(self.vel))
                step = self.vel + (self.priorParent * dt)
                self.avatarNodePath.setFluidPos(
                    Point3(self.avatarNodePath.getPos() + step))
            self.avatarNodePath.setH(self.avatarNodePath.getH() + rotation)
        else:
            self.vel.set(0.0, 0.0, 0.0)
        if self.moving or jump:
            messenger.send("avatarMoving")
        return Task.cont
Example #56
0
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        # get the button states:
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft")
        turnRight = inputState.isSet("turnRight")
        slideLeft = inputState.isSet("slideLeft")
        slideRight = inputState.isSet("slideRight")
        levitateUp = inputState.isSet("levitateUp")
        levitateDown = inputState.isSet("levitateDown")
        run = inputState.isSet("run") and self.runMultiplier.getValue() or 1.0

        # Check for Auto-Run
        if base.localAvatar.getAutoRun():
            forward = 1
            reverse = 0

        # Determine what the speeds are based on the buttons:
        self.speed=(
                (forward and self.avatarControlForwardSpeed or
                reverse and -self.avatarControlReverseSpeed))
        self.liftSpeed=(
                (levitateUp and self.avatarControlForwardSpeed or
                levitateDown and -self.avatarControlReverseSpeed))
        self.slideSpeed=(
                (slideLeft and -self.avatarControlForwardSpeed) or
                (slideRight and self.avatarControlForwardSpeed))
        self.rotationSpeed=(
                (turnLeft and self.avatarControlRotateSpeed) or
                (turnRight and -self.avatarControlRotateSpeed))

        if self.wantDebugIndicator:
            self.displayDebugInfo()

        # Check to see if we're moving at all:
        if self.speed or self.liftSpeed or self.slideSpeed or self.rotationSpeed:
            # How far did we move based on the amount of time elapsed?
            dt=ClockObject.getGlobalClock().getDt()
            distance = dt * self.speed * run
            lift = dt * self.liftSpeed * run
            slideDistance = dt * self.slideSpeed * run
            rotation = dt * self.rotationSpeed

            # Take a step in the direction of our previous heading.
            self.vel=Vec3(Vec3.forward() * distance +
                          Vec3.up() * lift +
                          Vec3.right() * slideDistance)
            if self.vel != Vec3.zero():
                # rotMat is the rotation matrix corresponding to
                # our previous heading.
                rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
                step=rotMat.xform(self.vel)
                self.avatarNodePath.setFluidPos(Point3(self.avatarNodePath.getPos()+step))
            self.avatarNodePath.setH(self.avatarNodePath.getH()+rotation)
            messenger.send("avatarMoving")
        else:
            self.vel.set(0.0, 0.0, 0.0)
        return Task.cont
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        if __debug__:
            if self.wantDebugIndicator:
                onScreenDebug.append("localAvatar pos = %s\n"%(
                    base.localAvatar.getPos().pPrintValues(),))
                onScreenDebug.append("localAvatar hpr = %s\n"%(
                    base.localAvatar.getHpr().pPrintValues(),))
        #assert self.debugPrint("handleAvatarControls(task=%s)"%(task,))
        physObject=self.actorNode.getPhysicsObject()
        contact=self.actorNode.getContactVector()

        # get the button states:
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("slideLeft") or inputState.isSet("turnLeft")
        turnRight = inputState.isSet("slideRight") or inputState.isSet("turnRight")
        slide = inputState.isSet("slide")
        slideLeft = 0
        slideRight = 0
        jump = inputState.isSet("jump")
        # Determine what the speeds are based on the buttons:

        # Check for Auto-Sailing
        if self.ship.getIsAutoSailing():
            forward = 1
            reverse = 0

        # How far did we move based on the amount of time elapsed?
        dt=ClockObject.getGlobalClock().getDt()

        if reverse or turnLeft or turnRight:
            # Reset Straight Sailing Bonus
            self.straightHeading = 0

        # Straight Sailing Acceleration Bonus
        straightSailDt += dt
        straightSailBonus = 0.0
        if straightSailDt > self.STRAIGHT_SAIL_BONUS_TIME / 2.0:
            straightSailBonus = (straightSailDt - (self.STRAIGHT_SAIL_BONUS_TIME / 2.0)) / self.STRAIGHT_SAIL_BONUS_TIME / 2.0
        straightSailBonus *= self.MAX_STRAIGHT_SAIL_BONUS
        straightSailBonus += 1.0

        print "##################"
        print straightSailBonus

        # this was causing the boat to get stuck moving forward or back
        if 0:
            if not hasattr(self, "sailsDeployed"):
                self.sailsDeployed = 0.0
            if forward and reverse:
                # Way anchor:
                self.__speed = 0.0
                physObject.setVelocity(Vec3.zero())
            elif forward:
                self.sailsDeployed += 0.25
                if self.sailsDeployed > 1.0:
                    self.sailsDeployed = 1.0
            elif reverse:
                self.sailsDeployed -= 0.25
                if self.sailsDeployed < -1.0:
                    self.sailsDeployed = -1.0
            self.__speed = self.ship.acceleration * self.sailsDeployed
        else:
            self.__speed=(forward and self.ship.acceleration) or \
                (reverse and -self.ship.reverseAcceleration)
            #self.__speed=(forward and min(dt*(self.__speed + self.ship.acceleration), self.ship.maxSpeed) or
            #        reverse and min(dt*(self.__speed - self.ship.reverseAcceleration), self.ship.maxReverseSpeed))

        avatarSlideSpeed=self.ship.acceleration*0.5
        #self.__slideSpeed=slide and (
        #        (turnLeft and -avatarSlideSpeed) or
        #        (turnRight and avatarSlideSpeed))
        self.__slideSpeed=(forward or reverse) and (
                (slideLeft and -avatarSlideSpeed) or
                (slideRight and avatarSlideSpeed))
        self.__rotationSpeed=not slide and (
                (turnLeft and self.ship.turnRate) or
                (turnRight and -self.ship.turnRate))

        # Add in Straight Sailing Multiplier
        self.__speed *= straightSailBonus

        # Enable debug turbo mode
        maxSpeed = self.ship.maxSpeed * straightSailBonus
        debugRunning = inputState.isSet("debugRunning")
        if debugRunning or base.localAvatar.getTurbo():
            self.__speed*=4.0
            self.__slideSpeed*=4.0
            self.__rotationSpeed*=1.25
            maxSpeed = self.ship.maxSpeed * 4.0

        #self.__speed*=4.0
        #self.__slideSpeed*=4.0
        #self.__rotationSpeed*=1.25
        #maxSpeed = self.ship.maxSpeed * 4.0

        #*#
        self.currentTurning += self.__rotationSpeed
        if self.currentTurning > self.ship.maxTurn:
            self.currentTurning = self.ship.maxTurn
        elif self.currentTurning < -self.ship.maxTurn:
            self.currentTurning = -self.ship.maxTurn
        if turnLeft or turnRight:
            mult = .9
        elif forward or reverse:
            mult = .82
        else:
            mult = .8
        self.currentTurning *= mult
        if self.currentTurning < 0.001 and self.currentTurning > -0.001:
            self.currentTurning = 0.0
        self.__rotationSpeed = self.currentTurning


        if self.wantDebugIndicator:
            self.displayDebugInfo()

        if self.needToDeltaPos:
            self.setPriorParentVector()
            self.needToDeltaPos = 0

        airborneHeight=self.getAirborneHeight()
        if airborneHeight > self.highMark:
            self.highMark = airborneHeight
            if __debug__:
                onScreenDebug.add("highMark", "% 10.4f"%(self.highMark,))
        #if airborneHeight < 0.1: #contact!=Vec3.zero():
        if 1:
            if (airborneHeight > self.avatarRadius*0.5
                    or physObject.getVelocity().getZ() > 0.0
                    ): # Check stair angles before changing this.
                # The avatar is airborne (maybe a lot or a tiny amount).
                self.isAirborne = 1
            else:
                # The avatar is very close to the ground (close
                # enough to be considered on the ground).
                if self.isAirborne and physObject.getVelocity().getZ() <= 0.0:
                    # the avatar has landed.
                    contactLength = contact.length()
                    if contactLength>self.__hardLandingForce:
                        messenger.send("shipJumpHardLand")
                    else:
                        messenger.send("shipJumpLand")
                    #self.priorParent.setVector(Vec3.zero())
                    self.isAirborne = 0
                elif jump:
                    #self.__jumpButton=0
                    messenger.send("shipJumpStart")
                    if 0:
                        # Jump away from walls and with with the slope normal.
                        jumpVec=Vec3(contact+Vec3.up())
                        #jumpVec=Vec3(rotAvatarToPhys.xform(jumpVec))
                        jumpVec.normalize()
                    else:
                        # Jump straight up, even if next to a wall.
                        jumpVec=Vec3.up()
                    jumpVec*=self.avatarControlJumpForce
                    physObject.addImpulse(Vec3(jumpVec))
                    self.isAirborne = 1 # Avoid double impulse before fully airborne.
                else:
                    self.isAirborne = 0
            if __debug__:
                onScreenDebug.add("isAirborne", "%d"%(self.isAirborne,))
        else:
            if contact!=Vec3.zero():
                # The avatar has touched something (but might
                # not be on the ground).
                contactLength = contact.length()
                contact.normalize()
                angle=contact.dot(Vec3.up())
                if angle>self.__standableGround:
                    # ...avatar is on standable ground.
                    if self.__oldContact==Vec3.zero():
                    #if self.__oldAirborneHeight > 0.1: #self.__oldContact==Vec3.zero():
                        # ...avatar was airborne.
                        self.jumpCount-=1
                        if contactLength>self.__hardLandingForce:
                            messenger.send("jumpHardLand")
                        else:
                            messenger.send("jumpLand")
                    elif jump:
                        self.jumpCount+=1
                        #self.__jumpButton=0
                        messenger.send("jumpStart")
                        jump=Vec3(contact+Vec3.up())
                        #jump=Vec3(rotAvatarToPhys.xform(jump))
                        jump.normalize()
                        jump*=self.avatarControlJumpForce
                        physObject.addImpulse(Vec3(jump))

        if contact!=self.__oldContact:
            # We must copy the vector to preserve it:
            self.__oldContact=Vec3(contact)
        self.__oldAirborneHeight=airborneHeight

        #------------------------------
        #debugTempH=self.avatarNodePath.getH()
        if __debug__:
            q1=self.avatarNodePath.getQuat()
            q2=physObject.getOrientation()
            q1.normalize()
            q2.normalize()
            assert q1.isSameDirection(q2) or (q1.getHpr() == q2.getHpr())
        assert self.avatarNodePath.getPos().almostEqual(
            physObject.getPosition(), 0.0001)
        #------------------------------

        # Check to see if we're moving at all:
        physVel = physObject.getVelocity()
        physVelLen = physVel.length()
        if (physVelLen!=0.
                or self.__speed
                or self.__slideSpeed
                or self.__rotationSpeed):
            distance = dt * self.__speed
            goForward = True
            if (distance < 0):
                goForward = False
            slideDistance = dt * self.__slideSpeed
            rotation = dt * self.__rotationSpeed

            # update pos:
            # Take a step in the direction of our previous heading.
            self.__vel=Vec3(
                Vec3.forward() * distance +
                Vec3.right() * slideDistance)

            # rotMat is the rotation matrix corresponding to
            # our previous heading.
            rotMat=Mat3.rotateMatNormaxis(
                self.avatarNodePath.getH(), Vec3.up())
            step=rotMat.xform(self.__vel)

            #newVector = self.acForce.getLocalVector()+Vec3(step)
            newVector = Vec3(step)
            #newVector=Vec3(rotMat.xform(newVector))
            #maxLen = maxSpeed
            if (goForward):
                maxLen = self.ship.acceleration
            else:
                maxLen = self.ship.reverseAcceleration
            if newVector.length() > maxLen:
                newVector.normalize()
                newVector *= maxLen


            if __debug__:
                onScreenDebug.add(
                    "newVector", newVector)
                onScreenDebug.add(
                    "newVector length", newVector.length())
            base.controlForce.setVector(newVector)
            assert base.controlForce.getLocalVector() == newVector
            assert base.controlForce.getPhysicsObject()
            assert base.controlForce.getPhysicsObject() == physObject


            #momentum = self.momentumForce.getLocalVector()
            #momentum *= 0.9
            #self.momentumForce.setVector(momentum)

            # update hpr:
            o=physObject.getOrientation()
            r=LRotationf()
            r.setHpr(Vec3(rotation, 0.0, 0.0))
            physObject.setOrientation(o*r)

            # sync the change:
            self.actorNode.updateTransform()
            #assert self.avatarNodePath.getH()==debugTempH-rotation
            messenger.send("avatarMoving")
        else:
            # even if there are no active inputs, we still might be moving
            assert physObject.getVelocity().length() == 0.
            #base.controlForce.setVector(Vec3.zero())
            goForward = True


        #*#
        speed = physVel
        if (goForward):
            if physVelLen > maxSpeed:
                speed.normalize()
                speed *= maxSpeed
        else:
            if physVelLen > self.ship.maxReverseSpeed:
                speed.normalize()
                speed *= self.ship.maxReverseSpeed

        #speed *= 1.0 - dt * 0.05

        # modify based on sail damage
        speed *= self.ship.Sp
        speed /= self.ship.maxSp
        ## physObject.setVelocity(speed)

        #rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
        #speed=rotMat.xform(speed)
        # The momentumForce makes it feel like we are sliding on ice -- Joe
        # f = Vec3(self.__vel)
        # f.normalize()
        # self.momentumForce.setVector(Vec3(f*(speed.length()*0.9)))


        if __debug__:
            q1=self.avatarNodePath.getQuat()
            q2=physObject.getOrientation()
            q1.normalize()
            q2.normalize()
            assert q1.isSameDirection(q2) or q1.getHpr() == q2.getHpr()
        assert self.avatarNodePath.getPos().almostEqual(
            physObject.getPosition(), 0.0001)

        # Clear the contact vector so we can
        # tell if we contact something next frame
        self.actorNode.setContactVector(Vec3.zero())

        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
        self.__oldDt = dt
        assert hasattr(self.ship, 'worldVelocity')
        self.ship.worldVelocity = self.__oldPosDelta*(1/self.__oldDt)
        if self.wantDebugIndicator:
            onScreenDebug.add("w __oldPosDelta vec",
                self.__oldPosDelta.pPrintValues())
            onScreenDebug.add("w __oldPosDelta len",
                "% 10.4f"%self.__oldPosDelta.length())
            onScreenDebug.add("w __oldDt",
                "% 10.4f"%self.__oldDt)
            onScreenDebug.add("w worldVelocity vec",
                self.ship.worldVelocity.pPrintValues())
            onScreenDebug.add("w worldVelocity len",
                "% 10.4f"%self.ship.worldVelocity.length())

        # if hasattr(self.ship, 'sailBillow'):
        #     self.ship.sailBillow = self.sailsDeployed

        if hasattr(self.ship, 'currentTurning'):
            self.ship.currentTurning = self.currentTurning

        return Task.cont
Example #58
0
 def build_dct(self, ai, has_weapon):
     keys = ['forward', 'left', 'reverse', 'right']
     return {key: inputState.isSet(key) for key in keys}
Example #59
0
    def handleAvatarControls(self, task):
        """
        Check on the arrow keys and update the avatar.
        """
        if __debug__:
            if self.wantDebugIndicator:
                onScreenDebug.append("localAvatar pos = %s\n"%(base.localAvatar.getPos().pPrintValues(),))
                onScreenDebug.append("localAvatar h = % 10.4f\n"%(base.localAvatar.getH(),))
                onScreenDebug.append("localAvatar anim = %s\n"%(base.localAvatar.animFSM.getCurrentState().getName(),))
        #assert self.debugPrint("handleAvatarControls(task=%s)"%(task,))
        physObject=self.actorNode.getPhysicsObject()
        #rotAvatarToPhys=Mat3.rotateMatNormaxis(-self.avatarNodePath.getH(), Vec3.up())
        #rotPhysToAvatar=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
        contact=self.actorNode.getContactVector()

        # hack fix for falling through the floor:
        if contact==Vec3.zero() and self.avatarNodePath.getZ()<-50.0:
            # DCR: don't reset X and Y; allow player to move
            self.reset()
            self.avatarNodePath.setZ(50.0)
            messenger.send("walkerIsOutOfWorld", [self.avatarNodePath])

        if self.wantDebugIndicator:
            self.displayDebugInfo()

        # get the button states:
        forward = inputState.isSet("forward")
        reverse = inputState.isSet("reverse")
        turnLeft = inputState.isSet("turnLeft")
        turnRight = inputState.isSet("turnRight")
        slide = 0#inputState.isSet("slide")
        slideLeft = 0#inputState.isSet("slideLeft")
        slideRight = 0#inputState.isSet("slideRight")
        jump = inputState.isSet("jump")
        
        # Check for Auto-Run
        if base.localAvatar.getAutoRun():
            forward = 1
            reverse = 0
                
        # Determine what the speeds are based on the buttons:
        self.__speed=(forward and self.avatarControlForwardSpeed or
                reverse and -self.avatarControlReverseSpeed)
        avatarSlideSpeed=self.avatarControlForwardSpeed*0.5
        #self.__slideSpeed=slide and (
        #        (turnLeft and -avatarSlideSpeed) or
        #        (turnRight and avatarSlideSpeed))
        self.__slideSpeed=(
                (slideLeft and -avatarSlideSpeed) or
                (slideRight and avatarSlideSpeed))
        self.__rotationSpeed=not slide and (
                (turnLeft and self.avatarControlRotateSpeed) or
                (turnRight and -self.avatarControlRotateSpeed))

        # How far did we move based on the amount of time elapsed?
        dt=ClockObject.getGlobalClock().getDt()

        if self.needToDeltaPos:
            self.setPriorParentVector()
            self.needToDeltaPos = 0
        #self.__oldPosDelta = render.getRelativeVector(
        #    self.avatarNodePath,
        #    self.avatarNodePath.getPosDelta(render))
        #self.__oldPosDelta = self.avatarNodePath.getRelativeVector(
        #    render,
        #    self.avatarNodePath.getPosDelta(render))
        self.__oldPosDelta = self.avatarNodePath.getPosDelta(render)
        self.__oldDt = dt
        #posDelta = self.avatarNodePath.getPosDelta(render)
        #if posDelta==Vec3.zero():
        #    self.priorParent.setVector(self.__oldPosDelta)
        #else:
        #    self.priorParent.setVector(Vec3.zero())
        #    # We must copy the vector to preserve it:
        #    self.__oldPosDelta=Vec3(posDelta)
        if __debug__:
            if self.wantDebugIndicator:
                onScreenDebug.add("posDelta1",
                    self.avatarNodePath.getPosDelta(render).pPrintValues())

                if 0:
                    onScreenDebug.add("posDelta3",
                        render.getRelativeVector(
                            self.avatarNodePath,
                            self.avatarNodePath.getPosDelta(render)).pPrintValues())

                if 0:
                    onScreenDebug.add("gravity",
                        self.gravity.getLocalVector().pPrintValues())
                    onScreenDebug.add("priorParent",
                        self.priorParent.getLocalVector().pPrintValues())
                    onScreenDebug.add("avatarViscosity",
                        "% 10.4f"%(self.avatarViscosity.getCoef(),))

                    onScreenDebug.add("physObject pos",
                        physObject.getPosition().pPrintValues())
                    onScreenDebug.add("physObject hpr",
                        physObject.getOrientation().getHpr().pPrintValues())
                    onScreenDebug.add("physObject orien",
                        physObject.getOrientation().pPrintValues())

                if 1:
                    onScreenDebug.add("physObject vel",
                        physObject.getVelocity().pPrintValues())
                    onScreenDebug.add("physObject len",
                        "% 10.4f"%physObject.getVelocity().length())

                if 0:
                    onScreenDebug.add("posDelta4",
                        self.priorParentNp.getRelativeVector(
                            render,
                            self.avatarNodePath.getPosDelta(render)).pPrintValues())

                if 1:
                    onScreenDebug.add("priorParent",
                        self.priorParent.getLocalVector().pPrintValues())

                if 0:
                    onScreenDebug.add("priorParent po",
                        self.priorParent.getVector(physObject).pPrintValues())

                if 0:
                    onScreenDebug.add("__posDelta",
                        self.__oldPosDelta.pPrintValues())

                if 1:
                    onScreenDebug.add("contact",
                        contact.pPrintValues())
                    #onScreenDebug.add("airborneHeight", "% 10.4f"%(
                    #    self.getAirborneHeight(),))

                if 0:
                    onScreenDebug.add("__oldContact",
                        contact.pPrintValues())
                    onScreenDebug.add("__oldAirborneHeight", "% 10.4f"%(
                        self.getAirborneHeight(),))
        airborneHeight=self.getAirborneHeight()
        if airborneHeight > self.highMark:
            self.highMark = airborneHeight
            if __debug__:
                onScreenDebug.add("highMark", "% 10.4f"%(self.highMark,))
        #if airborneHeight < 0.1: #contact!=Vec3.zero():
        if 1:
            if (airborneHeight > self.avatarRadius*0.5
                    or physObject.getVelocity().getZ() > 0.0
                    ): # Check stair angles before changing this.
                # ...the avatar is airborne (maybe a lot or a tiny amount).
                self.isAirborne = 1
            else:
                # ...the avatar is very close to the ground (close enough to be
                # considered on the ground).
                if self.isAirborne and physObject.getVelocity().getZ() <= 0.0:
                    # ...the avatar has landed.
                    contactLength = contact.length()
                    if contactLength>self.__hardLandingForce:
                        #print "jumpHardLand"
                        messenger.send("jumpHardLand")
                    else:
                        #print "jumpLand"
                        messenger.send("jumpLand")
                    self.priorParent.setVector(Vec3.zero())
                    self.isAirborne = 0
                elif jump:
                    #print "jump"
                    #self.__jumpButton=0
                    messenger.send("jumpStart")
                    if 0:
                        # ...jump away from walls and with with the slope normal.
                        jumpVec=Vec3(contact+Vec3.up())
                        #jumpVec=Vec3(rotAvatarToPhys.xform(jumpVec))
                        jumpVec.normalize()
                    else:
                        # ...jump straight up, even if next to a wall.
                        jumpVec=Vec3.up()
                    jumpVec*=self.avatarControlJumpForce
                    physObject.addImpulse(Vec3(jumpVec))
                    self.isAirborne = 1 # Avoid double impulse before fully airborne.
                else:
                    self.isAirborne = 0
            if __debug__:
                onScreenDebug.add("isAirborne", "%d"%(self.isAirborne,))
        else:
            if contact!=Vec3.zero():
                # ...the avatar has touched something (but might not be on the ground).
                contactLength = contact.length()
                contact.normalize()
                angle=contact.dot(Vec3.up())
                if angle>self.__standableGround:
                    # ...avatar is on standable ground.
                    if self.__oldContact==Vec3.zero():
                    #if self.__oldAirborneHeight > 0.1: #self.__oldContact==Vec3.zero():
                        # ...avatar was airborne.
                        self.jumpCount-=1
                        if contactLength>self.__hardLandingForce:
                            messenger.send("jumpHardLand")
                        else:
                            messenger.send("jumpLand")
                    elif jump:
                        self.jumpCount+=1
                        #self.__jumpButton=0
                        messenger.send("jumpStart")
                        jump=Vec3(contact+Vec3.up())
                        #jump=Vec3(rotAvatarToPhys.xform(jump))
                        jump.normalize()
                        jump*=self.avatarControlJumpForce
                        physObject.addImpulse(Vec3(jump))

        if contact!=self.__oldContact:
            # We must copy the vector to preserve it:
            self.__oldContact=Vec3(contact)
        self.__oldAirborneHeight=airborneHeight

        moveToGround = Vec3.zero()
        if not self.useHeightRay or self.isAirborne:
            # ...the airborne check is a hack to stop sliding.
            self.phys.doPhysics(dt)
            if __debug__:
                onScreenDebug.add("phys", "on")
        else:
            physObject.setVelocity(Vec3.zero())
            #if airborneHeight>0.001 and contact==Vec3.zero():
            #    moveToGround = Vec3(0.0, 0.0, -airborneHeight)
            #moveToGround = Vec3(0.0, 0.0, -airborneHeight)
            moveToGround = Vec3(0.0, 0.0, -self.determineHeight())
            if __debug__:
                onScreenDebug.add("phys", "off")
        # Check to see if we're moving at all:
        if self.__speed or self.__slideSpeed or self.__rotationSpeed or moveToGround!=Vec3.zero():
            distance = dt * self.__speed
            slideDistance = dt * self.__slideSpeed
            rotation = dt * self.__rotationSpeed

            #debugTempH=self.avatarNodePath.getH()
            assert self.avatarNodePath.getQuat().isSameDirection(physObject.getOrientation())
            assert self.avatarNodePath.getPos().almostEqual(physObject.getPosition(), 0.0001)

            # update pos:
            # Take a step in the direction of our previous heading.
            self.__vel=Vec3(
                Vec3.forward() * distance +
                Vec3.right() * slideDistance)

            # rotMat is the rotation matrix corresponding to
            # our previous heading.
            rotMat=Mat3.rotateMatNormaxis(self.avatarNodePath.getH(), Vec3.up())
            step=rotMat.xform(self.__vel)
            physObject.setPosition(Point3(
                physObject.getPosition()+step+moveToGround))

            # update hpr:
            o=physObject.getOrientation()
            r=LRotationf()
            r.setHpr(Vec3(rotation, 0.0, 0.0))
            physObject.setOrientation(o*r)

            # sync the change:
            self.actorNode.updateTransform()

            assert self.avatarNodePath.getQuat().isSameDirection(physObject.getOrientation())
            assert self.avatarNodePath.getPos().almostEqual(physObject.getPosition(), 0.0001)
            #assert self.avatarNodePath.getH()==debugTempH-rotation
            messenger.send("avatarMoving")
        else:
            self.__vel.set(0.0, 0.0, 0.0)
        # Clear the contact vector so we can tell if we contact something next frame:
        self.actorNode.setContactVector(Vec3.zero())
        return Task.cont
Example #60
0
 def trackAnimToSpeed(self, task):
     speed, rotSpeed, slideSpeed = self.controlManager.getSpeeds()
     if speed != 0.0 or rotSpeed != 0.0 or inputState.isSet('jump'):
         if not self.movingFlag:
             self.movingFlag = 1
             self.stopLookAround()
     elif self.movingFlag:
         self.movingFlag = 0
         self.startLookAround()
     if self.movingFlag or self.hp <= 0:
         self.wakeUp()
     elif not self.sleepFlag:
         now = globalClock.getFrameTime()
         if now - self.lastMoved > self.sleepTimeout:
             self.gotoSleep()
     state = None
     if self.sleepFlag:
         state = 'Sleep'
     elif self.hp > 0:
         state = 'Happy'
     else:
         state = 'Sad'
     if state != self.lastState:
         self.lastState = state
         self.b_setAnimState(state, self.animMultiplier)
         if state == 'Sad':
             self.setWalkSpeedSlow()
         else:
             self.setWalkSpeedNormal()
     if self.cheesyEffect == OTPGlobals.CEFlatProfile or self.cheesyEffect == OTPGlobals.CEFlatPortrait:
         needH = None
         if rotSpeed > 0.0:
             needH = -10
         elif rotSpeed < 0.0:
             needH = 10
         elif speed != 0.0:
             needH = 0
         if needH != None and self.lastNeedH != needH:
             node = self.getGeomNode().getChild(0)
             lerp = Sequence(LerpHprInterval(node,
                                             0.5,
                                             Vec3(needH, 0, 0),
                                             blendType='easeInOut'),
                             name='cheesy-lerp-hpr',
                             autoPause=1)
             lerp.start()
             self.lastNeedH = needH
     else:
         self.lastNeedH = None
     action = self.setSpeed(speed, rotSpeed)
     if action != self.lastAction:
         self.lastAction = action
         if self.emoteTrack:
             self.emoteTrack.finish()
             self.emoteTrack = None
         if action == OTPGlobals.WALK_INDEX or action == OTPGlobals.REVERSE_INDEX:
             self.walkSound()
         elif action == OTPGlobals.RUN_INDEX:
             self.runSound()
         else:
             self.stopSound()
     return Task.cont