Action Script 3, How to disable keys? - actionscript-3

If there's too many functions, so It is very hard to "removeEventListener" each one,
Is there any way to disable all keys temporarily?
Thank you.

"Is there any way to disable all keys temporarily?"
Can you not just use .removeEventListener(KeyboardEvent.KEY_DOWN...?
Either your Stage or some MovieClip is listening for key press event, right? eg:
stage.addEventListener(KeyboardEvent.KEY_DOWN, handle_KeyPress);
Where your handle_KeyPress function, which handles all key presses, looks like:
function handle_KeyPress ( evt:KeyboardEvent ) : void
{
//# RIGHT ARROW or numpad 6 (arrow)
if ( evt.keyCode == 39 || evt.keyCode == 54 || evt.keyCode == 102)
{
//do something if Right arrow
}
//# SPACE BAR
if ( evt.keyCode == 32)
{
//do something if Space bar
}
}
PS:
Show an example of code with "too many functions" (eg: give small example how they're spread out it). It's possible you need to re-think / re-structure your code if it's not currently flexible.

If your goal is just to temporarily "pause" the event handlers, you could throw in a simple boolean:
var eventsHandled:Boolean = true;
And inside the event handler functions you would use it as a condition:
function buttonClicked(evt:KeyboardEvent):void{
if(eventsHandled){
//do stuff
This is just a simple bandage. VC.One's answer is probably hinting into your actual problem and in some point you'll have to face it.

Related

Actionscript 3 equivalent of KeyboardEvent.Repeat

I'm very much a beginner when it comes to programming; I'm doing a flash game for my 2D Game class on Adobe Animator, and I had a doubt about the code that my instructor couldn't answer himself. Long story short, I want the character speed to increase based on how long the key has been pressed, so I came up with this:
spdX = spdX + aclMov*(tempo) - aclFrc*(tempo);
Where the variable tempo would increase as long as the key is being held down, and I would check if it is with KeyboardEvent.repeat, as in:
if(heldDown){while(heldDown){tempo += 1}}
else{tempo = 0}
spdX = spdX + aclMov*(tempo) - aclFrc*(tempo);
However when I try to do that, the output responds with "Property repeat not found on flash.events.KeyboardEvent and there is no default value". I assume that this is because KeyboardEvent.repeat is not defined in the medium I'm using. Is there anyway I can reproduce the same effect of KeyboardEvent.repeat, perhaps by creating a function that mimics what it would have done?
Thanks in advance.
(Edit 1)
I begin apologizing for my shortness of clarification, as well as my ignorance in the topic as I am barely a beginner when it comes to as3, and am not properly presented yet to many of the terms I've read.
So, thanks to the meaningful contributions of comments, I already have been given a glimpse of what kind of workaround I would need to do to substitute KeyboardEvent.repeat. There are other parts of the code of relevance to the problem, as well:
stage.addEventListener(KeyboardEvent.KEY_DOWN,pressKey)
function pressKey (Event){
(...)
if(Event.keyCode == (Keyboard.A)) {left = true;}
(...)
}
stage.addEventListener(KeyboardEvent.KEY_UP,releaseKey)
function releaseKey (Event){
(...)
if(Event.keyCode == (Keyboard.A)) {left = false;}
(...)
}
This is how the code was intended to go. It was suggested that I use the getTimer() method to record the moment the event KEY_DOWN happens, stopping when the KEY_UP comes into effect. Problem is, how can I increment the code to make it differentiate between those two events, and more specifically, how can I adapt the ENTER_FRAME event so that differentiating between them still works with it? Here's the most relevant parts of it, by the way:
addEventListener(Event.ENTER_FRAME,walk);
function walk(Event) {
if(left) {
(...)
char.x -= spdX;
(...)
}
I assume that the code worked up till now because, as the state of "left" constantly switched between "true" and "false", the if conditional was met repeatedly, leading the character to move. However, if I try to make it so that the conditional depends on "left" staying "true" for a certain time, the code becomes incompatible with itself.
In short, it brings the question of how to adapt the "KEY_[]" event listeners and the "walk" function to work, in using the getTimer() method, to work together.
Again, thanks in advance.
I believe that would be somehow self-explanatory .
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
addEventListener(Event.ENTER_FRAME, onFrame);
var pressedKeyA:int;
// Never name variables and arguments with the same name
// as existing classes, however convenient that might seem.
function onDown(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.A)
{
// Let's record the moment it was pressed.
pressedKeyA = getTimer();
}
}
function onUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.A)
{
// Mark the key as not pressed.
pressedKeyA = 0;
}
}
function onFrame(e:Event):void
{
// It is true if it is not 0.
if (pressedKeyA)
{
// That's how long it has been pressed. In milliseconds.
var pressedFor:int = getTimer() - pressedKeyA;
// Change the position with regard to it.
// For example 1 base + 1 per second.
char.x -= 1 + pressedFor / 1000;
}
}

AS3: pass Keyboard control to child movieclip and back to main timeline

EDIT: I don't know if this is the norm, but I preferred to leave the original question in and add updates. Please, feel free to let me know if I should eliminate the original code snippets and somesuch.
I am trying to create a slideshow-like presentation in flash CS6, using a main timeline with one symbol in each frame and the different animations (some quite complex) in those symbols. Since I'm going to use a presenter remote, I've captured the keystrokes and coded pg_up and pg_down to go to the next and previous frame respectively:
stage.addEventListener(KeyboardEvent.KEY_DOWN, pagerFunction);
var symb:movieClip;
function pagerFunction(e:KeyboardEvent):void
{
var myKey = e.keyCode;
if (myKey == Keyboard.PAGE_DOWN){
if (symb != null){
//some code that allows to control the symbols timeline forward
} else {
nextFrame();
}
}
if (myKey == Keyboard.PAGE_UP){
if (symb != null){
//some code that allows to control the symbols timeline backward
} else {
prevFrame();
}
}
The problem I'm having is the following. I've added framelabels and stop(); code inside the symbol animations where I needed to control the step from one animation to the next one. However, after having tried numerous solutions on the web, I haven't been able to succeed having the symbols react to pg_up and pg_down as if they were part of the main timeline.
To sum up, what I need to solve is this:
Enter Main timeline Frame
Identify symbol instance (labeled as _mc)
Inside symbol timeline, play from first frame (labeled '0') until next labeled frame ('1' and so on)
stop and wait for next pg_down to start playing from next labeled frame to the following (i.e. '1'-'2'), or pg_up to start playing from the previous labeled frame (i.e. '0' to '1') (for this, I would use a variable to keep track.
on last frame (labeled 'final') exit symbol focus and return keyboard control to main timeline to allow pg_down and pg_up to move to the next / previous frame. on pg_up on symbol.currentFrame == 0, do same.
BTW, if there's a better way to achieve this, I'm open (and quite desperate) for better suggestions / solutions.
Thank you so much to anyone who can help!
Edit: Ok, I guess I wasn't too clear on the issue, so I'll try to add a bit to this:
addEventListener(KeyboardEvent.KEY_DOWN, mc_pagerFunction);
var lbl:String;
var counter:Number = 0;
function mc_pagerFunction(e:KeyboardEvent):void {
var myKey = e.keyCode;
if (myKey == Keyboard.PAGE_DOWN){
lbl = this.currentFrameLabel;
if (this.currentFrameLabel == 'final'){
stop();
stage.focus = this.parent; //which would be the main timeline
} else if (Number(lbl) == counter){
this.gotoAndStop(lbl);
counter++;
} else {
this.gotoAndPlay(lbl);
}
}
if (myKey == Keyboard.PAGE_UP){
lbl = this.currentFrameLabel;
if (this.currentFrameLabel == '0'){
stop();
stage.focus = this.parent; //which would be the main timeline
} else if (Number(lbl) == counter){
this.gotoAndStop(lbl);
counter--;
} else {
this.gotoAndPlay(lbl);
}
}
}
Now, this bit is the behaviour I'd like to see inside the symbol when the main timeline goes into the next frame, thus being able to use the main timeline as sort of slideholder and the real thing happening inside the symbol.
Btw, I'd like to try and keep all code within the main action layer, not in the symbols. I tried that, shifting focus to the symbol and it didn't work either, and having code all over the place grates against my nerves ;).
I hope this throws some light on what I'm stuck at.
Again, any help is appreciated. Thanks all in advance
UPDATE:
Please someone help me out here!
This is what I'm trying. Logically, it makes all the sense in the world, except that it doesn't work.
var symb:MovieClip;
symb = MovieClip(root); //assign symbol I want to be controlled by pg_up/pg_down
symb.focusRect = false;
stage.focus = symb; //focus on current symbol
symb.addEventListener(KeyboardEvent.KEY_DOWN, mc_pager); //add keyboard event listener
function mc_pager(e:KeyboardEvent):void{
var myKey = e.keyCode;
if (myKey == Keyboard.PAGE_DOWN){
do{
symb.play(); // it plays, then checks if the lbl is null or final, then quits
} while (symb.currentFrameLabel == null && symb.currentFrameLabel != 'final');
symb.stop();
symb.removeEventListener(KeyboardEvent.KEY_DOWN, mc_pager);
stage.focus=MovieClip(root); //return focus to main timeline (in the next keyframes, the focus is on the nested _mc
}
if (myKey == Keyboard.PAGE_UP){
do{
symb.prevFrame();
} while (symb.currentFrameLabel == null && symb.currentFrameLabel != '0');
symb.stop();
symb.removeEventListener(KeyboardEvent.KEY_DOWN, mc_pager);
stage.focus=MovieClip(root);
}
}
Where am I being to moronic to get it right? Please, guys, you're the experts, I need your advice here. Thanks!
UPDATE:
Doing a trace on symb, it seems like as soon as it enters the function, it forgets the initial assignment (symb = MovieClip(root)) and shows null. Why?
In this sample, I created a basic proof of concept where I have a circle MC with an instance name of "c" on the main timeline. Within this mc, I created with 2 keyframes inside with stop actions on both. I colored the circle a different color on frame 2 and labeled it as "two".
In the Main timeline I have the following code:
import flash.events.KeyboardEvent;
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyEvt);
function keyEvt(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.PAGE_DOWN){
trace("down");
c.gotoAndPlay("two");
}
}
This should help form a foundation for your code as long as you stick with targeting the symbol through direct reference and ensure your keyboard event is attached to the stage.
Also, always stick with getting a basic working version down first. I.E. Check to see if your keyboard listeners are working for your target object and then build additional functionality off of that.

Redirect ENTER key to different command (AS3)

I have a textbox for which I want the space key to be executed every time a person hits the enter key INSTEAD OF adding an extra line. I am using the following code but to no avail:
txtVerbs.addEventListener(KeyboardEvent.KEY_DOWN, enterkey);
function enterkey(event:KeyboardEvent):void{
if (event.keyCode == 13){event.keyCode == 32}}
Try this:
txtVerbs.addEventListener(KeyboardEvent.KEY_DOWN, enterkey);
function enterkey(event:KeyboardEvent):void{
if (event.keyCode == Keyboard.ENTER){ // you should use the Keyboard constants instead of the hard value
event.preventDefault();
event.stopImmediatePropagation();
txtVerbs.text += ' ';
}
}
stopImmediatePropagation() prevents the event from traveling any further, so it will stop any other KEY_DOWN event further down the line and should (at least from what I remember) stop the KEY_UP from firing as well.
preventDefault() cancels the default behavior of an event, if it is possible to be cancelable. If memory serves, the key being pressed is cancelable. If it isn't, however, you could also do a RegEx replace.
txtVerbs.addEventListener(KeyboardEvent.KEY_UP, enterkey);
function enterkey(event:KeyboardEvent):void{
if (event.keyCode == Keyboard.ENTER){ // you should use the Keyboard constants instead of the hard value
txtVerbs.text = txtVerbs.text.replace(/\r?\n/gm, ' ');
}
}
That should match any newline character (it is \r\n on some systems and just \n on others) and replace it with a space

Using QWER keys to jump to a specific scene in AS3

TLDR: I need code in action script 3 which will let users press keys like QWER to jump to a specific scene.
So what I'm doing is creating and interactive comic within flash, and to be blunt I didn't know any AS3 code before this and still pretty much know none.
So I'm going to need some help on this one and I think it is worth mentioning that I am using sound in this project.
what I need to know is how to use letter keys (eg. QWER) to act as shorts cuts to jump to specific scenes. What I have so far which is working is this and another version which uses a mouse click instead.
stop(); ( 1 )
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_KeyboardDownHandler);
function fl_KeyboardDownHandler(event:KeyboardEvent):void {
gotoAndPlay(currentFrame+1);
}
and of course all this does is advance the frame, which I do need for some sections of dialogue but that's the basis I've been trying to get it to work.
I do know that q = 81, w = 87, e = 69 and r = 82.
Besides that I've got nothing and I need some help real bad.
You need to check which key has been pressed, you can do it like this:
function fl_KeyboardDownHandler(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.Q){
//do what you need to do when Q was pressed
}else if(event.keyCode == Keyboard.W){
//same for W
}
...etc
}
The KeyboardEvent instance contains data about the event itself, part of it being keyCode, which gives the code of the pressed key. Using this property, you can detect which key the user pressed, and react accordingly.
As you understood, you can use gotoAndPlay() and gotoAndStop() to move around your animation.
It gives us the following code :
stop();
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_KeyboardDownHandler);
function fl_KeyboardDownHandler(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.Q) {
gotoAndPlay(1); // Back to the start
} else if (event.keyCode == Keyboard.W) {
gotoAndPlay(currentFrame-1); // Back one frame
} else if (event.keyCode == Keyboard.E) {
gotoAndPlay(currentFrame-1); // Forward one frame
} else if (event.keyCode == Keyboard.R) {
gotoAndPlay(100); // Go to 100th frame
}
}
Note that I am using the Keyboard class to get the keyCode associated to a specific key.

