- Home /
Directional Jumping (Help)
This is my first time trying to code a jump movement and controller for my ball in Unity. My question is how can I make my ball jump in the direction of the arrow key pressed? Right now my character jumps just straight up and down, but I want to it to jump in the direction I am inputting using the arrows keys. Thanks in advance!
var speed : float = 6.0;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
var rotateSpeed : float = 3.0;
var inAirVelocity: float = 3.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
transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
// Move forward / backward
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var curSpeed : float = speed * Input.GetAxis ("Vertical");
controller.SimpleMove(forward * curSpeed);
var inAirVelocity = Vector3.zero;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
@script RequireComponent( CharacterController )
Answer by aldonaletto · Aug 07, 2011 at 06:44 PM
You must change a little your logic: if the character is grounded, zero its vertical velocity and check for jump, and let the "Vertical" axis control horizontal movement only - this way even jumping it will continue moving in the selected direction:
var speed : float = 6.0; var jumpSpeed : float = 8.0; var gravity : float = 20.0; var rotateSpeed : float = 3.0; private var moveDirection : Vector3 = Vector3.zero;
function Update() { var controller : CharacterController = GetComponent(CharacterController); transform.Rotate(0, Input.GetAxis ("Horizontal") rotateSpeed, 0); // Calculate forth/back velocity vector var forward : Vector3 = transform.forward speed Input.GetAxis("Vertical"); forward.y = moveDirection.y; // keep current vertical velocity moveDirection = forward; // but update horizontal velocity if (controller.isGrounded) { moveDirection.y = 0; // zero vertical velocity if already grounded if (Input.GetButton ("Jump")) { // of set it to jumpSpeed if Jump pressed moveDirection.y = jumpSpeed; } } // Apply gravity anyway moveDirection.y -= gravity Time.deltaTime; // Move the controller controller.Move(moveDirection * Time.deltaTime); } I eliminated the SimpleMove, since you must have only one Move or SimpleMove per Update.
Answer by appmonster · Aug 07, 2011 at 07:23 PM
Thank you so much, now I understand the error I made!