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

Transfering character controller to c#

Discussion in 'Scripting' started by Airship, Sep 28, 2012.

  1. Airship

    Airship

    Joined:
    Sep 10, 2011
    Posts:
    260
    I am trying to transfer the default unity characterMotor.js to c#

    In the script a class called CharacterMotorMovement is created with a bunch of variables and then this line of code is used after the class ends. I guess this is to use the class in other parts of the script like in the update function. How do I write this line in c#? Thanks

    Code (csharp):
    1. var movement : CharacterMotorMovement = CharacterMotorMovement();
     
  2. KyleOlsen

    KyleOlsen

    Joined:
    Apr 3, 2012
    Posts:
    237
    Code (csharp):
    1.  CharacterMotorMovement movement = new CharacterMotorMovement();
     
  3. Airship

    Airship

    Joined:
    Sep 10, 2011
    Posts:
    260
    Thank you!
     
  4. Airship

    Airship

    Joined:
    Sep 10, 2011
    Posts:
    260
    Okay another issue I am having:
    I am now trying to change the FPSInputController to c#.

    in JS it reads in the CharacterMotor script like this.
    Code (csharp):
    1. private var motor : CharacterMotor;

    in C# I have done this.

    Code (csharp):
    1. CharacterMotor motor =  new CharacterMotor();
    and then in my void awake I do
    Code (csharp):
    1. motor = GetComponent<CharacterMotor>();
    This worsk and the scripts function/ communicate with each other properly but I get these warning messages when I play the game so I dont think this is entirely correct.
    Code (csharp):
    1.  
    2. You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent().  Alternatively, your script can inherit from ScriptableObject or no base class at all
    3. UnityEngine.MonoBehaviour:.ctor()
    4. CharacterMotor:.ctor()
    5. FPSInputController:.ctor()
     
  5. Fyko-chan

    Fyko-chan

    Joined:
    Sep 29, 2012
    Posts:
    76
    Without reading the code, I would guess you could change
    Code (csharp):
    1. CharacterMotor motor =  new CharacterMotor();
    into
    Code (csharp):
    1. CharacterMotor motor;
     
  6. Airship

    Airship

    Joined:
    Sep 10, 2011
    Posts:
    260
    thank you - that was it.
     
  7. Airship

    Airship

    Joined:
    Sep 10, 2011
    Posts:
    260
    Okay. I am now trying to modify the firstperson controller into a third person rpg controller. I got some basic rotation in there so it's no longer a fps controller but there are still some issues.

    1. The character keeps moving for about a second even when no button is pushed down if the speed is higher than 6. The velocity of the character just doesn't stop instantly.

    2. The character instantly turns around if moving right/ left or forward backwards. It should have take like .3 seconds to fade.

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

    omelchor

    Joined:
    Jun 15, 2011
    Posts:
    20
    Excellent, thanks.
     
  9. WHPPR

    WHPPR

    Joined:
    Jan 25, 2016
    Posts:
    3
    does anyone know; or can they help me more specifically, with the process of a basic 2d character controller?
    My requirements on this character controller are to have it be able to jump and move in both directions.
    I am completely new to c# and really want to put my "profiency with unity" into use. if you can help me with this problem,
    my email is ozz.layman@outlook.com.