- Home /
Long press for charged Jump
Hey, question for you guys, I am trying to make a player charge up a jump by long pressing a button and then after a time or when released the jumpforce will be equal to how long he pressed the button for. I've seen some tutorials on how to make the player float the longer you press but I really wanted to make it charge up and then release instead. Any ideas?
public class StartScreen : MonoBehaviour {
void Jump()
{
rig.velocity = new Vector2 (rig.velocity.x, jumpForce);
}
}
Answer by LTonon · Jan 23, 2018 at 11:41 PM
Ok, I gave it a try and came up with this code, hope it does what you want:
// Update will receive the input data
void Update () {
// If pressing Space, charge the variable charger using the Time it's being pressed.
if (Input.GetKey(KeyCode.Space))
{
charger += Time.deltaTime;
}
// On release, set the boolean 'discharge' to true.
if (Input.GetKeyUp(KeyCode.Space))
{
discharge = true;
}
}
// Using fixed update since we are dealing with Unity's Physics
private void FixedUpdate()
{
// On (discharge == true)
if (discharge)
{
// Set jump force and give new velocity
jumpForce = 10 * charger;
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
// Reset discharge and charger values
discharge = false;
charger = 0f;
}
}
I appreciate you help! hmm it seems to be working okay, however the number is pretty unpredictable for some reason and I'm not sure why. for instance if I hold the button for a while it sometimes jumps the player shorter than I short press. Which is a pretty confusing...
Also the charged float seems to be capping off on its own even though I didn't tell it to do that. Any ideas?
It is unpredictable because I used Time.deltaTime and this number corresponds to the time in seconds it took to complete the last frame. It's unpredictable but it should not present that much difference, it's the most reliable way that I can think of.
What do mean "capping off"? Resetting to 0? Did you want to keep adding speed to the Game Object without stopping?...
O$$anonymous$$AY I made the mistake, I used Get$$anonymous$$ouseButtonDown ins$$anonymous$$d of Get$$anonymous$$ouseButton, then I just added an if charger > 1 , charger = 1.
You totally saved me! Thanks so much!
Your answer
Follow this Question
Related Questions
Raycast2D not working 1 Answer
Problem with Jump 1 Answer
Jump only when Jump button is pressed - not held 1 Answer