Forums

ForumsProgramming Forum

Detecting if space was pressed, but don't repeat the action if it is held down?

Posted Oct 25, '13 at 5:33pm

mightybob

mightybob

353 posts

So what I need is in my game you can press space to jump. Except, i don't want them to be able to hold space and keep jumping every time they hit the ground. I need the action to happen once for each time they hit space, but not to repeat every frame. Any ideas?

Thanks!

 

Posted Oct 25, '13 at 6:01pm

weirdlike

weirdlike

588 posts

Knight

just make the keypress event a function instead of switching a boolean and using the enter frame loop

ex.
addEventListener(KeyboardEvent.KEY_DOWN, keyPress);
function keyPress(event):void
{
      //jump code here
}

normally you would need a key down and a key up for switching

-------------------------------------------------------------------------------------

if you absolutely must use a loop then I recommend using it to execute a separate function that is dependent on a boolean

//boolean initially false
private var jumpLock:Boolean = false;

//loop
if(space == true)
{
     //if key is pressed loop function
     jumpFunction();
}
else
{
     //false if key is not pressed
     jumpLock = false;
}

//loop the function every frame
private function  jumpFunction():void
{
     if(jumpLock == true)
     {
          //do nothing
     }
     else
     {
          //make boolean true
          jumpLock = true;

          //jumpfunction
     }
}

hope this helps :)

 

Posted Oct 26, '13 at 10:21am

mightybob

mightybob

353 posts

Thanks, this helped a lot!

 
Reply to Detecting if space was pressed, but don't repeat the action if it is held down?

You must be logged in to post a reply!