- Home /
how can I make a character fly when holding down the jump button?
I have a character controlled with a character controller object. When I press the jump button my character jumps. If I press the button again in the air he jumps again (double jump). If I hold the jump button down I want the character to slowly fly upwards at a constant velocity, while still being able to move the character left and right ( It's a 2D platformer). When I release the jump button I want the character to fall down. I want their to be a certain time limit that the character can "fly" though. For instance I have game objects in the game that the character needs to collect to keep flying. So without collecting them he can fly for a maximum of 8 seconds. I have tried a lot of different approaches to this but cannot get this to work. I'm hoping someone might have some suggestions for me. Thank you!
Please share some code that you do have. The more you share, the easier it would be to change it to what you're wanting.
@Chad$$anonymous$$- FYI, if you post comments as comments ins$$anonymous$$d of answers, you won't have to wait for the moderation queue...
Answer by syclamoth · Mar 15, 2012 at 03:10 AM
Well, I'm not too hot on specifics of CharacterControllers (Can't stand 'em, never use 'em), but I can outline some pseudocode for you. What I'm writing here assumes that you want the action to be something like-
tap jump once: jump
tap jump again: double-jump
hold jump having let go of jump after the double-jump: fly upwards, constant speed.
bool hasDoubleJumped;
public float maxFlyTime;
float currentFlyTime;
if(on ground)
{
hasDoubleJumped = false;
currentFlyTime = 0;
}
if(jumpButton pressed down)
{
if(on ground)
{
jump;
}
if(inAir)
{
if(!hasDoubleJumped)
{
doubleJump;
hasDoubleJumped = true;
}
}
}
if(jumpButton held down && hasDoubleJumped && currentFlyTime < maxFlyTime)
{
fly upward;
currentFlyTime += Time.deltaTime;
} else {
apply gravity;
}
Thank you Syclamoth. Your code sample helped me out a bit. I'm still tweaking it but I'm on the right track. I'll post the code once I get it all working.
no reason to post my code... just do exactly what syclamoth said... got it working. also... when character hits the ground make sure you reset the currentFlyTime to 0.0 otherwise you cannot fly again :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613065132im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
creating a jump pad for a character controller 2 Answers
Third person controller in Flight 1 Answer
Make NavMesh Agent Jump on Off-Mesh Links 0 Answers
Why won't this jump code work? 1 Answer
Jumping not always work 2 Answers