Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




Keyboard Event Listener Problem



Hi there, I'm new to actionscript, and need some help. I want to play a movieclip when a user presses a key, and then play a different movieclip when they release the same key. I have the following small code which traces key codes, pressed and released. Could this be converted to do what I want? stage.addEventListener(KeyboardEvent.KEY_DOWN,checkKeysDown);stage.addEventListener(KeyboardEvent.KEY_UP,checkKeysUp);function checkKeysDown(event:KeyboardEvent):void{trace("You pressed key: "+event.keyCode);}function checkKeysUp(event:KeyboardEvent):void{trace("You released key: "+event.keyCode);}any help on this would be appreciated.Morgan.Edited: 05/26/2008 at 02:38:27 PM by noNick77



Adobe > ActionScript 3
Posted on: 05/26/2008 02:28:04 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Keyboard Event Listener Problem
i have built a space game. i am using numbers for the menu screen. when the user presses 1 i want 10 instances of a movieclip called blackhole to be added to the stage and when the user presses 2 i want 5 instances of the same movieclip to be added to the stage. This works as an easy and normal setting. However when the user presses 1 or 2 i get this error -

Error: Error #1023: Stack overflow occurred.
at spaceGameMobileMenuWorkingPublished_fla::MainTimel ine/position()
at spaceGameMobileMenuWorkingPublished_fla::MainTimel ine/position()
at spaceGameMobileMenuWorkingPublished_fla::MainTimel ine/position() etc.....

Here is my code -


Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, chooseStart);//adds an eventlistener to the stage to listen for a keyDown event
function chooseStart(evt:KeyboardEvent):void
{
if(evt.keyCode == 49)//listens for the 1 key
{
openingSoundSC.stop();//plays the openingSound
moon.visible = true;//shows the moon movieclip on the stage
for(i = 0; i < 10; i++)//executes the for loop for 10 times
{
blackHole.x = Math.random() * stage.stageWidth;
blackHole.y = Math.random() * stage.stageHeight;
position(blackHole);
blackHoles.push(blackHole);//stops blackholes overlapping
blackHoles.push(moon);//stops blackholes and moon overlapping
blackHoles.push(gameTimer_tb);//stops blackholes and gameTimer overlapping
blackHoles.push(lives_tb);//stops blackholes and lives_tb overlapping
blackHoles.push(spaceship_mc);//stops blackholes and spaceship_mc overlapping
addChild(blackHole);//add the blackhole to the stage
}
gravity = 1;//sets the gravity to 1
timer.start();//starts the timer
addChild(spaceship);//adds the spaceship to the stage
spaceship.x = 30;
spaceship.y = 20;//positions spaceship
removeChild(startButton);//removes startButton from stage
removeChild(easy);//removes easy button from stage
removeChild(hard);//removes hard button from stage
removeChild(exit);//removes exit button from stage
removeChild(splashScreen);//removes splashScreen from stage
removeChild(instructionsText);//removes//instructions text from stage
stage.removeEventListener(KeyboardEvent.KEY_DOWN, chooseStart);//removes the start event listener
stage.removeEventListener(KeyboardEvent.KEY_DOWN, chooseHard);//removes the hard event listener
stage.removeEventListener(KeyboardEvent.KEY_DOWN, chooseExit);//removes the exit event listener
}
else if(evt.keyCode == 50)//listens for the 2 key
{
moon.visible = true;
for(i = 0; i < 5; i++)//executes the for loop for 5 times
{
blackHole.x = Math.random() * stage.stageWidth;
blackHole.y = Math.random() * stage.stageHeight;
position(blackHole);
blackHoles.push(blackHole);
blackHoles.push(moon);
blackHoles.push(gameTimer_tb);
blackHoles.push(lives_tb);
blackHoles.push(spaceship_mc);
addChild(blackHole);
}
gravity = 1;
timer.start();
addChild(spaceship);
spaceship.x = 30;
spaceship.y = 20;
removeChild(instructionsText);
removeChild(startButton);
removeChild(easy);
removeChild(hard);
removeChild(exit);
removeChild(splashScreen);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, chooseStart);
}
}
Can anyone help?

Global Event Listener For Keyboard (as3)
(the following concerns only actionscript 3. Any suggestions in as3 are greatly appriciated)
hey,
I've been wondering if there is a quick and painless way to add a keyboard event handler to an entire fla, as apposed to a single element on the form.
Basically, what I'm saying is, I understand the concept of applying a listener to an object, but I'd benefit more from an event listener, listening to keyboard input, that isn't bound to an object, but is always triggered regardless of the current focus.

I might not be clear on my intentions, so I'll give an example. I have a form with a movieclip, a textfield, and a bitmap on the stage. Now i want to add an event listener to listen to keyboard input, but i don't want the listener to be added to any of the thing on the stage, ie. the movieclip, textfield... Instead I want a event listener that works on a higher level then those items, and always fires regardless of current focus.
In AS2, key.addlistener(receivingOBJ) is similar to what i want to achieve. Anyone have any advice on how to add this kind of functionality? --there are 10 types of people in this world. those who know binary, and those who don't.--

