How to jump with the Character Controller

Hello everyone, I'm trying to make a Character Controller to jump, but it doesn't works properly. This is my script:

var speed : float = 3.0;
var gravity : float = 20.0;
var rotateSpeed : float = 3.0;
var jumpSpeed : float = 8.0;
private var moveDirection : Vector3 = Vector3.zero;

function Update () {
    var controller : CharacterController = GetComponent(CharacterController);
if(controller.isGrounded){   
transform.Rotate(0,0,Input.GetAxis ("Horizontal") * rotateSpeed);

transform.Rotate(0,0,Input.GetAxis ("Unhorizontal") * -rotateSpeed);

var forward : Vector3 = transform.TransformDirection(Vector3.left);
var curSpeed : float = speed * Input.GetAxis ("Vertical");

 if (Input.GetButton ("Jump")) 
 {transform.Translate(Vector3.forward * jumpSpeed * Time.deltaTime);}

}

moveDirection.y -= gravity * Time.deltaTime;
controller.SimpleMove(forward * curSpeed);

}

@script RequireComponent(CharacterController)

Can you explain me the proper way to do it please?

1 Answer

1

You forgot 'controller.Move(moveDirection * Time.deltaTime);' to the bottom where you have the simple.move line.

try this

var speed : float = 3.0;
var gravity : float = 20.0;
var rotateSpeed : float = 3.0;
var jumpSpeed : float = 8.0;
private var moveDirection : Vector3 = Vector3.zero;

function Update () {
var controller : CharacterController = GetComponent(CharacterController);
var forward : Vector3 = transform.TransformDirection(Vector3.left);
var curSpeed : float = speed * Input.GetAxis ("Vertical");transform.Rotate(0,0,Input.GetAxis ("Horizontal") * rotateSpeed);

transform.Rotate(0,0,Input.GetAxis ("Unhorizontal") * -rotateSpeed);

controller.SimpleMove(forward * curSpeed);

if (Input.GetButton ("Jump")) 
if(controller.isGrounded){ 
moveDirection.y= jumpSpeed;

}

moveDirection.y -= gravity * Time.deltaTime;

controller.Move(moveDirection * Time.deltaTime);
}

Thank's for your time! Now it works at all!

the code you given is not smooth only the falling is(its by charachter controller)this code just teleports the player to a higher position and let the character controller do the rest, any idea how to make it smooth?

Nice code .It helped me...

You don't need to call the variable of controller every frame. Put it outside of update and assign it in the inspector for better performance.

This provided a great deal of help, thank you!