- Home /
Changing Direction While In Mid-Air?
I'm creating a 2D platformer, and the character control script from the Unity API is working decently well. The only concern I have with it is that you cannot go left or right when you are in mid-jump. How can I make the script do this?
 var speed : float = 6.0;
 var jumpSpeed : float = 8.0;
 var gravity : float = 20.0;
 
 private var moveDirection : Vector3 = Vector3.zero;
 
 function Update() {
     var controller : CharacterController = GetComponent(CharacterController);
     if (controller.isGrounded) {
         // We are grounded, so recalculate
         // move direction directly from axes
         moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
                                 0);
         moveDirection = transform.TransformDirection(moveDirection);
         moveDirection *= speed;
         
         if (Input.GetButton ("Jump")) {
             moveDirection.y = jumpSpeed;
         }
     }
 
     // Apply gravity
     moveDirection.y -= gravity * Time.deltaTime;
     
     // Move the controller
     controller.Move(moveDirection * Time.deltaTime);
 }
I'd also be interested in a solution if anybody has a working one
Answer by DuxDucis · Dec 19, 2012 at 11:26 PM
Move the move direction assignment outside of the if statement, resulting in this code:
 var speed : float = 6.0;
 var jumpSpeed : float = 8.0;
 var gravity : float = 20.0;
 
 private var moveDirection : Vector3 = Vector3.zero;
 
 function Update() {
     var controller : CharacterController = GetComponent(CharacterController);
     if (controller.isGrounded) {
        
 
         if (Input.GetButton ("Jump")) {
             moveDirection.y = jumpSpeed;
         }
     }
 
  // We are grounded, so recalculate
         // move direction directly from axes
         moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
                                 0);
         moveDirection = transform.TransformDirection(moveDirection);
         moveDirection *= speed;
 
     // Apply gravity
     moveDirection.y -= gravity * Time.deltaTime;
 
     // Move the controller
     controller.Move(moveDirection * Time.deltaTime);
 }
Also because row 19 is after the if, I can't jump as it reinitializes the vector there. If I put it before, jumping/falling breaks because, I assume, the controller.$$anonymous$$ove resets the fall/jump.
Your answer
 
 
             Follow this Question
Related Questions
How to make camera position relative to a specific target. 1 Answer
Changing the jump key in a premade code 4 Answers
In air direction control 4 Answers
Max height jump 1 Answer
Max height jump 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                