Search Unity

Translated CharacterMotor.js into C# and made it more readable, figured I'd share.

Discussion in 'Scripting' started by falconfetus8, Apr 9, 2014.

  1. falconfetus8

    falconfetus8

    Joined:
    Feb 4, 2013
    Posts:
    17
    EDIT: Nevermind, apparently an error popped up while I was translating this. I'll update it when I get it fixed. Sorry, I guess I should have tested it before sharing it >.>

    EDIT2: Fixed it now. Let me know if there's anything I missed.

    If you're like me, you've found that the CharacterMotor.js script(comes with Unity) is extremely messy and hard-to-read. Or, perhaps, you're used to working with C# and would prefer it in that language. Either way, this is for you.

    I took the liberty of translating CharacterMotor.js into C#. I've also reorganized it a bit to make it less of an eyesore to scroll through. Finally, I've added an extra method called GetVelocity(), which returns the current velocity of the character, which for some reason was not present in the original version.

    I mainly did this for myself, but I see no reason why I shouldn't share it, so here you go.

    If this isn't the right forum for this, could a mod please move it? Thanks!

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