I’m working on a 2d platformer game, but I ran into a little problem when I was working on the controller, I can’t make it jump. I have never programmed character controllers before and I am still trying to learn how they work, but I can’t find out what the best solution is.
here’s my code untill now:
var Speed = 3.0;
var JumpSpeed = 3.0;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
//Movement in the x-axis
var right = transform.TransformDirection(1, 0, 0);
var CurSpeed = Speed * Input.GetAxis("Horizontal");
controller.SimpleMove(right * CurSpeed);
//Jumping controlls
//Check if the character controller is on the ground
if (controller.isGrounded) {
if (Input.GetButton ("Jump")) {
//problem-------> what should I add here to make the character controller jump?
}
}
}
@script RequireComponent(CharacterController);
/// This script moves the character controller forward
/// and sideways based on the arrow keys.
/// It also jumps when pressing space.
/// Make sure to attach a character controller to the same game object.
/// It is recommended that you make only one call to Move or SimpleMove per frame.
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,
Input.GetAxis("Vertical"));
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);
}