Keyboard Event Listener Not Catching ENTER Key
I'm using the Flash 9 public alpha with AS3 and it appears that the enter key does not trigger a KeyboardEvent... The only way to get it to work is when the focus is inside a textbox.

Does anyone have a workaround?

Setting Up An Event Listener To Listen For An Event Inside Of Another Movieclip.
I'm trying to set up an event listener on the stage that will listen for a mouseEvent.CLICK on a certain button inside a movieclip on the stage, but i cant seem to figure out how to target that specific button. Any help would be greatly appreciated.

Passing Parameters From Event Listener To Event Handler
Hi Chaps,

First of all, apologies as I know this question has been asked before, but I have spent the last twenty minutes reading this thread and still can't seem to figure out how to apply it to my situation - probably because I'm thick!

I have a number of objects which need to be rotated according to different parameters. I have a function which takes those parameters, then uses the tween class to handle the rotation. I'm then using the tweenEvent class to check for when the motion is complete. Then, I need access to those same parameters in the complete handler to do further operations. The problem I have is that the tween event class doesn't allow me to pass the parameters along to the cpmpleteHandler, so I'm stuck getting my parameters from the first function to the second function:


Code:
function rotate(parameters){

rotationTween = new Tween(object,parameter1,parameter2,........);

rotationTween.addEventListener(TweenEvent.MOTION_FINISH,completeHandler);

}

function completeHandler(e:TweenEvent){

//need access to the paremeters passed into the first function here!!

}
From reading the thread mentioned above, I have a feeling I may need a custom class to do this - please don't laugh but I've never written (or had the need to) write my own class before, so I really wouldn't know what to do. Any help greatly appreciated, but an actual code snippet which demonstrates this would be even better!

Ric.

Event Listener Mouse Event Click - Obstructions
This is an oversimplification of my problem.

I have an event listener on a sprite.
I then have portions of this sprite covered with other sprites or moveclips.

If I click a movieclip, it blocks my eventlistener on the sprite underneath it.

Is it possible to listen to the even click 'through' a movieclip. I dont want interaction with them, but I dont want them as bitmap data onto the base sprite either...

Global Keyboard Listener
I'm trying to make a class which listens to and handles keyboard events. However I can get it to work. Instead I get this error message.

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at test::Class02$iinit()
at test::Class01$iinit()

How can I fix this?

Class01.as


Code:
package test{
import flash.display.Sprite;

public class Class01 extends Sprite{
private var class02:Class02;

public function Class01() {
class02 = new Class02;
}
}
}
Class02.as


Code:
package test{

import flash.events.*;
import flash.display.*;

public class Class02 extends Sprite{
public function Class02(){
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
}
private function keyPressed(e:Event):void {
trace ("Key Pressed");
}
}
}

Keyboard Listener Not Working?
Hello, I am new here, and new to ActionScript as well. Thanks for taking the time to read the post, I've spent the last two days searching this up before I finally gave up, so sorry this must have been posted many times.

ActionScript Code:
function handle(e:KeyboardEvent):void
{
    trace(e.toString());
    if(e.charCode == 65)
        trace("you pressed a");
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, handle);

