Help a newbie with Keyboard events

Right so I'm just getting started with ActionScript (and Flash) and I'm getting a bit confused. I've got quite a bit of experience programming in other languages but I've never touched either actionscript or flash before.
I've got various books and have tried searching around the internet but I can't find anything to help me with this problem... it looks to me like it SHOULD work (but obviously I'm wrong because it doesn't!) I'm just trying to get the base for a game set up, and want to be able to take in user input via the keyboard (I will want mouse control as well, but let's focus on this problem first).
My code is:
package {
    import flash.display.MovieClip;
    import flash.events.*;
    import flash.ui.Keyboard;
    public class Main extends MovieClip
        var isRunning:Boolean = true;
        public function Main()
            trace("Flash Project!");
            Initialize();
            //Game Loop
            while(isRunning)
                Update();
            trace("Exiting...");
        public function Initialize():void
            trace("Initializing!");
            stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyPressed);
        public function Update():void
            trace("Updating...");
        public function OnKeyPressed(evt:KeyboardEvent):void
            switch (evt.keyCode)
                case Keyboard.ENTER:
                    trace("Enter!");
                    break;
                case Keyboard.ESCAPE:
                    isRunning = false;
                    break;
                case default:
                    trace("keyCode: ", event.keyCode);
                    break;
The errors it is generating refer to the OnKeyPressed function, and say that I have tried to access the undefined properties Keyboard, escape and default. I thought I imported all the keyboard stuff at the top? Help would be much appreciated here, I'll be fine once I'm up and running but at the moment I'm feeling somewhat lost.

Right, well at least part of my problem was that I had
trace("keyCode: " event.keyCode);
instead of
trace("keyCode: " evt.keyCode);
but it still doesn't like the word "default"? This is strange as it's coming up in blue so it's obviosly recognising it as a keyword...
If I comment out the 'default' section of te switch case statement it get's stuck in an infinite loop, even if I press escape... which should set 'isRunning' false therefore exiting the loop...
Help!

