Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

3rd person controller script not moving left or right/still jumping though!!!

Discussion in 'Scripting' started by tallieke, Sep 29, 2014.

  1. tallieke

    tallieke

    Joined:
    Aug 17, 2014
    Posts:
    37
    I don't have much time but heres the problem, I dont think I messed up the script because I don't think i touched it and I havent screwed with teh values it should be moving, heres the script, please tell me whats wrong!!! thanks guys :) also, its csharp.. thanks :)

    Code (CSharp):
    1.  
    2. // Require a character controller to be attached to the same game object
    3. @script RequireComponent(CharacterController)
    4.  
    5. public var idleAnimation : AnimationClip;
    6. public var walkAnimation : AnimationClip;
    7. public var runAnimation : AnimationClip;
    8. public var jumpPoseAnimation : AnimationClip;
    9.  
    10. public var walkMaxAnimationSpeed : float = 0.75;
    11. public var trotMaxAnimationSpeed : float = 1.0;
    12. public var runMaxAnimationSpeed : float = 1.0;
    13. public var jumpAnimationSpeed : float = 1.15;
    14. public var landAnimationSpeed : float = 1.0;
    15.  
    16. private var _animation : Animation;
    17.  
    18. enum CharacterState {
    19.     Idle = 0,
    20.     Walking = 1,
    21.     Trotting = 2,
    22.     Running = 3,
    23.     Jumping = 4,
    24. }
    25.  
    26. private var _characterState : CharacterState;
    27.  
    28. // The speed when walking
    29. var walkSpeed = 2.0;
    30. // after trotAfterSeconds of walking we trot with trotSpeed
    31. var trotSpeed = 4.0;
    32. // when pressing "Fire3" button (cmd) we start running
    33. var runSpeed = 6.0;
    34.  
    35. var inAirControlAcceleration = 3.0;
    36.  
    37. // How high do we jump when pressing jump and letting go immediately
    38. var jumpHeight = 0.5;
    39.  
    40. // The gravity for the character
    41. var gravity = 20.0;
    42. // The gravity in controlled descent mode
    43. var speedSmoothing = 10.0;
    44. var rotateSpeed = 500.0;
    45. var trotAfterSeconds = 3.0;
    46.  
    47. var canJump = true;
    48.  
    49. private var jumpRepeatTime = 0.05;
    50. private var jumpTimeout = 0.15;
    51. private var groundedTimeout = 0.25;
    52.  
    53. // The camera doesnt start following the target immediately but waits for a split second to avoid too much waving around.
    54. private var lockCameraTimer = 0.0;
    55.  
    56. // The current move direction in x-z
    57. private var moveDirection = Vector3.zero;
    58. // The current vertical speed
    59. private var verticalSpeed = 0.0;
    60. // The current x-z move speed
    61. private var moveSpeed = 0.0;
    62.  
    63. // The last collision flags returned from controller.Move
    64. private var collisionFlags : CollisionFlags;
    65.  
    66. // Are we jumping? (Initiated with jump button and not grounded yet)
    67. private var jumping = false;
    68. private var jumpingReachedApex = false;
    69.  
    70. // Are we moving backwards (This locks the camera to not do a 180 degree spin)
    71. private var movingBack = false;
    72. // Is the user pressing any keys?
    73. private var isMoving = false;
    74. // When did the user start walking (Used for going into trot after a while)
    75. private var walkTimeStart = 0.0;
    76. // Last time the jump button was clicked down
    77. private var lastJumpButtonTime = -10.0;
    78. // Last time we performed a jump
    79. private var lastJumpTime = -1.0;
    80.  
    81.  
    82. // the height we jumped from (Used to determine for how long to apply extra jump power after jumping.)
    83. private var lastJumpStartHeight = 0.0;
    84.  
    85.  
    86. private var inAirVelocity = Vector3.zero;
    87.  
    88. private var lastGroundedTime = 0.0;
    89.  
    90.  
    91. private var isControllable = true;
    92.  
    93. function Awake ()
    94. {
    95.     moveDirection = transform.TransformDirection(Vector3.forward);
    96.    
    97.     _animation = GetComponent(Animation);
    98.     if(!_animation)
    99.         Debug.Log("The character you would like to control doesn't have animations. Moving her might look weird.");
    100.    
    101.     /*
    102. public var idleAnimation : AnimationClip;
    103. public var walkAnimation : AnimationClip;
    104. public var runAnimation : AnimationClip;
    105. public var jumpPoseAnimation : AnimationClip;  
    106.     */
    107.     if(!idleAnimation) {
    108.         _animation = null;
    109.         Debug.Log("No idle animation found. Turning off animations.");
    110.     }
    111.     if(!walkAnimation) {
    112.         _animation = null;
    113.         Debug.Log("No walk animation found. Turning off animations.");
    114.     }
    115.     if(!runAnimation) {
    116.         _animation = null;
    117.         Debug.Log("No run animation found. Turning off animations.");
    118.     }
    119.     if(!jumpPoseAnimation && canJump) {
    120.         _animation = null;
    121.         Debug.Log("No jump animation found and the character has canJump enabled. Turning off animations.");
    122.     }
    123.            
    124. }
    125.  
    126.  
    127. function UpdateSmoothedMovementDirection ()
    128. {
    129.     var cameraTransform = Camera.main.transform;
    130.     var grounded = IsGrounded();
    131.    
    132.     // Forward vector relative to the camera along the x-z plane  
    133.     var forward = cameraTransform.TransformDirection(Vector3.forward);
    134.     forward.y = 0;
    135.     forward = forward.normalized;
    136.  
    137.     // Right vector relative to the camera
    138.     // Always orthogonal to the forward vector
    139.     var right = Vector3(forward.z, 0, -forward.x);
    140.  
    141.     var v = Input.GetAxisRaw("Vertical");
    142.     var h = Input.GetAxisRaw("Horizontal");
    143.  
    144.     // Are we moving backwards or looking backwards
    145.     if (v < -0.2)
    146.         movingBack = true;
    147.     else
    148.         movingBack = false;
    149.    
    150.     var wasMoving = isMoving;
    151.     isMoving = Mathf.Abs (h) > 0.1 || Mathf.Abs (v) > 0.1;
    152.        
    153.     // Target direction relative to the camera
    154.     var targetDirection = h * right + v * forward;
    155.    
    156.     // Grounded controls
    157.     if (grounded)
    158.     {
    159.         // Lock camera for short period when transitioning moving & standing still
    160.         lockCameraTimer += Time.deltaTime;
    161.         if (isMoving != wasMoving)
    162.             lockCameraTimer = 0.0;
    163.  
    164.         // We store speed and direction seperately,
    165.         // so that when the character stands still we still have a valid forward direction
    166.         // moveDirection is always normalized, and we only update it if there is user input.
    167.         if (targetDirection != Vector3.zero)
    168.         {
    169.             // If we are really slow, just snap to the target direction
    170.             if (moveSpeed < walkSpeed * 0.9 && grounded)
    171.             {
    172.                 moveDirection = targetDirection.normalized;
    173.             }
    174.             // Otherwise smoothly turn towards it
    175.             else
    176.             {
    177.                 moveDirection = Vector3.RotateTowards(moveDirection, targetDirection, rotateSpeed * Mathf.Deg2Rad * Time.deltaTime, 1000);
    178.                
    179.                 moveDirection = moveDirection.normalized;
    180.             }
    181.         }
    182.        
    183.         // Smooth the speed based on the current target direction
    184.         var curSmooth = speedSmoothing * Time.deltaTime;
    185.        
    186.         // Choose target speed
    187.         //* We want to support analog input but make sure you cant walk faster diagonally than just forward or sideways
    188.         var targetSpeed = Mathf.Min(targetDirection.magnitude, 1.0);
    189.    
    190.         _characterState = CharacterState.Idle;
    191.        
    192.         // Pick speed modifier
    193.         if (Input.GetKey (KeyCode.LeftShift) || Input.GetKey (KeyCode.RightShift))
    194.         {
    195.             targetSpeed *= runSpeed;
    196.             _characterState = CharacterState.Running;
    197.         }
    198.         else if (Time.time - trotAfterSeconds > walkTimeStart)
    199.         {
    200.             targetSpeed *= trotSpeed;
    201.             _characterState = CharacterState.Trotting;
    202.         }
    203.         else
    204.         {
    205.             targetSpeed *= walkSpeed;
    206.             _characterState = CharacterState.Walking;
    207.         }
    208.        
    209.         moveSpeed = Mathf.Lerp(moveSpeed, targetSpeed, curSmooth);
    210.        
    211.         // Reset walk time start when we slow down
    212.         if (moveSpeed < walkSpeed * 0.3)
    213.             walkTimeStart = Time.time;
    214.     }
    215.     // In air controls
    216.     else
    217.     {
    218.         // Lock camera while in air
    219.         if (jumping)
    220.             lockCameraTimer = 0.0;
    221.  
    222.         if (isMoving)
    223.             inAirVelocity += targetDirection.normalized * Time.deltaTime * inAirControlAcceleration;
    224.     }
    225.    
    226.  
    227.        
    228. }
    229.  
    230.  
    231. function ApplyJumping ()
    232. {
    233.     // Prevent jumping too fast after each other
    234.     if (lastJumpTime + jumpRepeatTime > Time.time)
    235.         return;
    236.  
    237.     if (IsGrounded()) {
    238.         // Jump
    239.         // - Only when pressing the button down
    240.         // - With a timeout so you can press the button slightly before landing      
    241.         if (canJump && Time.time < lastJumpButtonTime + jumpTimeout) {
    242.             verticalSpeed = CalculateJumpVerticalSpeed (jumpHeight);
    243.             SendMessage("DidJump", SendMessageOptions.DontRequireReceiver);
    244.         }
    245.     }
    246. }
    247.  
    248.  
    249. function ApplyGravity ()
    250. {
    251.     if (isControllable)    // don't move player at all if not controllable.
    252.     {
    253.         // Apply gravity
    254.         var jumpButton = Input.GetButton("Jump");
    255.        
    256.        
    257.         // When we reach the apex of the jump we send out a message
    258.         if (jumping && !jumpingReachedApex && verticalSpeed <= 0.0)
    259.         {
    260.             jumpingReachedApex = true;
    261.             SendMessage("DidJumpReachApex", SendMessageOptions.DontRequireReceiver);
    262.         }
    263.    
    264.         if (IsGrounded ())
    265.             verticalSpeed = 0.0;
    266.         else
    267.             verticalSpeed -= gravity * Time.deltaTime;
    268.     }
    269. }
    270.  
    271. function CalculateJumpVerticalSpeed (targetJumpHeight : float)
    272. {
    273.     // From the jump height and gravity we deduce the upwards speed
    274.     // for the character to reach at the apex.
    275.     return Mathf.Sqrt(2 * targetJumpHeight * gravity);
    276. }
    277.  
    278. function DidJump ()
    279. {
    280.     jumping = true;
    281.     jumpingReachedApex = false;
    282.     lastJumpTime = Time.time;
    283.     lastJumpStartHeight = transform.position.y;
    284.     lastJumpButtonTime = -10;
    285.    
    286.     _characterState = CharacterState.Jumping;
    287. }
    288.  
    289. function Update() {
    290.    
    291.     if (!isControllable)
    292.     {
    293.         // kill all inputs if not controllable.
    294.         Input.ResetInputAxes();
    295.     }
    296.  
    297.     if (Input.GetButtonDown ("Jump"))
    298.     {
    299.         lastJumpButtonTime = Time.time;
    300.     }
    301.  
    302.     UpdateSmoothedMovementDirection();
    303.    
    304.     // Apply gravity
    305.     // - extra power jump modifies gravity
    306.     // - controlledDescent mode modifies gravity
    307.     ApplyGravity ();
    308.  
    309.     // Apply jumping logic
    310.     ApplyJumping ();
    311.    
    312.     // Calculate actual motion
    313.     var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;
    314.     movement *= Time.deltaTime;
    315.    
    316.     // Move the controller
    317.     var controller : CharacterController = GetComponent(CharacterController);
    318.     collisionFlags = controller.Move(movement);
    319.    
    320.     // ANIMATION sector
    321.     if(_animation) {
    322.         if(_characterState == CharacterState.Jumping)
    323.         {
    324.             if(!jumpingReachedApex) {
    325.                 _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;
    326.                 _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
    327.                 _animation.CrossFade(jumpPoseAnimation.name);
    328.             } else {
    329.                 _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;
    330.                 _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
    331.                 _animation.CrossFade(jumpPoseAnimation.name);              
    332.             }
    333.         }
    334.         else
    335.         {
    336.             if(controller.velocity.sqrMagnitude < 0.1) {
    337.                 _animation.CrossFade(idleAnimation.name);
    338.             }
    339.             else
    340.             {
    341.                 if(_characterState == CharacterState.Running) {
    342.                     _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed);
    343.                     _animation.CrossFade(runAnimation.name);  
    344.                 }
    345.                 else if(_characterState == CharacterState.Trotting) {
    346.                     _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed);
    347.                     _animation.CrossFade(walkAnimation.name);  
    348.                 }
    349.                 else if(_characterState == CharacterState.Walking) {
    350.                     _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed);
    351.                     _animation.CrossFade(walkAnimation.name);  
    352.                 }
    353.                
    354.             }
    355.         }
    356.     }
    357.     // ANIMATION sector
    358.    
    359.     // Set rotation to the move direction
    360.     if (IsGrounded())
    361.     {
    362.        
    363.         transform.rotation = Quaternion.LookRotation(moveDirection);
    364.            
    365.     }  
    366.     else
    367.     {
    368.         var xzMove = movement;
    369.         xzMove.y = 0;
    370.         if (xzMove.sqrMagnitude > 0.001)
    371.         {
    372.             transform.rotation = Quaternion.LookRotation(xzMove);
    373.         }
    374.     }  
    375.    
    376.     // We are in jump mode but just became grounded
    377.     if (IsGrounded())
    378.     {
    379.         lastGroundedTime = Time.time;
    380.         inAirVelocity = Vector3.zero;
    381.         if (jumping)
    382.         {
    383.             jumping = false;
    384.             SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
    385.         }
    386.     }
    387. }
    388.  
    389. function OnControllerColliderHit (hit : ControllerColliderHit )
    390. {
    391. //    Debug.DrawRay(hit.point, hit.normal);
    392.     if (hit.moveDirection.y > 0.01)
    393.         return;
    394. }
    395.  
    396. function GetSpeed () {
    397.     return moveSpeed;
    398. }
    399.  
    400. function IsJumping () {
    401.     return jumping;
    402. }
    403.  
    404. function IsGrounded () {
    405.     return (collisionFlags & CollisionFlags.CollidedBelow) != 0;
    406. }
    407.  
    408. function GetDirection () {
    409.     return moveDirection;
    410. }
    411.  
    412. function IsMovingBackwards () {
    413.     return movingBack;
    414. }
    415.  
    416. function GetLockCameraTimer ()
    417. {
    418.     return lockCameraTimer;
    419. }
    420.  
    421. function IsMoving ()  : boolean
    422. {
    423.     return Mathf.Abs(Input.GetAxisRaw("Vertical")) + Mathf.Abs(Input.GetAxisRaw("Horizontal")) > 0.5;
    424. }
    425.  
    426. function HasJumpReachedApex ()
    427. {
    428.     return jumpingReachedApex;
    429. }
    430.  
    431. function IsGroundedWithTimeout ()
    432. {
    433.     return lastGroundedTime + groundedTimeout > Time.time;
    434. }
    435.  
    436. function Reset ()
    437. {
    438.     gameObject.tag = "Player";
    439. }
    440.  
    441.  
     
  2. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    Well, did you set the horizontal axis in the settings?
    Also, I can see that if "!isControllable" then the inputs will not work, but jump will. Is it possible that it is constantly in that state?
     
  3. tallieke

    tallieke

    Joined:
    Aug 17, 2014
    Posts:
    37
    !isControllable is set to true so its not that, but i could not find out what you mean about horizontal axis. thanks for the help but its not there yet, any other advice?? :)
     
  4. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    I've just read how the original script is written in Unity, so forgive me about the silly remark about "isControllable".

    As for the horizontal axis, well, do you know where you set the keys?
    http://docs.unity3d.com/Manual/class-InputManager.html
     
  5. tallieke

    tallieke

    Joined:
    Aug 17, 2014
    Posts:
    37
    Sadly that wasnt it, I had already made sure that horizontal and vertical are set right in the input settings + my other character who uses another move script that I mad( a first person one) uses vertical and horizontal so that cant be it :(

    What you said about isControllable is'nt silly though (my spelling of is'nt is) I'm thankfull for any help you can give me, any other ideas :)