Anyways, what seems to be weird is that when I press a lowercase 'a', the event doesn't seem to be handled (for example, there is no trace), but when I press 'shift+a', I get the correct output I'm looking for. I can get this to work for arrow keys, etc. But I just thought if I were to make more complex games or websites, that having the other keys would benefit me quite a bit. The only work around I can see (of course unless I'm doing something wrong), is to press the shift key for the user whenever the flash stage has focus..

Anyways, sorry my post gets long winded! Thanks for your time.

Keyboard Listener Oddity - Any Ideas?
Hi folks, I'm trying to catch "delete" keys and I use a key listener for that. Only... it seems that some keys, including delete just don't trigger that listener. Did I do anything wrong? Any ideas?

When I use this I see "key" for every normal character I press, but I never see "del" and -- more than that -- I don't even see "key" when I press the Delete key. It seems delete doesn't send the key event for whatever reason (neither does backspace, etc.)

<pre>

KeyListener = new Object();
KeyListener.onKeyDown = keyHandler;
Key.addListener(KeyListener);

function keyHandler() {
trace("key!");
if (Key.isDown(Key.DELETEKEY)) {
trace("del");
}
}

</pre>

Ideas? thoughts? Advice?

Juggle5

Sandboxed Stage,want To Add A Keyboard Listener.
after reading grant skinner's post about Flash 9's failure to unload:
http://www.gskinner.com/blog/archive...e_to_unlo.html

method 3: " You can load content SWFs from a subdomain. This will place it into a security sandbox implicitly.", sounded like a simple solution for getting around the issue. The problem is when a swf is sandboxed you are not allowed to access the stage, so how can I track keyboardEvents?

[CS3] [AS2] Keyboard Listener And Getting Variable Back
Hello,

I made a login creation system with Flash CS3 for my website.
Everything's fine: you enter your login and click on a button and the system sends the data to a php script which verifies it. If the word chosen is ok, it's recorded in a database. Then, according to the word, a message is sent back to flash (success or error messages).

Now I have created a keyboard listener in case the user hits the enter key instead of pushing the button after typing his login.
It's also ok, the login is stored to the database which is a proof that the php script is working the way it should in the background.

The issue is that, if I use the button, I do get a notification message back as expected but if I use the enter key, I don't...

Here's a sample of my actionscript code:


Code:
//Receive
receiver.onLoad = function (psuccess){
valid.validation_pass.text = this.validation_pass;
gotoAndPlay("manage_password");
}

//Send with button
addPassword.onRelease = function (){
sender.newPass=inputPassword.text;
sender.sendAndLoad ("pass_create.php", receiver, "POST");
}

//Send with keyboard
var listenerKeyboard = new LoadVars();
listenerKeyboard.onKeyDown = function(){
if(Key.isDown(Key.ENTER))
{
sender.newPass=inputPassword.text;
sender.sendAndLoad ("pass_create.php", receiver, "POST");
}
}
Key.addListener(listenerKeyboard);
According to the behaviour, there is nothing wrong with the sender (as the login is well recorded to the database) and there shouldn't be a problem with the receiver as it works just fine with the button.
Whatever the problem, I'm stuck and don't know how to solve the problem...

My tests are made directly from my online server and I tried with Firefox 2 and IE6 with the same result.

Thank you for your help!

[AS3] Keyboard Listener - Detecting Capital Letter
hi guys, I want to find out how to get capital letter keyCode

The code below returns the ascii number of the keys located on the keyboard.
But those are uppercase case. How about lower case?

Example: when i press/hit the key 'a' it returns 65.
In the ascii chart, 65 is capital A.
When I try SHIFT + 'a', it returns 16 and 65.
How to solve this?


ActionScript Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);function keyDown(event:KeyboardEvent):void {    trace(event.keyCode);}


edit: found my solution here. Credits to Nutrox on UltraShock
http://www.ultrashock.com/forums/actionscript/keypress-for-as3-96851.html