Similar Messages

  • Help with Keyboard Event

    Hi, I am designing a drum machine in flash pro Cs6 actionscript 3.0  and I am trying to add a keyboard event that will trigger a button event that I have all ready created, I can create the event to play the sound but this is not what I want, can I call the click event so the button will move on the key event triggering the sound, here is an example of one of my buttons code... btn, thank you if anyone can help.
    import flash.events.KeyboardEvent;
    playsound2.fla
    playsound with extra functionality:
    textbox added.
    Displays ID3 info of the sound
    btn.addEventListener(MouseEvent.CLICK, playSomeSound);
    function playSomeSound(e:MouseEvent)
              var req:URLRequest = new URLRequest("Savage.mp3");
              var s:Sound = new Sound(req);
              s.addEventListener(Event.COMPLETE, onSoundLoaded);
              s.addEventListener(Event.ID3, onID3Info);
    function onSoundLoaded(event:Event):void
              var localSound:Sound = event.target as Sound;
              localSound.play();
    function onID3Info(e:Event):void
              var id3Props:ID3Info = e.target.id3;
              var sOut:String = txt.text = "";
              for (var propName:String in id3Props)
                        sOut = propName + "=" + id3Props[propName] + "\n";
                        trace(sOut);
                        txt.appendText(sOut);
              txt.text = id3Props.comment;
    var ba:ByteArray = new ByteArray();
    var gr:Sprite = new Sprite();
    gr.x = 5;
    gr.y = 50;
    addChild(gr);
    var time:Timer = new Timer(50);
    time.addEventListener(TimerEvent.TIMER, timerHandler);
    time.start();
    function timerHandler(event:TimerEvent):void
              SoundMixer.computeSpectrum(ba, false);
              var i:int;
              gr.graphics.clear();
              gr.graphics.lineStyle(2, 0xFF0000);
              gr.graphics.beginFill(0x00ff00);
              gr.graphics.moveTo(10, 10);
              //  draw a circle.;
              var w:uint = 15;
              for (i=0; i<512; i+=w)
                        var t:Number = ba.readFloat();
                        var n:Number = (t * 200);
                        gr.graphics.drawCircle(i, 0, -n);

    Thanks, this was the code I added in the end and it works nicely, It covers my sound and id3 aswell as Im displaying lcd text in a dynamic text box.
    stage.addEventListener(KeyboardEvent.KEY_DOWN, btndownKey);
    function btndownKey(event:KeyboardEvent)
              if (event.keyCode == 83)
                        var url:String = "Savage.mp3";
                        var request:URLRequest = new URLRequest(url);
                        var s:Sound = new Sound();
                        s.addEventListener(Event.COMPLETE, completeHandler);
                        s.addEventListener(Event.ID3, onID3Info);
                        s.load(request);

  • How can I get around Javascipt issue with keyboard events?

    Javascript issue: keydown, keypress, keyup events cause quick search to initiate with the division key on the keypad and slash key on the keyboard. I am trying to program a graphic representation of a 10 key pad and the division (/) sign is problematic for roll over and processing based on key events. How can I get around this? further notes: Safari also has problems with key events and the division key(s) but no search function connected. Thankyou for time and attention

    A good place to ask questions and advice about web development is at the mozillaZine Web Development/Standards Evangelism forum.<br />
    The helpers at that forum are more knowledgeable about web development issues.<br />
    You need to register at the mozillaZine forum site in order to post at that forum.<br />
    See http://forums.mozillazine.org/viewforum.php?f=25

  • Help a newbie with her timeline

    (Something to keep in mind: I learned Flash 7 a few years ago
    (quite in depth, actually) but forgot it all. Just recently, I have
    picked up a tutorial book and have kind-of gotten back into it. I
    know the basics, but be gentle in your advice.)
    I need help! I have created an interactive flash animation on
    our company's landing page that shows you how the product exercises
    the muscles. I am having trouble with my timeline, I beleive.
    Check it out here, bottom of right column:
    Flash
    Animation In Need of Help
    Ideally, what I want to happen is the individual movie clips
    will spin and then stop. Once you click on them, it will show you a
    close up of a figure and highlight what muscles that exercise uses.
    Then, once you click on the next exercise, the one you were on will
    go back to a static (non-spinning) image of the exercise and will
    stay that way, no matter whether you skip around or go from first
    to last exercise (this only makes sense if you look at the above
    link).
    Right now I have one flash file that contains 4 movie
    clips/buttons (each of the exercises).They are in their seperate
    layers in the first frame. In each layer, there is the first movie
    clip (spinning) in frame 1; in the next frame I have the movie clip
    that highlights the muscle groups which plays once you click on the
    first movie clip. Directly after this, in the next frame, I have a
    button/jpg of the original exercise that does not spin, but when
    clicked will take you to the highlighted movie clip. The frames are
    stacked, so that each of the highlighting clips are one frame
    further down the line than the layer on top of it, so they don't
    play at the same time.
    Therein lies my problem. For example, if you click on the
    last exercise, then click on the second exercise, the exercises
    beneath it spin because on the second layer, the highlighting movie
    clip is on the same frame as these movie clips' spinning image (if
    that doesn't make sense, let me know and I'll show you an image of
    my timeline).
    What I need help on is how to keep this from happening.
    Again, this all might not make much sense, but please ask me if you
    need further clarification.
    ANY ideas?

    I think you've answered your own question José!
    The page is deeper than your monitor screen size (it doesn't move on my monitor set at 1350deep) and is producing a scroll bar at the right which bumps the page in to accommodate the bar size.
    Garry

  • Please help a newbie with simple equal methode

    With my little know how of java I have written this methode
    to test the equality of two LinkedSet data structures.
    provided that the linkedSet class and the iterator are
    implemented correctly , can some one help me please to
    figure out what is wrong or give an alternate solution.
    Thanks in advance
    * Return true if this set and the parameter contain
    * exactly the same elements
    public boolean equals(SetADT setADT) throws IllegalStateException
    boolean result=false;
    if(this.size()!=setADT.size())
    throw new IllegalStateException(" Two sets are not equal");
    Iterator a=this.iterator();
    Iterator b=setADT.iterator();
    LinkedSet temp1=new LinkedSet();
    LinkedSet temp2=new LinkedSet();
    while(a.hasNext())
    temp1.add(a.next());
    temp2.add(b.next());
    Iterator c=temp1.iterator();
    Iterator d=temp2.iterator();
    if(c.next().equals(d.next()))
    temp1.remove(c.next());
    temp2.remove(d.next());
    result=(temp1.isEmpty()&&temp2.isEmpty());
    return result;

    while(a.hasNext())
      temp1.add(a.next());
      temp2.add(b.next());
      Iterator c=temp1.iterator();
      Iterator d=temp2.iterator();
      if(c.next().equals(d.next())) // <- Watch missing braces !
         temp1.remove(c.next());
      temp2.remove(d.next());
      result=(temp1.isEmpty()&&temp2.isEmpty());
    }Whay are you doing all that extra iteration stuff?
    I mean, I see what you are getting at ...towards the empty final objects. But isn't that a really exhaustive way the get to the end of this problem? The end doesn't justify the means.
    Start assuming result = true
    In your while loop...
    Just test 'if (!(a.next().equals(b.next())) {'
    If it ever does, something didn't match.
    So set result = false and 'break' from the loop.
    At the end of the method, result will be either true or false accordingly.
    Code that up and it should work better. But ...can we assume the iterators traverse the set in the same order always? That is the question I would ask here.

  • Can anyone help a newbie with "An unknown error (-609)" message?

    I just bought my first iPod a week ago and so far, I haven't had any problems with iTunes. But today, I can't get any artwork for CD's I'm importing because of "An unknown error (-609)." I checked, and my iTunes is up to date. Is there anything I can do about this or is this the kind of problem that will come and go on its own?

    No. I bought it online. Still can't restore. Pls help me. Thanks!

  • Help a newb with setting up Mail.app

    Im trying to set up my Mail app with my email account hosted with my shared hosting service.
    Ive used mail.app before...but i seem to be running into some issues.
    Ive used mail.app with .mac and mobileme email addresses and they functioned properly,my issue is that using the [email protected] doesnt seem to work so smoothly.
    For example when i send a message in Mail.app it stores it only in the Mail folder in Mail but in a new folder in webmail called Sent Messages.
    I use IMAP for Mail.app and with my iPod Touch (which uses the same EMAIL Address).
    When i send messages using the ipod touch i dont get the excess mailboxes and the sent messages/deleted messages etc get routed to the properly mailbox in the ipod touch and Webmail.
    These are the extra mailboxes i get when using Mail.app
    They show up in both Mail.app and my Webmail.
    SOO my question is; How do i properly set it up so i only have these mailboxes:
    INBOX
    SENT
    DRAFTS
    TRASH
    and that they all tie to gether?
    for example; send a message in Mail.app it goes into the Sent folder on both Mail.app and Webmail instead of a bogus Sent Mail folder automatically created.
    Any advice please????

    From Apple's web page on Exchange with Snow Leopard:
    Infrastructure requirements
    • Update Rollup 4 for Exchange Server 2007 Service Pack 1.
    • Exchange Web Services (EWS) must be enabled. EWS is on by default in Exchange 2007.
    • Exchange AutoDiscover must be turned on for automatic setup.
    • Snow Leopard uses SSL over port 443 to connect to EWS.

  • Please help a newbie with a video render problem!

    Im new to After Effects so please forgive if this is a silly question.
    I have a Edge Animation with a background color of #ffa800
    I have imported a video into After Affects which has a transparent background.
    Research tells me that video is never really transparent so I am creating a solid layer in AE, placing video above it and setting the blend mode to "screen"
    I now have a video with a background color of #ffa800.
    However, when I export / render the video out and import into my Edge Animate project the background color of the video is off and does not match my Edge Animate background.
    I have spent all day experimenting with different export options rendering direct from AE and also via Media encoder. Im now completely stumped.
    I have also tried setting the video background to color #ffa800 and then masking my video. This saves me from having to use a blend mode of "screen" but I get the exact same results.
    Could anybody please give me some tips on where I am going wrong please. The back ground is so close but either slightly darker or lighter depending on what I have set which spoils the overall animation effect I am attempting to create.
    Thanks,
    Paul

    Without exact system information, render settings and so on nobody can tell you much. That aside, there are some fundamental failures in your plan. First, web colors mean nothing in AE or in most graphics programs for that matter due to the little subject of color management and possible quantization errors. Whatever colors you dial in, do so using the normal RGB sliders. Second, blending modes do not create transparency, even if for mathematical reasons the blending formula used may appear to eradicate certain colors. Third, you need to consider Gamma values. Video is not blending linear and both your computer screen as well as the video content itself may have a built-in Gamma. As a result, your blending operation could already produce wrong results like a slight haze, the encoding of the video file could introduce Gamma skew and then finally in the last step, whatever tool you use to display may apply dynamic corrections as well or in reverse, none at all. So it basically comes down to checking those things and properly calibrating/ adjusting your monitor and your system color settings and make use of color management in AE, if relevant. In the end, though, you will always see minor color deviations. It's inherent in how compressed formats like H.264 work. You can only try to minimize them as much as you can.
    Mylenium

  • Help this newbie with a 1067 error code on a SIMPLE ActionScript please

    Hi, I am new to this. I am creating a presention in flash and I want to link to the narration mp3 files as oppsed to embedding them as they will change in the future..
    I have two different books with 2 different  pieces of script to use though the overall process is the pretty much same. For both I get the exact same error.
    See below:
    1120: Access of undefined property nar1.

    Thanks Ned.
    It's the posting. I had a nice little post written up for my initial request but when I posted-it truncated and I had to retype everything (it's the kind of morning I am having ) I will fix my typing.
    I suppose I could add the mp3 files to the library and update that way but I was hoping to set the files up so that files could be overwritten as the slides were changed or swapped out without the extra steps.

  • Help a newbie with Apps!

    Brand new at iPad and Mac. I tried to enter the apps page on the iPad, didn't have the right password, and now it is frozen, saying that required fields have been left blank...nothing on the page will move, and it is utterly frozen. Meanwhile, I got the Apple ID password, but how do I unfreeze the Apps page?

    Try a reset:
    Hold the home and power buttons at the same time until the Apple boot logo appears. No data will be lost.

  • AutoSuggest Widget and Custom Keyboard Events

    Hi,
    I'm using the 1.6 and AutoSuggest widget for a search form.
    I've managed to customise it slightly that when a user selects one
    of the suggestions with the mouse a hidden form field is populated
    with an ID (so that we don't actually have to search for the
    selected terms, we can just reference the hidden field value, if
    it's defined).
    I've used a very simple onclick= on the suggstion div (the
    autosuggest itself is almost identical to the examples) that sets
    the value of the hidden field to the ID when it's clicked. And
    works fine. Although I can't seem to get it to work with keyboard
    events. I've tried onkeydown=/onkeypress=/etc but not joy. The
    Autosuggest widget keyboard navigation works, (up, down and enter
    to select the suggestion) but does it overide any other attempts
    for keyboard events? Or am I doing something wrong?
    All the code is the same as the example apart from the actual
    suggestion div. Here it is:
    <div class="list" style="font-size:10px;"
    onkeydown="setHiddenValue('{hiddenid}')"
    onclick="setHiddenValue('{hiddenid}')">{name}</div>
    And the setHiddenValue function (which works fine onclick):
    function setHiddenValue(hidID) {
    document.getElementById("intHiddenID").value = hidID;
    Thanks in advance for any help
    Al

    Just an update - and not the best solution. I've gone in and
    edited the spryAutoSuggest.js to fit our needs exactly. It was a
    just case of editing the key press events for the enter key (13 -
    it's commented //enter key), which now gets the hidden field by ID
    and set the value required to it.
    Surprised there was no other suggestions... maybe something
    to be resolved in 1.7?
    Al

  • Help with possible mouseEvent/Keyboard Event problem

    Hi guys, I am having trouble with a game I am creating right now.  The problem seems to lie on mouse / Keyboard event.
    Basically, I have a character that the player can control using the  keyboard arrow keys and it works perfectly fine on its own.  Whenever the game starts,  the player can control the character instantly with the keyboard. Here's the problem now, after I added another page (at frame 1) and created a start game button, those keyboard events  won't start immediately anymore.  The player must click on the stage  again before it works.  Is there any method to solve this?
    Right now, here is my Start button page.
    var start_btn:Start_btn = new Start_btn;
    start_btn.addEventListener (MouseEvent.CLICK, goGame);
    function goGame(event:MouseEvent) {
    gotoAndStop("game"); //The game's frame
    this.removeEventListener(MouseEvent.CLICK,goGame);
    Here's some code for the actual game part.
    stage.addEventListener(KeyboardEvent.KEY_DOWN,keyP  ressed);
    function keyPressed (e:KeyboardEvent) :void {
    //character movement code...like charcter.x++, x-- etc
    Thanks in advance

    How about trying:
         stage.focus = stage;
    in goGame().

  • Getting keyboard events with Group

    Hi all,
    I'm new to JavaFX and I'm trying to handle keyboard events in a group but it doesn't seem to respond when I press the keyboard.
    As I understand this is because Group doesn't receive the focus. If that is the case, how can I make it receive focus? I tried calling setFocusTraversable(true) and setFocused(true) but both haven't helped.
    If it's not the focus, what is it?
    Thanks!

    Use requestFocus() instead of  setFocused(true).
    Keyboards events work as expected  with a group.
    @Override
        public void start(Stage primaryStage) {
            Button btn = new Button();
            btn.setText("Say 'Hello World'");
            Group root = new Group();
            root.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
                public void handle(KeyEvent event) {
                    System.out.println(event.getCode());
                    event.consume();
            root.getChildren().add(btn);
            Scene scene = new Scene(root, 300, 250);
            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
            root.requestFocus();

  • I have accepted iCal invitations with repeating events and they have since been deleted from the iCal on my Mac but won't delete from my iPhone. Help

    I have accepted iCal invitations with repeating events and they have since been deleted from the iCal on my Mac but won't delete from my iPhone. Help

    I experienced this issue as well.
    Background:
    I had opened an ICS attachment for a repeating event on my iPhone, which added the item to my phone's calendar. I did not have the option to delete the calendar entry from my phone, and the item did not appear on the calendar on my Mac. My phone is currently running iOS 7 (but the problem began quite awhile ago; I don't recall which version of iOS was installed when it started).
    Solution (summary):
    Create a new calendar, move the items that you wish to delete to the new calendar, then delete the new calendar
    Solution (detailed steps):
    Create a new calendar
    On your phone, open the calendar app
    Tap the "Calendars" option at the bottom of the screen
    Tap the "Edit" button in the top left corner
    Scroll to the bottom of the list and tap the "Add Calendar..." option
    Give your new calendar a good name, such as "Delete me"
    Tap "Done" in the top right corner to save the new calendar
    Tap "Done" in the top left corner to finish editing the list of calendars
    Tap "Done" to exit the list of calendars
    Assign all calendar entries that you wish to delete to the calendar you created in step 1
    Tap a calendar entry that you wish to delete
    Tap the "Edit" button in the top right corner
    Scroll down until you see the Calendar field (on an iPhone or iPod it's usually just below the bottom of the screen), then tap the Calendar field to bring up the list of available calendars
    Tap the name of the calendar that you created in step 1 (e.g. "Delete me"); the screen should return to the main calendar entry page
    Tap "Done" in the top right corner of the screen. You may need to then tap the "< Day" button on the top left of the screen to return to the main calendar view
    Repeat the instructions in step 2 for each of the calendar entries that you wish to delete
    Delete the calendar that you created in step 2 (this will delete all calendar entries assigned to this calendar)
    From the main screen in the calendar app, tap the "Calendars" option at the bottom of the screen
    Tap the "Edit" button in the top left corner
    Tap the entry for the calendar that you created in step 2 (e.g. "Delete me")
    Scroll to the bottom of the scren and tap the "Delete Calendar" option. You should be prompted with a warning that explains that "All events associated with this calendar will also be deleted."
    If you're sure that the only items on this calendar are items that you wish to delete, tap the "Delete Calendar" button
    Tap "Done" in the top right corner to exit the Edit Calendars screen
    Tap "Done" to exit the list of calendars. You should now be back at the main view of the calendars app
    Rejoice, your pesky repeating calendar events have been deleted
    At this point all of the items that you assigned to the deleted calendar should be gone
    Repeat the steps above for any entries that you missed
    Post another message to this thread if this did not resolve your problem
    minor edit for clarity made by ScottHooley

  • Newbie Help - 5th gen with no stuff!

    Hello all - I recently got a 5th gen iPod from a friend that owed me $$ and all i got was the unit (black/silver - 30GB). Besides a charger, headphones, etc - what do I need to join the revolution? I am totally new to this but feel that this iPod is the bees knees. Any help with software, connections, videos, etc? Any direction would be greatly appreciated. Thanks for helping a newbie out!
    New?   Windows XP   DuLL desktop

    Well the main thing you need, besides headphones, is a dock cable to plug the iPod into your computer. You can then put stuff on the iPod with that cable and the cable also charges the iPod from the USB port.
    One nice product out there is Griffin's Powerblock which can be seen here...
    http://www.griffintechnology.com/products/powerblock/
    $30 and can be bought at places like Best Buy. The nice thing about this is that not only is it a charger that plugs into the wall and gives you a standard USB port to charge your iPod and any other USB chargable devices without needing a computer (great for traveling), Griffin was even kind enough to include an iPod USB Dock cable that you need anyway.
    In the meantime, if you haven't already, download and install iTunes on your computer and start importing your CD library into it.
    Patrick

Maybe you are looking for