Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by tkoptur1 · Feb 13, 2014 at 04:01 AM · charactercontrollerjumpmovedirection

My character does not go forward when I jump?

Hello everyone,

I am having a big problem with the java script that I have.

I have customized and changed this code so many times. There were couple problems with the animations in this code but luckily I have fixed all of them.

Now, here is the problem that I have. When I press jump, while I am walking or running, my character does not move forward and jumping cuts it's speed. It's like he is hitting an invisible wall suddenly. I have tried everything to fix this problem but nothing seems working. The jump code looks correct. It gets the "moveDirection.y = jumpSpeed;" and so on. I have tried adding x and z moveDirection as well but that made it worst(character only went to a one direction).

Can someone help me please!!

Here is the code that I am using;

 var walkSpeed = 6.0;                            //How fast can the character walk
 
 var walkAnimSpeed:float;
 
 var runSpeed = 10.0;                            //How fast can the character run
 
 var runAnimSpeed:float;
 
 var toggleRun = false;                          //If checked, the run key toggles between running and walking. Otherwise character runs if the key is held down and walks otherwise.  There must be a button set up in the Input Manager called "Run"
 
 var limitDiagonalSpeed = true;                  //If true, diagonal speed (when strafing + moving forward or back) can't exceed normal move speed; otherwise it's about 1.4 times faster
 
 var jumpSpeed = 8.0;                            //How high can the character jump
 
 var gravity = 20.0;                             //How strong is gravity for the character
 
 var fallingDamageThreshold = 10.0;              //Units that character can fall before a falling damage function is run. To disable, type "infinity" in the inspector
 
 var slideWhenOverSlopeLimit = false;            //If checked, if the character ends up on a slope which is at least the slope limit as set on the character controller, then he will slide down
 
 var slideOnTaggedObjects = false;               //If checked and the character is on an object tagged "Slide", he will slide down it regardless of the slope limit
 
 var slideSpeed = 12.0;                          //Speed the character can slide
 
 var airControl = false;                         //If checked, then the player can change direction while in the air
 
 var antiBumpFactor = .75;                       //Small amounts of this results in bumping when walking down slopes, but large amounts results in falling too fast
 
 var antiBunnyHopFactor = 1;                     //Player must be grounded for at least this many physics frames before being able to jump again; set to 0 to allow bunny hopping 
 
 var idleSpeed:float;
 
 var rotateSpeed:float = 250.0;                  //Rotation speed of the character 
 
 private var moveDirection = Vector3.zero;       //The direction of movement
 
 private var grounded = false;                   //Is the character on the ground
 
 private var controller : CharacterController;   //Reference to the character controller
 
 private var myTransform : Transform;            //Reference to the transform
 
 private var speed : float;                      //Internal speed variable
 
 private var slideLimit : float;                 //Internal slide speed variable
 
 private var fallStartLevel : float;             //Height the character started to fall from
 
 private var falling = false;                    //Is the character falling
 
 private var hit : RaycastHit;                   //For checking distance to the ground
 
 private var rayDistance : float;                //For checking distance to the ground
 
 private var contactPoint : Vector3;             //For checking distance to the ground
 
 private var playerControl = false;              //Can the player control the character while in the air
 
 private var jumpTimer : int;                    //How long has the character been in the air
 
 private var mouseSideButton:boolean = false;    //Are the mouse side buttons being pressed
 
 private var pbuffer:float = 0.0;                //Cooldown pbuffer for mouse side buttons
 
 private var coolDown:float = 0.5;               //Cooldown time for mouse side buttons
 
 private var oldPos : Vector3; 
 
 private var moveStatus:String = "idle";
 
 private var moveSpeed:float = 0.0;
 
 private var jumping = false;
 
 
 
 function Start () {
 
     controller = GetComponent(CharacterController);
 
     myTransform = transform;
 
     speed = walkSpeed;
 
     rayDistance = controller.height * .5 + controller.radius;
 
     slideLimit = controller.slopeLimit - .1;
 
     jumpTimer = antiBunnyHopFactor;
 
     oldPos = transform.position;
 
 }
 
  
 function GetSpeed () {
     if (moveStatus == "idle")
         moveSpeed = 0;
         animation.Play("idle");
     if (moveStatus == "walk")
         moveSpeed = walkSpeed;
         animation.Play("walk");
     if (moveStatus == "run")
         moveSpeed = runSpeed;
         animation.Play("run");
     return moveSpeed;
 }
 
 function FixedUpdate() {
 
  
 
     //Get horizontal and vertical input axis and assign to variables
 
     var inputX = Input.GetAxis("Strafing");
 
     var inputY = Input.GetAxis("Vertical");
     
 
     //If both horizontal and vertical are used simultaneously, limit speed (if allowed), so the total doesn't exceed normal move speed
 
     var inputModifyFactor = (inputX != 0.0 && inputY != 0.0 && limitDiagonalSpeed)? .7071 : 1.0;
 
     
 
     //If the character is on the ground
 
     if (grounded) {
     
 
         //By default the character is not sliding
 
         var sliding = false;
 
         
 
         //Change moveDirection value to reflect the current direction of movement
 
         moveDirection = new Vector3((Input.GetMouseButton(1) ? Input.GetAxis("Strafing") : 0),0,Input.GetAxis("Vertical"));
         
         if(Input.GetAxis("Vertical") < 0.1){
 
             animation['idle'].speed = idleSpeed;
 
             animation.CrossFade("idle");
             
         }
         
         if(Input.GetAxis("Vertical") > 0){
 
         if(Input.GetButton("Run")){
 
             animation['run'].speed = runAnimSpeed;
 
             animation.CrossFade("run");
 
             controller.Move(transform.forward * runSpeed * Time.deltaTime);
 
         }
 
         else{
 
             animation['Walk'].speed = walkAnimSpeed;
 
             animation.CrossFade("Walk");
 
             controller.Move(transform.forward * walkSpeed * Time.deltaTime);
 
         }
 
     }
 
  
 
         //Pushbuffer to avoid on/off flipping
 
         if(pbuffer>0)
 
             pbuffer -=Time.deltaTime;
 
         if(pbuffer<0)pbuffer=0;
 
                        
 
         //Automove mouse side button movement
 
         if(Input.GetAxis("Toggle Move") && pbuffer == 0){
 
             pbuffer=coolDown;
 
             mouseSideButton = !mouseSideButton;
 
         }
         
 
         if(mouseSideButton && ((Input.GetAxis("Vertical") != 0) || Input.GetButton("Jump") || (Input.GetMouseButton(0) && Input.GetMouseButton(1)) ))
 
             mouseSideButton = false;
 
         
 
         //Strafing movement (like Q/E movement)
 
         moveDirection.x -= Input.GetAxis("Strafing");
 
         
 
         //See if surface immediately below should be slid down. We use this normally rather than a ControllerColliderHit point because that interferes with step climbing amongst other annoyances
 
         if (Physics.Raycast(myTransform.position, -Vector3.up, hit, rayDistance)) {
 
             if (Vector3.Angle(hit.normal, Vector3.up) > slideLimit)
 
                 sliding = true;
 
         }
 
         //However, just raycasting straight down from the center can fail when on steep slopes
 
         //So if the above raycast didn't catch anything, raycast down from the stored ControllerColliderHit point instead
 
         else {
 
             Physics.Raycast(contactPoint + Vector3.up, -Vector3.up, hit);
 
             if (Vector3.Angle(hit.normal, Vector3.up) > slideLimit)
 
                 sliding = true;
 
         }
 
  
 
         //If character was falling and fell a vertical distance greater than the threshold, run a falling damage routine
 
         if (falling) {
 
             falling = false;
 
             if (myTransform.position.y < fallStartLevel - fallingDamageThreshold)
 
                 FallingDamageAlert (fallStartLevel - myTransform.position.y);
 
         }
 
  
 
         //If running isn't on a toggle, then use the appropriate speed depending on whether the run button is down
 
         //if (!toggleRun) 
 
         //  speed = Input.GetButton("Run")? runSpeed : walkSpeed;
 
  
 
         //If sliding (and it's allowed), or if character is on an object tagged "Slide", get a vector pointing down the slope the character is on
 
         if ( (sliding && slideWhenOverSlopeLimit) || (slideOnTaggedObjects && hit.collider.tag == "Slide") ) {
 
             var hitNormal = hit.normal;
 
             moveDirection = Vector3(hitNormal.x, -hitNormal.y, hitNormal.z);
 
             Vector3.OrthoNormalize (hitNormal, moveDirection);
 
             moveDirection *= slideSpeed;
 
             playerControl = false;
 
         }
 
         //Otherwise recalculate moveDirection directly from axes, adding a bit of -y to avoid bumping down inclines
 
         else {
 
             moveDirection = Vector3(inputX * inputModifyFactor, -antiBumpFactor, inputY * inputModifyFactor);
 
             moveDirection = myTransform.TransformDirection(moveDirection) * speed;
 
             playerControl = true;
 
         }
 
         
 
         //L+R Mouse button movement
 
         if (Input.GetMouseButton(0) && Input.GetMouseButton(1) || mouseSideButton) {
 
             moveDirection.x = inputX * speed * inputModifyFactor;  //Strafe in the correct direction if Q/E are used
 
             moveDirection.z +=1 * speed;  //Move forward at the correct speed
 
             moveDirection = myTransform.TransformDirection(moveDirection);
 
             Screen.lockCursor = true;  //Lock the mouse cursor
 
         }
 
         else {
 
             Screen.lockCursor = false;  //Unlock the mouse cursor
 
         }
 
  
 
         //Jump, but only if the jump button has been released and the character has been grounded for a given number of frames
 
         if (!Input.GetButton("Jump"))
 
             jumpTimer++;
 
         else if (jumpTimer >= antiBunnyHopFactor) {
 
             moveDirection.y = jumpSpeed;
 
             jumpTimer = 0;
 
         }
 
     }
 
     
 
     //If the character is not on the ground
 
     else {
 
     
 
         //If the character stepped over a cliff or something, set the height at which the character started falling
 
         if (!falling) {
 
             falling = true;
 
             fallStartLevel = myTransform.position.y;
 
         }
 
  
 
         //If air control is allowed, check movement but don't touch the y component
 
         if (airControl && playerControl) {
 
             moveDirection.x = inputX * speed * inputModifyFactor;
 
             moveDirection.z = inputY * speed * inputModifyFactor;
 
                 // Give ability to jump forward while using both mouse buttons to move
 
                 if (Input.GetMouseButton(0) && Input.GetMouseButton(1) || mouseSideButton) {
 
                     moveDirection.z +=1 * speed;
 
                     Screen.lockCursor = true;  //Lock the mouse cursor.
 
                 }
 
                 else {
 
                     Screen.lockCursor = false;  //Unlock the mouse Cursor.
 
                 }
 
             moveDirection = myTransform.TransformDirection(moveDirection);
 
         }
 
     }
 
  
 
     //Allow turning at any time. Keep the character facing in the same direction as the camera if the right mouse button is down.
 
     if(Input.GetMouseButton(1)) {
 
         transform.rotation = Quaternion.Euler(0,Camera.main.transform.eulerAngles.y,0);
 
     } else {
 
         transform.Rotate(0,Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime, 0);
 
     } 
 
  
 
     //Apply gravity
     
     Physics.gravity = Vector3(0, -9.8, 0);
 
     moveDirection.y -= gravity * Time.deltaTime;
 
     //Move the controller and set grounded to true or false depending on whether the character is standing on something
 
     grounded = (controller.Move(moveDirection * Time.deltaTime) & CollisionFlags.Below) != 0;
     
     
     jumping = grounded ? false : jumping;
 
 
 }
 
 
 
 function Update () {
 
  
 
     //If the run button is set to toggle then switch between walk/run speed
 
     if (toggleRun && grounded && Input.GetButtonDown("Run"))
 
         speed = (speed == walkSpeed? runSpeed : walkSpeed);
 
 
 }
 
  
 
 //Store point that character is in contact with for use in FixedUpdate if needed
 
 function OnControllerColliderHit (hit : ControllerColliderHit) {
 
     contactPoint = hit.point;
 
 }
  
 
 //If falling damage occured, this is the place to do something about it. You can make the character
 
 //have hitpoints and remove some of them based on the distance fallen, add sound effects, etc.
 
 function FallingDamageAlert (fallDistance : float) {
 
     Debug.Log ("Fell " + fallDistance + " units!");   
 
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
â–¼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

18 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to jump multiple times to mid air? 3 Answers

(CharacterController) Jumping from other script 0 Answers

Jump and move (CharacterController.velocity) C# 0 Answers

Jumping not always work 2 Answers

I aren't able to jump. I find no mistake in the script 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges