- Home /
Improvements to Jumping
The following code is used for my character's movement. It's a very simple movement class for a 2D platformer. The jumping code is basically "if the character is grounded and the spacebar is held, jump". However, this means that when my player lands back on the ground, if the spacebar is still held when the character lands, he jumps again. This is unexpected behaviour, so I'd like to fix it so that if the spacebar is pressed, it only allows one jump for each press. Basically, ignore holding.
I'd also like if I could have each jump work proportionately to how long the spacebar was held in the first place. For example, if it's held for a long time, perform a full jump. If it's only tapped, perform a slight jump. My first question is more important, but if you happen to know an easy way to do this, I would appreciate suggestions.
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
float rotation = Input.GetAxis("Horizontal");
if(controller.isGrounded)
{
//jumpCount=2; //if on ground, 2 jumps can still be done
moveDirection.Set(rotation, 0, 0); //moveDirection = new Vector3(rotation, 0, 0);
moveDirection = transform.TransformDirection(moveDirection);
if(Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
{
running = true;
}
else
{
running = false;
}
if(running)Debug.Log ("yes running");
moveDirection *= running? runningSpeed : walkingSpeed;
if(Input.GetButton("Jump"))
{
moveDirection.y = jumpHeight;
//rigidbody.AddForce(Vector3.up * jumpHeight);
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}//end update
Answer by junkrar · Mar 20, 2013 at 07:09 PM
As brianruggieri said, Input.GetButtonDown() or even Input.GetKeyDown() solved this problem for me. Thanks!
Your answer
Follow this Question
Related Questions
Velocity in Unity2D 2 Answers
jump button(2d 2018 lts) 1 Answer
2.5D Platformer - Jump Question 1 Answer
How do I do a Snappy Jump in 2D with my 2D Jump Script? 1 Answer
Problem with Jump 1 Answer