ActionScript Code:
stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler );stage.addEventListener( KeyboardEvent.KEY_UP, keyUpHandler ); var pressedKeys:Object = {}; function keyDownHandler( e:KeyboardEvent ):void{    // The keyDown event is repeatedly fired while a key is    // held down, so we can do this to ensure we only deal with    // the event the first time a key is pressed.    if( pressedKeys[ e.keyCode ] )    {        return;    }        pressedKeys[ e.keyCode ] = 1;        //        trace( "KEY PRESSED" );    traceEvent( e );} function keyUpHandler( e:KeyboardEvent ):void{    delete pressedKeys[ e.keyCode ];        trace( "KEY RELEASED" );    traceEvent( e );} function traceEvent( e:KeyboardEvent ):void{    trace( "keyCode   ", e.keyCode );    trace( "charCode  ", e.charCode );    trace( "character ", String.fromCharCode( e.charCode ) );    trace( "" );}

Mouse Event Add Event Listener?
sorry, could not think of a better title!
anyway,
I downloaded a class that perfectly works for me,
it's basically a cube that rotates depending on mouse movement,
the way it does it is with the following line:

spBoard.addEventListener(MouseEvent.MOUSE_MOVE,boa rdMove);


what this does is, whenever the mouse moves the cube moves
the boardMove function does the movement based on the mouse's current position

but what i want to do is the keep the cube moving, if the mouse is on its left, it keeps rotating left, and on its rght, keep rotating right...and preferably to have the speed increase/decrease depending on how far/close mouse is to the center of the cube

any suggestions?
firstly is there an event listener that keeps calling the function just for the mouse 'being there' ? i tried rollover, didn't work

or maybe the boardMove function should be modified? i have no idea how though, totally new to AS3, here's the boardMove function for refrence:


ActionScript Code:
private function boardMove(e:MouseEvent):void {
        
                var locX:Number=prevX;
               
               
       
                if(doRotate){
               
               
                prevX=spBoard.mouseX;
                               
               
               
               
                               
                curTheta+=(prevX-locX);
                                   
               
               
                renderView(curTheta);
               
                e.updateAfterEvent();
               
                }
    }

About Keyboard Event
hi,

i've been searching thoughout the board for awhile already
and tried to test the code out,

but still i don't have any luck yet to get my code running properly.

this is what i trying to do.
i want to have a textBox that the number inside will change(increase) whenever i press on 'q' and change(decrease) whenever i press on '-'

this is what i am curretly trying

on(release, keyPress"q")
{
mytext.text = ++;
// i think i need to parse the text out first as an int
// and then try putting it back

}

about 'mytext' i made it as a 'texttool' with 'dynamic property'

any help would be really appreciate.

Tom

Keyboard Event
hello,

I would like to know if there's a code to simulate the same thing when you type on the beyboard.
I would like to have by code the same thing as SendKeys({ESC}) in VB.

Thanks,

Jerome.

Keyboard Event
Hi all,

I am having this strange problem with keyboard event where it doesn't respond when I pressed on certain keys like c and some others. I am only having trouble with lowercase letters, when I hold shift then all the keys work.

And it's not my keyboard since I can type the letters fine, I event swapped out keyboards just to test ><.

Mahalo,
Wen

Event Listener?
Hi,

I have an flv playing in my media display, but when the flv ends I want to "go to and play" a specific frame. The media diplay is a movie with additional graphics and a media controller attached to it. I am working in "screens" mode, does this pose any problems like having to tell it which frame # in which screen?

Event Listener?
Hello everyone,

I'm trying to learn Flash from a book and I've been getting on OK but I want to do something that my book doesn't cover.

I've got an invisible button the same size and shape and in the same position as a square dynamic text field. When the button is pressed, a movie-clip (about twice the size of the button/text field) plays around the same position. The movie-clip has 39 frames but I've set it to stop on frame 20. On frame 20, the user is presented with a set of buttons numbered 1 to 9 (and a delete button labelled 'X') arranged in a dial around the dynamic text field (and, of course, the invisible button). If the user clicks one of the numbered buttons, that number is placed in the dynamic text field, and the movie-clip completes. The movie-clip also completes if the user clicks the original invisible button a second time (this leaves the dynamic text field unchanged.) The general effect is that the dial of numbered buttons grows from the centre of the text field and then shrinks back into it when a number is chosen.

All this works fine so far, however I have several invisible buttons (with associated dynamic text fields and movie-clips) identical to the one above, and I only want one movie-clip to be active at any one time. What I'm hoping to do is to arrange things so that the movie-clip will complete if the mouse-pointer moves outside of the movie-clip area.

I imagine I'd need some kind of event listener to do that and possibly something to do with _xmouse and _ymouse, but I haven't been able to work out how to do it.

Any help you can give me would be much appreciated.

Cheers,

Jeff

Event Listener?
Hello everyone,

I'm trying to learn Flash from a book and I've been getting on OK but I want to do something that my book doesn't cover.

I've got an invisible button the same size and shape and in the same position as a square dynamic text field. When the button is pressed, a movie-clip (about twice the size of the button/text field) plays around the same position. The movie-clip has 39 frames but I've set it to stop on frame 20. On frame 20, the user is presented with a set of buttons numbered 1 to 9 (and a delete button labelled 'X') arranged in a dial around the dynamic text field (and, of course, the invisible button). If the user clicks one of the numbered buttons, that number is placed in the dynamic text field, and the movie-clip completes. The movie-clip also completes if the user clicks the original invisible button a second time (this leaves the dynamic text field unchanged.) The general effect is that the dial of numbered buttons grows from the centre of the text field and then shrinks back into it when a number is chosen.

All this works fine so far, however I have several invisible buttons (with associated dynamic text fields and movie-clips) identical to the one above, and I only want one movie-clip to be active at any one time. What I'm hoping to do is to arrange things so that the movie-clip will complete if the mouse-pointer moves outside of the movie-clip area.

I imagine I'd need some kind of event listener to do that and possibly something to do with _xmouse and _ymouse, but I haven't been able to work out how to do it.

Any help you can give me would be much appreciated.

Cheers,

Jeff

Key Event Listener
Hi,

i'm doing a game using the keyboard as controls.

I upload it onto the web and not all keys are working. Is it because of the below?


Quote:




A Flash application can only monitor keyboard events that occur within its focus. A Flash application cannot detect keyboard events in another application.




But if that is the case, why not all keys but only some are not working?

The arrow keys are working fine but the letters are not?

Anyone, any idea?

Event Listener...
I have a client that would like his video to auto play on initiation(frame 6) but as soon as the video is over gotoAndPlay(5) which would give the user the option to play the video again or select other various options(which means the video needs to be gone).

I was trying to use a listener to determine when the FLV is finished to navigate back to another frame. I believe I'm missing something here... Here is my script in frame 6

stop();
var listenerObject:Object = new Object();
listenerObject.stopped = function(eventObject:Object):Void {
gotoAndPlay(5);
};
my_FLVplybk.addEventListener("stopped", listenerObject);

Event Listener
Hi!

Is there any way of getting all the events triggered by an SWF? We need to get the name of the component (MovieClip, Button, Input Text...) which has received the event.

Any clue?

Best

Event Listener Help
What is the most efficient way of detecting when a movie clip has reached a certain frame?

The only method i know atm is adding a onEnterFrame listener and then checking every frame, but i doubt this is really efficient.

Event Listener Help
Hi, I am trying to get an event listener to work. It is just a mouseclick that traces "Click". Right now it only works when I click on the movieclip. I want it to work when I click anywhere on the stage.

Here is my code:
Main:

Code:
package src{
import src.Character;
import flash.display.MovieClip;
public class Main extends MovieClip {
public var char:Char;

public function Main() {
char = new Char();
char.x = char.y = 50;
stage.addChild(char);
}
}
}
Character:

Code:
package src{
import flash.display.MovieClip;
import flash.events.*;
public class Character extends MovieClip {

public function Character() {
this.gotoAndStop(1);
this.addEventListener(MouseEvent.CLICK, Click);
}
function Click(e:MouseEvent) {
trace("Click");
}
}
}
Please help.

Some Help Please With An Event Listener
Hi guys,

How can I create an event listener that detects when I resize
a text field dynamically?


ActionScript Code:
inputField.addEventListener(Event.CHANGE,onResizeField);

function onResizeField(event:Event):void{
   
    trace("has been resized");
}

The above doesn't work and I have tried already Event.RESIZE
without access.

Any ideas?

Thanks a lot

Event Listener
Hey there. I am, to say the least, new at writing code. Here is my problem. I currently have a video that plays thru my instance called clydeplayer as seen in the following code:

on (rollOver) {
this.gotoAndPlay("s1");
}
on (releaseOutside, rollOut) {
this.gotoAndPlay("s2");
}
on (release)
{
_root.myMC.clydeplayer.contentPath = "http://www.clydemedia.com/Video_for_site/GAN111.flv"
}


What I would like to happen after this video clip "GAN111.flv" plays is to have another video, located in the same spot, start playing automatically.

like I said, I really have very little knowledge on how to do this so any help would be great. thanks!

Event Listener?
Can anyone help me....

I am making a flash banner and it goes like this...

I have the first moveicip playing on the main timelne and then buttons that contrtol the movie loadd in... you can click on button 1 and it will take you to frame 122 where the second movie clip is and clilck on button 2 to go to frame 123 which is the third movieclip and button three restarts the first movieclip by going back to frame 1....

however, there are two things I am trying to do... I want to figure out the code that will make the movie (on main timeline) play frame 122 then frame 123... if no buttons are pressed and reloop.... but go to a specific movieclip when pressed...

and also in my movies... the buttons are not going the the main timeline.... they're playing frame 122 anda frame 123 of the current timeline (i loaded the second and third moviecip onto the timeline on frames 122 and 123 respectively)....

where do i put the code and does anyone have any ideas... I know i may have to use an event listener i think to control the timeline.. i dunno.. i'm pretty new at this.. a bit stuck...

jan

Event Listener
Hi Guys,

How can i create custom event in AS 3.0.

Thanks
MS

Event Listener
I have a script that creates falling snow. I want to be able to control the amount of snow from a slidebar how would I do this? In this case "snow_per_second" controls how much it will snow.
The current script: (sorry it's a bit long)








Attach Code

var speed:Number = 3;
var total_snow:Number = 20;
var snow_per_second:Number = 4
var hit_target:MovieClip = myObject
//
var holderSnow:Sprite = new Sprite();
var target_shake:Boolean = false;
//
addChild(holderSnow);
//
hit_target.mainX=hit_target.x;
hit_target.mainY=hit_target.y;
//
function createSnow() {
var snow:MovieClip = new MovieClip();
snow.graphics.beginFill(0xFFFFFF);
snow.graphics.drawCircle(0,0,Math.random()*3);
reset(snow);
addBlur(snow);
snow.addEventListener(Event.ENTER_FRAME,fall);
holderSnow.addChild(snow);
}
function reset(s:MovieClip) {
s.hit=s.shake=false;
s.y=0;
s.x=Math.random()*970;
s.xspeed=Math.random()*speed-(speed/2);
s.yspeed=Math.random()*speed+1;
}
function init(e:Event) {
for(var i=0; i<snow_per_second; i++) {
createSnow();
}
snow_id++;
if(snow_id>total_snow) {
removeEventListener(Event.ENTER_FRAME,init);
}
}
function addBlur(s:MovieClip) {
var blurX:Number = Math.random()*2+3;
var blurY:Number = Math.random()*2+3;
var filter:BitmapFilter = new BlurFilter(blurX, blurY, BitmapFilterQuality.LOW);
var myFilters:Array = new Array();
myFilters.push(filter);
s.filters = myFilters;
}
function fall(e:Event) {
if (!e.target.hit) {
e.target.x+=e.target.xspeed;
e.target.y+=e.target.yspeed;
if (e.target.y>600) {
reset(MovieClip(e.target));
}
if(!e.target.shake) {
if (hit_target.hitTestPoint(e.target.x,e.target.y,true)) {
e.target.hit=true;
}
}
}else{
if(target_shake) {
e.target.hit=false
e.target.shake=true;
}
}
}
function shake_int(e:TimerEvent) {
hit_target.x=hit_target.mainX+Math.random()*5-2.5;
hit_target.y=hit_target.mainY+Math.random()*5-2.5;
}

target_shake=true;

//
hit_target.addEventListener(MouseEvent.CLICK,shake_start);
function shake_start(e:Event) {
target_shake=true;
//shake_timer.reset();
//shake_timer.start();
}
//
var snow_id:int = 0
addEventListener(Event.ENTER_FRAME,init);

Event Listener, Help
If ten mc's are going to have the same MOUSE_DOWN event, how can I, inside the mouseDown-function, know which mc it is? Like;

ActionScript Code:
for(var i=0;i<10;i++) {this["mc"+i].addEventListener(MouseEvent.MOUSE_DOWN, press);}function press(e:Event) { // lol? Could it be mc0 or mc2 or mc9? wtf...}

Keyboard Event Problem
Quote:




function mkey (event:KeyboardEvent)
{
}

function mkey (event:MouseEvent)
{
}

this.addEventListener(KeyboardEvent.KEY_DOWN, mkey);
mbutton.addEventListener(MouseEvent.CLICK, mbut);




I created a simple keyboard event that makes an object move. The problem I'm having is that when I try this out in the player the flash doesn't recieve any Keyboard events until I click an object that I made use a mouse event.

basically I have to click on the mbutton object for the keyboard events to be recognised.

Should I set a focus or what?

Trouble With Keyboard Event
Hello,

I'm trying to create a class (that controls a MovieClip), that is capable of listening for keyboard events on its own and then moving its x + y position.

I've highlighted the part of the code that must be causing the problem. I have placed a trace statement on one of the keys and it isn't working, so I'm guessing that its something to do with the event listener/ handler.


Code:
package fork
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import mcFork;

public class ForkClass extends MovieClip
{
var ySpeed:Number = 200;
var xSpeed:Number = 20;

public function ForkClass()
{
this.x = 225;
this.y = -150;
this.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);
}


private function KeyPressed(evt:KeyboardEvent) {
switch (evt.keyCode) {
case Keyboard.UP :
this.y -= ySpeed;
trace("working");
break;
case Keyboard.DOWN :
this.y += ySpeed;
break;
case Keyboard.LEFT :
this.x -= xSpeed;
break;
case Keyboard.RIGHT :
this.x += xSpeed;
break;
}
}
}
}

Keyboard Event Not Registering
I created a simple AS# project in flex2.

Code:
package {
import flash.display.Sprite;
import flash.events.KeyboardEvent;

public class Snake extends Sprite
{
public function Snake()
{
this.addEventListener(KeyboardEvent.KEY_DOWN,onKeyPress);
}
private function onKeyPress(event:KeyboardEvent):void{
trace("here");
}
}
}
but it does not trace out anything

thanks
cheers
firdosh

Keyboard-event Only On Textinput?
Im trying to add a global key-listener that will listen on any key pressed...no matter what object that is active.

on frame1:

Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);

