Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

FPSInputController and CharacterMotor in Csharp

Discussion in 'Scripting' started by BotMo, Jun 17, 2011.

  1. BotMo

    BotMo

    Joined:
    Mar 2, 2011
    Posts:
    101
    Incase anyone is interested, I converted the JS scripts to C#. I don't know if it will be useful to anyone, but I figure I may as well put it out here to save you the dull work of converting by hand. The scripts work perfectly if you just replace them in the standard character-controller.

    The scripts have the same name as the JS versions, but with C at the end.

    FPSInputControllerC

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.     // Require a character controller to be attached to the same game object
    5.     [RequireComponent (typeof (CharacterMotorC))]
    6.     //RequireComponent (CharacterMotor)
    7.     [AddComponentMenu("Character/FPS Input Controller C")]
    8.     //@script AddComponentMenu ("Character/FPS Input Controller")
    9.  
    10.  
    11. public class FPSInputControllerC : MonoBehaviour
    12. {
    13.  
    14.     public CharacterMotorC cmotor;
    15.    
    16.     // Use this for initialization
    17.     void Awake ()
    18.     {
    19.         cmotor = GetComponent<CharacterMotorC>();
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update ()
    24.     {
    25.         // Get the input vector from keyboard or analog stick
    26.         int ltrig = Events.laddertrigger;
    27.         Vector3 directionVector;
    28.         if(ltrig==0){directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));}
    29.         else{directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);}
    30.        
    31.         if (directionVector != Vector3.zero)
    32.         {
    33.             // Get the length of the directon vector and then normalize it
    34.             // Dividing by the length is cheaper than normalizing when we already have the length anyway
    35.             float directionLength = directionVector.magnitude;
    36.             directionVector = directionVector / directionLength;
    37.            
    38.             // Make sure the length is no bigger than 1
    39.             directionLength = Mathf.Min(1, directionLength);
    40.            
    41.             // Make the input vector more sensitive towards the extremes and less sensitive in the middle
    42.             // This makes it easier to control slow speeds when using analog sticks
    43.             directionLength = directionLength * directionLength;
    44.            
    45.             // Multiply the normalized direction vector by the modified length
    46.             directionVector = directionVector * directionLength;
    47.         }
    48.        
    49.         // Apply the direction to the CharacterMotor
    50.         cmotor.inputMoveDirection = transform.rotation * directionVector;
    51.         cmotor.inputJump = Input.GetButton("Jump");
    52.     }
    53.  
    54. }
    55.  
    CharacterMotorC

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

    AzulValium

    Joined:
    Sep 14, 2009
    Posts:
    103
    I believe there is a mistake....the IEnumerator method "SubtractNewPlatformVelocity" must be called using "StartCoroutine", if not it just acts as an normal method ignoring the yield WaitForFixedUpdate.
     
  3. Claes

    Claes

    Joined:
    Jul 4, 2011
    Posts:
    4
    Thanks for posting this, it's exactly what I need.

    However, Im getting this error:

    "Assets/Scripts/Player/FPSInputControllerC.cs(26,21): error CS0103: The name `Events' does not exist in the current context"

    Any tips on fixing it? I'm new to this whole thing, but I'm learning :)
     
  4. zfalconer

    zfalconer

    Joined:
    Apr 12, 2013
    Posts:
    3
    ^I'm having the same problem. Anyone figure out how to fix it?
     
  5. zephjc

    zephjc

    Joined:
    May 16, 2013
    Posts:
    2
    Change

    int ltrig = Events.laddertrigger;
    Vector3 directionVector;
    if(ltrig==0){directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));}
    else{directionVector = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);}

    to

    Vector3 directionVector;
    directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));


    The laddertrigger stuff I think is OPs custom stuff, seemingly changing the direction to vertical instead of lateral.

    EDIT: I made a gist with my updated copies of the files (see the notes) https://gist.github.com/zephjc/5641540
     
    Last edited: May 24, 2013
  6. ccrh

    ccrh

    Joined:
    Aug 12, 2014
    Posts:
    1
    Alright, so just so you all know, I think there might be a tiny bug in this script. I was working on a game and the character would keep getting flung off into no-mans-land at unbelieveable velocities. It only seemed to happen when objects were involved, such as I had a cube that I had scaled to be 4x wide and 4x deep and another cube that was a basic plain cube, I set the large cube down and then got on top of it and set the small cube down right next to me and I got flung SO FAR. But no longer! Sorry to say that these scripts are likely the cause of it and most of the instability the physics in my game were experiencing. Sometimes I would even just have a bunch of cubes that I spawned and I was jumping over them and FLING, off to nowhere. But replacing the scripts fixed that. Its a shame too. I was hoping I could keep them and not have to deal with that later. I am sure I will find a work around, if I need to though. Best of luck to you all.
     
  7. HamFar

    HamFar

    Joined:
    Nov 16, 2014
    Posts:
    89
    Hi BotMo,

    How do I reduce the movement speed of a character that uses FPSInputController and CharacterMotor?

    I have a scene (made and coded by someone else) with a First Person Standard Controller that receives input from the arrow keys, but no matter which speed or acceleration variables I modify, the character moves as fast when I use the arrow key to make it go forward...

    I would appreciate your help, as I am confused.
     
  8. jaekx

    jaekx

    Joined:
    Dec 15, 2014
    Posts:
    27
    This conversion is more detailed, organized and works flawlessly. Variable structures are set up exactly the same to work with any java tutorials you may come across and find helpful. Read my comment at the bottom of the page for a minor unnecessary fix dealing with velocity, because it may make your life easier.

    https://gist.github.com/zephjc/5641540
     
  9. HamFar

    HamFar

    Joined:
    Nov 16, 2014
    Posts:
    89
    Thank you for getting back to me...

    Do you mean I should first add public to

    Code (CSharp):
    1. void SetVelocity (Vector3 velocity)
    2. {
    3.    grounded = false;
    4.    movement.velocity = velocity;
    5.    movement.frameVelocity = Vector3.zero;
    6.    SendMessage("OnExternalVelocity");
    7. }
    and then use it within the Update method of FPSInputControllerC.cs?

    Like the following?

    Code (CSharp):
    1. void Update ()
    2. {
    3.    Vector3 directionVector;
    4.    directionVector = new Vector3( Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") );
    5.    SetVelociy ( directionVector );
    6. .
    7. .
    8. .
    9. }
     
    Last edited: Dec 17, 2014
  10. HamFar

    HamFar

    Joined:
    Nov 16, 2014
    Posts:
    89
    Actually, I tried the following at the bottom of the FPSInputController script:

    Code (CSharp):
    1. motor.inputMoveDirection = transform.rotation * directionVector * Time.deltaTime;
    which made it too slow, so I just went for:

    Code (CSharp):
    1. motor.inputMoveDirection = ( transform.rotation * directionVector ) / 2.0f;
     
  11. Tolufoyeh

    Tolufoyeh

    Joined:
    Nov 13, 2014
    Posts:
    16
    Hey guys! Does anyone know where I can find the Third Person Controller converted to C# like this one was?