- Home /
Moving player while jumping
I have my cube jumping around, but if he's not moving before hand, he just jumps straight up and then back down. So how can I have it so that when you jump, you can still move side to side (left to right)if you have no starting velocity. I'm using a Character Controller, here's my jumping code:
if (Input.GetButton ("Jump")) { moveDirection.y = jumpSpeed; } }
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
Answer by aldonaletto · May 08, 2012 at 03:13 AM
The problem isn't in the part you've posted. It seems you're using the example code in CharacterController.Move, where movement is controlled only when the character is grounded. You could move the control code outside this if, but this would kill the jump feature because the vertical velocity is always zeroed when reading the input axes. To get both things, you must keep the vertical velocity in a separate variable, like this:
var speed : float = 6.0; var jumpSpeed : float = 8.0; var gravity : float = 10.0;
private var moveDirection : Vector3 = Vector3.zero; private var vertVel: float = 0; // vertical velocity
function Update() { var controller : CharacterController = GetComponent(CharacterController); // read the controls outside the if: moveDirection = Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection) speed; if (controller.isGrounded) { // if it's grounded... if (Input.GetButton ("Jump")) { // and Jump is pressed... vertVel = jumpSpeed; // vertical velocity = jumpSpeed } } vertVel -= gravity Time.deltaTime; // apply gravity to the vertical velocity moveDirection.y = vertVel; // combine move direction with vertical velocity controller.Move(moveDirection * Time.deltaTime); // and Move }
Thanks a lot for answer this 4 years ago! helped a lot today!
Your answer
Follow this Question
Related Questions
CharacterController - moving while jumping (movement vector values reset?) 1 Answer
how to flip a sprite 0 Answers
jump with character controller best way? 1 Answer
Player Inconsistent Jumps 0 Answers