function onKey(event:KeyboardEvent):void {
trace(event.keyCode);
if(event.keyCode == 90 && event.ctrlKey){
GUI.doSoemthing(null);
}
if(event.keyCode == 37){
GUI.doThis(null);
}
if(event.keyCode == 39){
GUI.doThat(null);
}
}
For some reason this only works when a inputfield has focus.
If I with the mouse selects a row in a DataGrid, the listener doesnt work anymore.

All graphics on stage is in a class called "GUI.as" and is added to the displaylist from same frame the eventlistener is on.

Any solution?

Keyboard Event ENTER
I've looked at several posts on this and it SEEMS as if my code should be working , but I'm getting "ArgumentError: Error #1063: Argument count mismatch on MethodInfo-7(). Expected 1, got 0." I just want to give an press enter option to clicking on the button (go_mc) . What am I doing wrong??? Thanks!

Here's the relevant code:


Code:
package{

import flash.display.Stage;
import flash.display.MovieClip;
import flash.ui.Keyboard;
import flash.events.*;
import flash.text.*;

public class Main extends MovieClip{


public function Main(){





stage.addEventListener(KeyboardEvent.KEY_DOWN, enterHandler);
go_mc.addEventListener(MouseEvent.CLICK, onClick);
go_mc.addEventListener(MouseEvent.MOUSE_OVER, onOver);
go_mc.addEventListener(MouseEvent.MOUSE_OUT, onOut);



function enterHandler(event :KeyboardEvent):void
{
if (event.keyCode == Keyboard.ENTER)
{
onClick();
}
}


function onClick(event:MouseEvent):void{
//blah blah blah
}

Delay With Keyboard Event
So I'm trying to convert this tile engine I wrote in AS 2.0 to AS 3.0... The problem is that when you hold down an arrow key to move, there is a delay. If I hold down right arrow, it moves one pixel to the right, pauses, then proceeds to move to the right at a continuous rate. The pause has to go! This did not happen in AS 2.0. If you pressed an arrow key and had code to move the x value of something, there was no pause. Here is some simple demonstration code:


ActionScript Code:
var land:Sprite = new Sprite();
land.name = "land";
addChild(land);
var landtile1:Shape = new Shape();
landtile1.name = "landtile1";
land.addChild(landtile1);

var mc=Shape(land.getChildByName("landtile1"));
mc.graphics.lineStyle(1, 0xFF0000, 1, false, "normal", "square", "miter", 3);
mc.graphics.drawRect(20,40,50,10);

stage.addEventListener(KeyboardEvent.KEY_DOWN, moveStuff);
function moveStuff(event:KeyboardEvent):void
{
    if(event.keyCode==39)
    {
        land.x++;
    }
}

just copy/paste that into a 3.0 FLA and hold the right arrow key to see the effect.

Is there any way to fix this?

Not Reacting To Keyboard Event..
Ive had some succes now, learning AS3.

But i cant figure out why this code is not letting my keydown function execute.

I do this in the FLASH ide, I use a document class as my main class. Which then creates a instance of a Player class, where it has a keyboard eventlistener, but when i press a key nothing happens.


Code:
package classes
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;

public class Player extends MovieClip
{
public function Player()
{
trace("Hero!");
addEventListener(KeyboardEvent.KEY_DOWN,checkKeysDown);
//this.setFocus();
}

private function checkKeysDown(event:KeyboardEvent):void
{
this.x++;
trace("kgkl");
trace("You pressed key: "+event.keyCode);
}

}


}

I have disabled the keyboard shortcuts in the flash player, but it is not reacting at all :.

I'd really appreciate it if someone can tell me what is going on here.

Keyboard Event Listeners
I'm definitely suffering with the lack of Keyis.Down! Anywhoo here is my code...


ActionScript Code:
public function Crung() {
    this.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
}
   
public function onKeyPressed(evt:KeyboardEvent):void {
    switch (evt.keyCode) {
        case Keyboard.RIGHT:
            this.x += 1;
            break;
        }
    }
}

This does nothing, and I'm thinking its because this isn't the document class and the event listener needs to be on the stage. 'public function Crung() {' is the constructor for the class Crung. An instance of Crung is created in Level1.as. And an instance of Level1 is created in Main.as which is the document class. So...

Main.as
...Level1.as
......Crung.as

Crung is basically a MovieClip which the user moves around the stage using the keyboard keys.

Any help in going about this? Not necessarily moving him around, just getting the listener to do anything in Crung.as

Keyboard Event Problem
It seems like the Keyboard.KEY_DOWN and Keyboard.KEY_UP events are fired continuously if youre keeping a key down. How can you make that the event KEY_DOWN is only fired the first time the key is pressed, and KEY_UP only one time when it's released?


ActionScript Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyDown);
stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyUp);

