Guest User

Unity3d - Motion

a guest
Sep 28th, 2012
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #pragma strict
  2. #pragma implicit
  3. #pragma downcast
  4.  
  5.  
  6. var running : boolean = false;
  7. var cannotRun : boolean = false;
  8. var timer : float = 0;
  9.  
  10. // Does this script currently respond to input?
  11. var canControl : boolean = true;
  12.  
  13. var useFixedUpdate : boolean = true;
  14.  
  15. // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
  16. // Very handy for organization!
  17.  
  18. // The current global direction we want the character to move in.
  19. @System.NonSerialized
  20. var inputMoveDirection : Vector3 = Vector3.zero;
  21.  
  22. // Is the jump button held down? We use this interface instead of checking
  23. // for the jump button directly so this script can also be used by AIs.
  24. @System.NonSerialized
  25. var inputJump : boolean = false;
  26.  
  27. class CharacterMotorMovement {
  28.     // The maximum horizontal speed when moving
  29.     var maxForwardSpeed : float ;
  30.     var maxSidewaysSpeed : float ;
  31.     var maxBackwardsSpeed : float ;
  32.    
  33.     // Curve for multiplying speed based on slope (negative = downwards)
  34.     var slopeSpeedMultiplier : AnimationCurve = AnimationCurve(Keyframe(-90, 1), Keyframe(0, 1), Keyframe(90, 0));
  35.    
  36.     // How fast does the character change speeds?  Higher is faster.
  37.     var maxGroundAcceleration : float = 30.0;
  38.     var maxAirAcceleration : float = 20.0;
  39.  
  40.     // The gravity for the character
  41.     var gravity : float = 10.0;
  42.     var maxFallSpeed : float = 20.0;
  43.    
  44.     // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
  45.     // Very handy for organization!
  46.  
  47.     // The last collision flags returned from controller.Move
  48.     @System.NonSerialized
  49.     var collisionFlags : CollisionFlags;
  50.  
  51.     // We will keep track of the character's current velocity,
  52.     @System.NonSerialized
  53.     var velocity : Vector3;
  54.    
  55.     // This keeps track of our current velocity while we're not grounded
  56.     @System.NonSerialized
  57.     var frameVelocity : Vector3 = Vector3.zero;
  58.    
  59.     @System.NonSerialized
  60.     var hitPoint : Vector3 = Vector3.zero;
  61.    
  62.     @System.NonSerialized
  63.     var lastHitPoint : Vector3 = Vector3(Mathf.Infinity, 0, 0);
  64. }
  65.  
  66. var movement : CharacterMotorMovement = CharacterMotorMovement();
  67.  
  68. enum MovementTransferOnJump {
  69.     None, // The jump is not affected by velocity of floor at all.
  70.     InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop.
  71.     PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing.
  72.     PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor.
  73. }
  74.  
  75. // We will contain all the jumping related variables in one helper class for clarity.
  76. class CharacterMotorJumping {
  77.     // Can the character jump?
  78.     var enabled : boolean = true;
  79.  
  80.     // How high do we jump when pressing jump and letting go immediately
  81.     var baseHeight : float = 1.0;
  82.    
  83.     // We add extraHeight units (meters) on top when holding the button down longer while jumping
  84.     var extraHeight : float = 4.1;
  85.    
  86.     // How much does the character jump out perpendicular to the surface on walkable surfaces?
  87.     // 0 means a fully vertical jump and 1 means fully perpendicular.
  88.     var perpAmount : float = 0.0;
  89.    
  90.     // How much does the character jump out perpendicular to the surface on too steep surfaces?
  91.     // 0 means a fully vertical jump and 1 means fully perpendicular.
  92.     var steepPerpAmount : float = 0.5;
  93.    
  94.     // For the next variables, @System.NonSerialized tells Unity to not serialize the variable or show it in the inspector view.
  95.     // Very handy for organization!
  96.  
  97.     // Are we jumping? (Initiated with jump button and not grounded yet)
  98.     // To see if we are just in the air (initiated by jumping OR falling) see the grounded variable.
  99.     @System.NonSerialized
  100.     var jumping : boolean = false;
  101.    
  102.     @System.NonSerialized
  103.     var holdingJumpButton : boolean = false;
  104.  
  105.     // the time we jumped at (Used to determine for how long to apply extra jump power after jumping.)
  106.     @System.NonSerialized
  107.     var lastStartTime : float = 0.0;
  108.    
  109.     @System.NonSerialized
  110.     var lastButtonDownTime : float = -100;
  111.    
  112.     @System.NonSerialized
  113.     var jumpDir : Vector3 = Vector3.up;
  114. }
  115.  
  116. var jumping : CharacterMotorJumping = CharacterMotorJumping();
  117.  
  118. class CharacterMotorMovingPlatform {
  119.     var enabled : boolean = true;
  120.    
  121.     var movementTransfer : MovementTransferOnJump = MovementTransferOnJump.PermaTransfer;
  122.    
  123.     @System.NonSerialized
  124.     var hitPlatform : Transform;
  125.    
  126.     @System.NonSerialized
  127.     var activePlatform : Transform;
  128.    
  129.     @System.NonSerialized
  130.     var activeLocalPoint : Vector3;
  131.    
  132.     @System.NonSerialized
  133.     var activeGlobalPoint : Vector3;
  134.    
  135.     @System.NonSerialized
  136.     var activeLocalRotation : Quaternion;
  137.    
  138.     @System.NonSerialized
  139.     var activeGlobalRotation : Quaternion;
  140.    
  141.     @System.NonSerialized
  142.     var lastMatrix : Matrix4x4;
  143.    
  144.     @System.NonSerialized
  145.     var platformVelocity : Vector3;
  146.    
  147.     @System.NonSerialized
  148.     var newPlatform : boolean;
  149. }
  150.  
  151. var movingPlatform : CharacterMotorMovingPlatform = CharacterMotorMovingPlatform();
  152.  
  153. class CharacterMotorSliding {
  154.     // Does the character slide on too steep surfaces?
  155.     var enabled : boolean = true;
  156.    
  157.     // How fast does the character slide on steep surfaces?
  158.     var slidingSpeed : float = 15;
  159.    
  160.     // How much can the player control the sliding direction?
  161.     // If the value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed.
  162.     var sidewaysControl : float = 1.0;
  163.    
  164.     // How much can the player influence the sliding speed?
  165.     // If the value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%.
  166.     var speedControl : float = 0.4;
  167. }
  168.  
  169. var sliding : CharacterMotorSliding = CharacterMotorSliding();
  170.  
  171. @System.NonSerialized
  172. var grounded : boolean = true;
  173.  
  174. @System.NonSerialized
  175. var groundNormal : Vector3 = Vector3.zero;
  176.  
  177. private var lastGroundNormal : Vector3 = Vector3.zero;
  178.  
  179. private var tr : Transform;
  180.  
  181. private var controller : CharacterController;
  182.  
  183. function Awake () {
  184.     controller = GetComponent (CharacterController);
  185.     tr = transform;
  186.    
  187. }
  188.  
  189. private function UpdateFunction () {
  190.     // We copy the actual velocity into a temporary variable that we can manipulate.
  191.     var velocity : Vector3 = movement.velocity;
  192.    
  193.     // Update velocity based on input
  194.     velocity = ApplyInputVelocityChange(velocity);
  195.    
  196.     // Apply gravity and jumping force
  197.     velocity = ApplyGravityAndJumping (velocity);
  198.    
  199.     // Moving platform support
  200.     var moveDistance : Vector3 = Vector3.zero;
  201.     if (MoveWithPlatform()) {
  202.         var newGlobalPoint : Vector3 = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint);
  203.         moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint);
  204.         if (moveDistance != Vector3.zero)
  205.             controller.Move(moveDistance);
  206.        
  207.         // Support moving platform rotation as well:
  208.         var newGlobalRotation : Quaternion = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalRotation;
  209.         var rotationDiff : Quaternion = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation);
  210.        
  211.         var yRotation = rotationDiff.eulerAngles.y;
  212.         if (yRotation != 0) {
  213.             // Prevent rotation of the local up vector
  214.             tr.Rotate(0, yRotation, 0);
  215.         }
  216.     }
  217.    
  218.     // Save lastPosition for velocity calculation.
  219.     var lastPosition : Vector3 = tr.position;
  220.    
  221.     // We always want the movement to be framerate independent.  Multiplying by Time.deltaTime does this.
  222.     var currentMovementOffset : Vector3 = velocity * Time.deltaTime;
  223.    
  224.     // Find out how much we need to push towards the ground to avoid loosing grouning
  225.     // when walking down a step or over a sharp change in slope.
  226.     var pushDownOffset : float = Mathf.Max(controller.stepOffset, Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude);
  227.     if (grounded)
  228.         currentMovementOffset -= pushDownOffset * Vector3.up;
  229.    
  230.     // Reset variables that will be set by collision function
  231.     movingPlatform.hitPlatform = null;
  232.     groundNormal = Vector3.zero;
  233.    
  234.     // Move our character!
  235.     movement.collisionFlags = controller.Move (currentMovementOffset);
  236.    
  237.     movement.lastHitPoint = movement.hitPoint;
  238.     lastGroundNormal = groundNormal;
  239.    
  240.     if (movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform) {
  241.         if (movingPlatform.hitPlatform != null) {
  242.             movingPlatform.activePlatform = movingPlatform.hitPlatform;
  243.             movingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMatrix;
  244.             movingPlatform.newPlatform = true;
  245.         }
  246.     }
  247.    
  248.     // Calculate the velocity based on the current and previous position.  
  249.     // This means our velocity will only be the amount the character actually moved as a result of collisions.
  250.     var oldHVelocity : Vector3 = new Vector3(velocity.x, 0, velocity.z);
  251.     movement.velocity = (tr.position - lastPosition) / Time.deltaTime;
  252.     var newHVelocity : Vector3 = new Vector3(movement.velocity.x, 0, movement.velocity.z);
  253.    
  254.     // The CharacterController can be moved in unwanted directions when colliding with things.
  255.     // We want to prevent this from influencing the recorded velocity.
  256.     if (oldHVelocity == Vector3.zero) {
  257.         movement.velocity = new Vector3(0, movement.velocity.y, 0);
  258.     }
  259.     else {
  260.         var projectedNewVelocity : float = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude;
  261.         movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up;
  262.     }
  263.    
  264.     if (movement.velocity.y < velocity.y - 0.001) {
  265.         if (movement.velocity.y < 0) {
  266.             // Something is forcing the CharacterController down faster than it should.
  267.             // Ignore this
  268.             movement.velocity.y = velocity.y;
  269.         }
  270.         else {
  271.             // The upwards movement of the CharacterController has been blocked.
  272.             // This is treated like a ceiling collision - stop further jumping here.
  273.             jumping.holdingJumpButton = false;
  274.         }
  275.     }
  276.    
  277.     // We were grounded but just loosed grounding
  278.     if (grounded && !IsGroundedTest()) {
  279.         grounded = false;
  280.        
  281.         // Apply inertia from platform
  282.         if (movingPlatform.enabled &&
  283.             (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||
  284.             movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)
  285.         ) {
  286.             movement.frameVelocity = movingPlatform.platformVelocity;
  287.             movement.velocity += movingPlatform.platformVelocity;
  288.         }
  289.        
  290.         SendMessage("OnFall", SendMessageOptions.DontRequireReceiver);
  291.         // We pushed the character down to ensure it would stay on the ground if there was any.
  292.         // But there wasn't so now we cancel the downwards offset to make the fall smoother.
  293.         tr.position += pushDownOffset * Vector3.up;
  294.     }
  295.     // We were not grounded but just landed on something
  296.     else if (!grounded && IsGroundedTest()) {
  297.         grounded = true;
  298.         jumping.jumping = false;
  299.         SubtractNewPlatformVelocity();
  300.        
  301.         SendMessage("OnLand", SendMessageOptions.DontRequireReceiver);
  302.     }
  303.    
  304.     // Moving platforms support
  305.     if (MoveWithPlatform()) {
  306.         // Use the center of the lower half sphere of the capsule as reference point.
  307.         // This works best when the character is standing on moving tilting platforms.
  308.         movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height*0.5 + controller.radius);
  309.         movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint);
  310.        
  311.         // Support moving platform rotation as well:
  312.         movingPlatform.activeGlobalRotation = tr.rotation;
  313.         movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalRotation;
  314.     }
  315. }
  316.  
  317. function FixedUpdate () {
  318.     if (movingPlatform.enabled) {
  319.         if (movingPlatform.activePlatform != null) {
  320.             if (!movingPlatform.newPlatform) {
  321.                 var lastVelocity : Vector3 = movingPlatform.platformVelocity;
  322.                
  323.                 movingPlatform.platformVelocity = (
  324.                     movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint)
  325.                     - movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint)
  326.                 ) / Time.deltaTime;
  327.             }
  328.             movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMatrix;
  329.             movingPlatform.newPlatform = false;
  330.         }
  331.         else {
  332.             movingPlatform.platformVelocity = Vector3.zero;
  333.         }
  334.     }
  335.    
  336.     if (useFixedUpdate)
  337.         UpdateFunction();
  338. }
  339.  
  340. function Update () {
  341.     if (!useFixedUpdate)
  342.         UpdateFunction();
  343.    
  344.     if(Input.GetButtonDown ("Run"))
  345.     {  
  346.     running = true;
  347.         }
  348.         else if(!Input.GetButton("Run"))
  349.         {
  350.         running = false;
  351.         }
  352.                 if(running == true){
  353.                     maxForwardSpeed = 5;
  354.                     maxSidewaysSpeed = 5;
  355.                     maxBackwardsSpeed = 5;
  356.                    timer += Time.smoothDeltaTime;
  357.                         }
  358.                         if( timer >= 20){
  359.                         timer = 20;
  360.                         running = false;
  361.                         cannotRun = true;
  362.                         }
  363.                                        
  364.                         if( timer <= 10){
  365.                         cannotRun = false;
  366.                         }
  367.                                                        
  368.                         if ( cannotRun == true){
  369.                         running = false;
  370.                         }
  371.                
  372.                  if(running == false){
  373.                     maxForwardSpeed = 3;
  374.                     maxSidewaysSpeed = 3;
  375.                     maxBackwardsSpeed = 3;                                    
  376.                     timer -= Time.smoothDeltaTime;
  377.                     }
  378.                     if( timer <= 0){
  379.                     timer = 0;
  380.                     }
  381.                                  
  382.                    
  383. }
  384.  
  385. private function ApplyInputVelocityChange (velocity : Vector3) {   
  386.     if (!canControl)
  387.         inputMoveDirection = Vector3.zero;
  388.    
  389.     // Find desired velocity
  390.     var desiredVelocity : Vector3;
  391.     if (grounded && TooSteep()) {
  392.         // The direction we're sliding in
  393.         desiredVelocity = Vector3(groundNormal.x, 0, groundNormal.z).normalized;
  394.         // Find the input movement direction projected onto the sliding direction
  395.         var projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity);
  396.         // Add the sliding direction, the spped control, and the sideways control vectors
  397.         desiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysControl;
  398.         // Multiply with the sliding speed
  399.         desiredVelocity *= sliding.slidingSpeed;
  400.     }
  401.     else
  402.         desiredVelocity = GetDesiredHorizontalVelocity();
  403.    
  404.     if (movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) {
  405.         desiredVelocity += movement.frameVelocity;
  406.         desiredVelocity.y = 0;
  407.     }
  408.    
  409.     if (grounded)
  410.         desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal);
  411.     else
  412.         velocity.y = 0;
  413.    
  414.     // Enforce max velocity change
  415.     var maxVelocityChange : float = GetMaxAcceleration(grounded) * Time.deltaTime;
  416.     var velocityChangeVector : Vector3 = (desiredVelocity - velocity);
  417.     if (velocityChangeVector.sqrMagnitude > maxVelocityChange * maxVelocityChange) {
  418.         velocityChangeVector = velocityChangeVector.normalized * maxVelocityChange;
  419.     }
  420.     // If we're in the air and don't have control, don't apply any velocity change at all.
  421.     // If we're on the ground and don't have control we do apply it - it will correspond to friction.
  422.     if (grounded || canControl)
  423.         velocity += velocityChangeVector;
  424.    
  425.     if (grounded) {
  426.         // When going uphill, the CharacterController will automatically move up by the needed amount.
  427.         // Not moving it upwards manually prevent risk of lifting off from the ground.
  428.         // When going downhill, DO move down manually, as gravity is not enough on steep hills.
  429.         velocity.y = Mathf.Min(velocity.y, 0);
  430.     }
  431.    
  432.     return velocity;
  433. }
  434.  
  435. private function ApplyGravityAndJumping (velocity : Vector3) {
  436.    
  437.     if (!inputJump || !canControl) {
  438.         jumping.holdingJumpButton = false;
  439.         jumping.lastButtonDownTime = -100;
  440.     }
  441.    
  442.     if (inputJump && jumping.lastButtonDownTime < 0 && canControl)
  443.         jumping.lastButtonDownTime = Time.time;
  444.    
  445.     if (grounded)
  446.         velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTime;
  447.     else {
  448.         velocity.y = movement.velocity.y - movement.gravity * Time.deltaTime;
  449.        
  450.         // When jumping up we don't apply gravity for some time when the user is holding the jump button.
  451.         // This gives more control over jump height by pressing the button longer.
  452.         if (jumping.jumping && jumping.holdingJumpButton) {
  453.             // Calculate the duration that the extra jump force should have effect.
  454.             // If we're still less than that duration after the jumping time, apply the force.
  455.             if (Time.time < jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight)) {
  456.                 // Negate the gravity we just applied, except we push in jumpDir rather than jump upwards.
  457.                 velocity += jumping.jumpDir * movement.gravity * Time.deltaTime;
  458.             }
  459.         }
  460.        
  461.         // Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity.
  462.         velocity.y = Mathf.Max (velocity.y, -movement.maxFallSpeed);
  463.     }
  464.        
  465.     if (grounded) {
  466.         // Jump only if the jump button was pressed down in the last 0.2 seconds.
  467.         // We use this check instead of checking if it's pressed down right now
  468.         // because players will often try to jump in the exact moment when hitting the ground after a jump
  469.         // and if they hit the button a fraction of a second too soon and no new jump happens as a consequence,
  470.         // it's confusing and it feels like the game is buggy.
  471.         if (jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime < 0.2)) {
  472.             grounded = false;
  473.             jumping.jumping = true;
  474.             jumping.lastStartTime = Time.time;
  475.             jumping.lastButtonDownTime = -100;
  476.             jumping.holdingJumpButton = true;
  477.            
  478.             // Calculate the jumping direction
  479.             if (TooSteep())
  480.                 jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount);
  481.             else
  482.                 jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount);
  483.            
  484.             // Apply the jumping force to the velocity. Cancel any vertical velocity first.
  485.             velocity.y = 0;
  486.             velocity += jumping.jumpDir * CalculateJumpVerticalSpeed (jumping.baseHeight);
  487.            
  488.             // Apply inertia from platform
  489.             if (movingPlatform.enabled &&
  490.                 (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||
  491.                 movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)
  492.             ) {
  493.                 movement.frameVelocity = movingPlatform.platformVelocity;
  494.                 velocity += movingPlatform.platformVelocity;
  495.             }
  496.            
  497.             SendMessage("OnJump", SendMessageOptions.DontRequireReceiver);
  498.         }
  499.         else {
  500.             jumping.holdingJumpButton = false;
  501.         }
  502.     }
  503.    
  504.     return velocity;
  505. }
  506.  
  507. function OnControllerColliderHit (hit : ControllerColliderHit) {
  508.     if (hit.normal.y > 0 && hit.normal.y > groundNormal.y && hit.moveDirection.y < 0) {
  509.         if ((hit.point - movement.lastHitPoint).sqrMagnitude > 0.001 || lastGroundNormal == Vector3.zero)
  510.             groundNormal = hit.normal;
  511.         else
  512.             groundNormal = lastGroundNormal;
  513.        
  514.         movingPlatform.hitPlatform = hit.collider.transform;
  515.         movement.hitPoint = hit.point;
  516.         movement.frameVelocity = Vector3.zero;
  517.     }
  518. }
  519.  
  520. private function SubtractNewPlatformVelocity () {
  521.     // When landing, subtract the velocity of the new ground from the character's velocity
  522.     // since movement in ground is relative to the movement of the ground.
  523.     if (movingPlatform.enabled &&
  524.         (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer ||
  525.         movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)
  526.     ) {
  527.         // If we landed on a new platform, we have to wait for two FixedUpdates
  528.         // before we know the velocity of the platform under the character
  529.         if (movingPlatform.newPlatform) {
  530.             var platform : Transform = movingPlatform.activePlatform;
  531.             yield WaitForFixedUpdate();
  532.             yield WaitForFixedUpdate();
  533.             if (grounded && platform == movingPlatform.activePlatform)
  534.                 yield 1;
  535.         }
  536.         movement.velocity -= movingPlatform.platformVelocity;
  537.     }
  538. }
  539.  
  540. private function MoveWithPlatform () : boolean {
  541.     return (
  542.         movingPlatform.enabled
  543.         && (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked)
  544.         && movingPlatform.activePlatform != null
  545.     );
  546. }
  547.  
  548. private function GetDesiredHorizontalVelocity () {
  549.     // Find desired velocity
  550.     var desiredLocalDirection : Vector3 = tr.InverseTransformDirection(inputMoveDirection);
  551.     var maxSpeed : float = MaxSpeedInDirection(desiredLocalDirection);
  552.     if (grounded) {
  553.         // Modify max speed on slopes based on slope speed multiplier curve
  554.         var movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y)  * Mathf.Rad2Deg;
  555.         maxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle);
  556.     }
  557.     return tr.TransformDirection(desiredLocalDirection * maxSpeed);
  558. }
  559.  
  560. private function AdjustGroundVelocityToNormal (hVelocity : Vector3, groundNormal : Vector3) : Vector3 {
  561.     var sideways : Vector3 = Vector3.Cross(Vector3.up, hVelocity);
  562.     return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude;
  563. }
  564.  
  565. private function IsGroundedTest () {
  566.     return (groundNormal.y > 0.01);
  567. }
  568.  
  569. function GetMaxAcceleration (grounded : boolean) : float {
  570.     // Maximum acceleration on ground and in air
  571.     if (grounded)
  572.         return movement.maxGroundAcceleration;
  573.     else
  574.         return movement.maxAirAcceleration;
  575. }
  576.  
  577. function CalculateJumpVerticalSpeed (targetJumpHeight : float) {
  578.     // From the jump height and gravity we deduce the upwards speed
  579.     // for the character to reach at the apex.
  580.     return Mathf.Sqrt (2 * targetJumpHeight * movement.gravity);
  581. }
  582.  
  583. function IsJumping () {
  584.     return jumping.jumping;
  585. }
  586.  
  587. function IsSliding () {
  588.     return (grounded && sliding.enabled && TooSteep());
  589. }
  590.  
  591. function IsTouchingCeiling () {
  592.     return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0;
  593. }
  594.  
  595. function IsGrounded () {
  596.     return grounded;
  597. }
  598.  
  599. function TooSteep () {
  600.     return (groundNormal.y <= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad));
  601. }
  602.  
  603. function GetDirection () {
  604.     return inputMoveDirection;
  605. }
  606.  
  607. function SetControllable (controllable : boolean) {
  608.     canControl = controllable;
  609. }
  610.  
  611. // Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed.
  612. // The function returns the length of the resulting vector.
  613. function MaxSpeedInDirection (desiredMovementDirection : Vector3) : float {
  614.     if (desiredMovementDirection == Vector3.zero)
  615.         return 0;
  616.     else {
  617.         var zAxisEllipseMultiplier : float = (desiredMovementDirection.z > 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSpeed;
  618.         var temp : Vector3 = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).normalized;
  619.         var length : float = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysSpeed;
  620.         return length;
  621.     }
  622. }
  623.  
  624. function SetVelocity (velocity : Vector3) {
  625.     grounded = false;
  626.     movement.velocity = velocity;
  627.     movement.frameVelocity = Vector3.zero;
  628.     SendMessage("OnExternalVelocity");
  629. }
  630.  
  631. // Require a character controller to be attached to the same game object
  632. @script RequireComponent (CharacterController)
  633. @script AddComponentMenu ("Character/Character Motor")
Advertisement
Add Comment
Please, Sign In to add comment