AS3: Multiple options in one key and preventing multiple key presses

I have a "pause function" in my AS3 code, the problem is that i can't figure the logic necessary to give the letter "P" the capacity to pause and unpause and at the same time limit the number of presses to one at a time. My code so far (working ,yes, but without the "one press at a time" limit).
public function PauseDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.P)
{
pause = true;
trace ("apreté pausa");
pausa();
}
}
public function pausa():void
{
trace ("pausa");
if (pause == true && paused == false)
{
paused = true;
backgroundLvL1.removeEventListener(Event.ENTER_FRAME,update);
}
else if(pause == true && paused == true)
{
paused = false;
backgroundLvL1.addEventListener(Event.ENTER_FRAME,update);
}
}
Your 'PauseDown' function should probably be called something else, because it's going to be called whenever ANY key is pressed; Something like 'keyPressed' is probably more descriptive.
If you want to have only ONE key acknowledged as the most recently pressed key, I would set a variable (eg _currentKeyCode) to the event.keyCode in the 'keyPressed' function. Then, in your game loop function you can check the value of _currentKeyCode and have the game respond accordingly.
In the 'keyPressed' function you could also still include your test to see if 'P' has been pressed.
Note that you should also have a 'keyReleased' function, triggered on a KeyBoardEvent.KEY_UP event. This could check if _currentKeyCode == the event.keyCode and, if so, set _currentKeyCode to -1. Then, in your game loop, -1 would signify no key presses.
One last, slightly irrelevant, thing: In the 'pausa' function you don't need to check if 'pause == true' because the pausa function is only called when pause == true.