function KeyDown(e)
{
    trace("down"+e.keyCode);
}

function KeyUp(e)
{
    trace("up"+e.keyCode);
}

If I keep shift pressed for a while, and then release it, this is the result:


Code:
down16
up16
down16
up16
down16
up16
down16
up16
down16
up16
down16
up16
down16
up16
[...]
... you get the idea...

Keyboard Event Problems
I keep getting an error from the Keyboard.NUMBER_2. If I use NUMPAD_2 it works fine, but I don't want to use the numpad if I don't have to.
Also, the keyboard events do the same thing in every frame - how can I get them to do different things for different frames?


stage.addEventListener(KeyboardEvent.KEY_DOWN,repo rtKeyDown);
function reportKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.F4)
{
gotoAndStop(4);
}
if (event.keyCode == Keyboard.F5)
{
gotoAndStop(6);
}
if (event.keyCode == Keyboard.NUMBER_2)
{
gotoAndStop (7);
}
};

stop();

Generating Keyboard Event?
I need to make my application more accessible to keyboard only users.

This requires me to add an eventlistener for keyboard activity and filter the TAB key. I wish to issue a keyboard event for the ENTER key when the TAB key is pressed by the user. How can I generate the ENTER key please?

Dynamic Keyboard-event
hello!

i want to make some dynamic buttons which are able to use by pressing a letter and klick them. the problem is, that i try do test it by using trace() and so on but there is no feedback by the flesh when i pressed something. does anybody know what's wrong?

