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

2 33274
mightybob
offline
mightybob
360 posts
Peasant

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!

  • 2 Replies
weirdlike
offline
weirdlike
1,299 posts
Prince

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

mightybob
offline
mightybob
360 posts
Peasant

Thanks, this helped a lot!

Showing 1-2 of 2