the event looks like that:

private function mausMarkiert(n)
{
n.currentTarget.alpha = 1;
// AENDERN --- hier noch die möglichkeit des tastendrückens und exemplare verschiebens einbauen
container_kalkulator_variante.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
}

private function mausUnmarkiert(n)
{
n.currentTarget.alpha = .8;
}

the alpha-manipulation works. do i have to write something more? container_kalkulator_variante is a sprite.

thanks for reading, understanding and re-writing!

Keyboard Event Problems
I keep getting an error from the Keyboard.NUMBER_2. If I use NUMPAD_2 it works fine, but I don't want to use the numpad if I don't have to.
Also, the keyboard events do the same thing in every frame - how can I get them to do different things for different frames?







Attach Code

stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
function reportKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.F4)
{
gotoAndStop(4);
}
if (event.keyCode == Keyboard.F5)
{
gotoAndStop(6);
}
if (event.keyCode == Keyboard.NUMBER_2)
{
gotoAndStop (7);
}
};

stop();

Keyboard Event Woes
Ok here's what I got going on. I have an object that inherits from Sprite, and it's just a simple png. In the main class I go ahead and add it, and then I call these 2 methods:


Code:

addEventListener(Event.ADDED,addedListener);
addEventListener(FocusEvent.FOCUS_IN,focusInListener);
/**
*
*/
private function focusInListener(e:FocusEvent):void {
if (e.target == player) {
player.focusRect = 0; //I don't want to see that lame *** focus rectangle
}
}


/**
*
*/
private function addedListener(e:Event):void {
if (e.target == player) {
stage.focus = player;
}
}
now when i load up my swf , the player object is still inside a focusRect, I also tried setting it to false. However as soon as use the keyboard to move the player object it moves out of the focusRect (which just stays in it's orginal location) So what's the deal with that thing, and how can I rid myself of it?

External COM Event Listener
ok heres the deal i want to know if this is possible.

using CE.NET for pocket pc.. which only supports flash player 6.. can you build a COM event listener that waits for an action from the server. then envokes an action within flash and also sends a result out of flash back to the server.

I have found a few examples of listeners within flash but they are dependent on actions within flash. I need to build a flash movie that sits static until a result is sent by the server.. not a user actively clicking on a button or anything.

can anyone point me to something like this that has been built? and what i need to study up on to make this work..

Thanks,
Kirk

Datagrid And Event-listener
Ive got a DataGrid, and Id like to get the value from one of the cells as soon as it has been changed (its editable).

Problem is, I only know how to get ahold of the row-index, and the column-index, but not the data inside the cell.

Anybody knows?

code:
myDataGridListener = new Object();
myDataGridListener.cellEdit = function(event){
var colIndex = event.columnIndex; // gets columnnr
var rowIndex = event.itemIndex; // gets rownr

var myCellsValue = event.?????? // How do I get the value inside this cell?
}
myDataGrid.addEventListener("cellEdit", myDataGridListener);

[F8] TextInput Event Listener
I’m in Flash 8 and working with the TextInput component.

My question is about setting up an event listener. I would like to fire off a few methods when the user clicks out of the TextInput with there mouse, or by tabbing out of the field.

Does anybody know of a good way to do this?
Is there a way to setup an unfocus event?
Thanks!


PHP Code:



var my_ti:mx.controls.TextInput;
var tiListener:Object = new Object();
tiListener.change = function(evt_obj:Object) {
trace("trigger methods”);
};
my_ti.addEventListener("??field_unfocus??", tiListener);

Event Listener Not Listening
I have a component that dispatches an event like this:
dispatchEvent( new Event( "fooChanged" ) );

In my Application
<mx:Application ... creationComplete="init()">
<mx:Script>
<![CDATA[
private function init() : void {
addEventListener( "fooChanged", handleChange );
}

public function handleChange (event:Event) : void {
....
}
]]>
</mx:Script>

The handleChange function never gets fired. Is there some big important piece I am missing?
Thanks

Event Listener Issues
Howdy,

I'm making a game with multiple characters. You move them by clicking on them, then clicking where you want them to move. Everything works great, except for when one character is traveling, and the user changes his or her mind and clicks somewhere else before the character reaches their destination. For some reason, my code will not remove the old event listener before assigning the new one.


heres the code:


stage.addEventListener(MouseEvent.CLICK, moveStarter);

function moveStarter(e:MouseEvent){
var xx = root.mouseX;
var yy = root.mouseY;

frank = personcontainer.getChildByName(whichCharacter);

///frank is the name of the variable i use tell the program which character is selected. the variable whichCharacter is defined elsewhere.


////in the code below, the hasEventListener command works, returning "true"
only when the character is moving. But the removeEventListener command does nothing.

if (frank.hasEventListener(Event.ENTER_FRAME)){
frank.removeEventListener(Event.EnterFrame, frankmover)
}else{
trace("not currently moving");
}

frank.addEventListener(Event.ENTER_FRAME, frankmover);

function frankmover(e:Event){
////there is code here that moves the character to the point xx, yy then removes the eventListener. It all works fine.

}

}



If anyone has any ideas, please let me know before i get too angry and dropkick my computer.

thanks so much!

-kenny

Copyright © 2005-08 www.BigResource.com, All rights reserved