How to add a keyboard navigation to a Flash AS3 based app? - actionscript-3

I would like to make my Flash AS3 based app more accessible with a keyboard navigation.
What's the best way to add to every MovieClip with a MouseEvent.CLICK the ability to get selected through the TAB and clicked/fired through ENTER?
Some basic example of my code:
nav.btna.addEventListener(MouseEvent.CLICK, openSection);
dialog.btnx.addEventListener(MouseEvent.CLICK, closeDialog);
function openSection(event:Event=null):void
{
trace("nav.btna")
}
function closeDialog(event:Event=null):void
{
trace("dialog.btnx")
}
I remember that there was a AS3 function that enabled that every MovieClip with a MouseEvent could be fire through ENTER if the MovieClip was selected with TAB. I can't remeber the function though.

I think the problem may be that you are attempting this with a MovieClip instead of a button (Button or SimpleButton).
I made a simple test by creating buttons instead of MovieClips in my library and this worked as expected:
// I have 4 buttons (button1, button2, etc) on the stage
for(var i:int = 1; i <= 4; i++)
{
var mc = getChildByName("button" + (i+1));
mc.tabIndex = i;
mc.addEventListener(MouseEvent.CLICK, onClicked);
}
function onClicked(e:MouseEvent):void
{
trace(e.currentTarget + " clicked");
}
stage.focus = stage;
I initially ran this test with MovieClip instances, and while they would show that the tab was working (a yellow border shows up), the MouseEvent.CLICK was never firing. Once I switched to actual buttons (SimpleButton in this case), it worked with both the Enter and Space keys.
EDIT:
To answer the question posed in the comments, this is a quick-and-dirty way to "convert" MovieClips to SimpleButtons at runtime:
// I have 4 MovieClips (button1, button2, etc) on the stage
for(var i:int = 1; i <= 4; i++)
{
var mc:MovieClip = getChildByName("button" + i) as MovieClip;
var button:SimpleButton = convertMovieClipToButton(mc);
button.tabIndex = i;
button.addEventListener(MouseEvent.CLICK, onClicked);
}
function convertMovieClipToButton(mc:MovieClip):SimpleButton
{
var className:Class = getDefinitionByName(getQualifiedClassName(mc)) as Class;
var button:SimpleButton = new SimpleButton(new className(), new className(), new className(), new className());
button.name = mc.name;
button.x = mc.x;
button.y = mc.y;
mc.parent.addChildAt(button, getChildIndex(mc));
mc.parent.removeChild(mc);
return button;
}

Related

AS3 Editing event.target after being clicked befor executing gotoAndPlay("abc");

Greetings stackoverflow members,
i have 3 animated movieclips nested in a movieclip. What I'm trying to do is to get the name of the instance clicked and edit it befor applying gotoAndPlay. I can get the name but when ever I try to edit it I'm getting the Error:
Symbol 'Buttons MC', Layer 'Actions', Frame 1, Line 30 1061: Call to a possibly undefined method gotoAndPlay through a reference with static type String.
Here's my code so far:
[Bindable] var targetName:String;
var _userInput:String = new String();
_userInput = targetName;
//array for buttons
var btnArray:Array = [INS_Btn1, INS_Btn2, INS_Btn3];
//add eventlistiners
for(var i:uint=0; i<btnArray.length; i++) {
btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
btnArray[i].addEventListener(MouseEvent.CLICK, bClick);
btnArray[i].buttonMode=true;
}
//btn over state
function bRollover(event:MouseEvent):void{
event.target.gotoAndPlay("Over");
}
//btn out state
function bOut(event:MouseEvent):void{
event.target.gotoAndPlay("Out");
}
//btn click state
function bClick(event:MouseEvent):void{
targetName = event.target +("_ani")
targetName.gotoAndPlay("Active");
}
What I want is that the MC clicked should go and play the animation of an onther MC. Best I should mention that I'm a beginner in AS3.
targetName is a String and of course you can't gotoAndPlay on a string :) Besides of that, event.target will return the object that you've clicked and not its name. And the targetName does not need to be bindable if you don't do anything special with it besides of this code.
So I assume you want a movieclip with the instance name INS_Btn1_ani to be played when you click on the INS_Btn1 button? First, make sure your buttons have the name property set (to make it easier, set the name as "INS_Btn1", "INS_Btn2" etc as well.
INS_Btn1.name = "INS_Btn1";
Then you would do it like that:
function bClick(event:MouseEvent):void
{
targetName = event.target.name + "_ani"; // this will become INS_Btn1 + _ani = INS_Btn1_ani
// Now you need to let the movieclip with the name "INS_Btn1_ani" play
this[targetName].gotoAndPlay("Active");
}
So after understanding the answer from Philarmon I've solved the problem. In case someone has the same/similar problem here's what I've done to get it working:
var targetName:String;
var _userInput:String = new String();
_userInput = targetName;
//array for buttons MCs
var btnArray:Array = [INS_btn1, INS_btn2];
var aniArray:Array = [INS_btn1_ani, INS_btn2_ani];
//add eventlistiners
for(var i:uint=0; i<btnArray.length; i++) {
btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
btnArray[i].addEventListener(MouseEvent.CLICK, bClick);
btnArray[i].buttonMode=true;
}
//btn over state
function bRollover(event:MouseEvent):void{
targetName = event.currentTarget.name + "_ani";
this[targetName].gotoAndPlay("Over");
}
//btn out state
function bOut(event:MouseEvent):void{
targetName = event.currentTarget.name + "_ani";
this[targetName].gotoAndPlay("Out");
}
//on clicked
function bClick(event:MouseEvent):void{
//add listeners for unclicked
for (var i:uint=0;i<btnArray.length; i++){
btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
//stopping animation
aniArray[i].gotoAndStop("Out");
}
//remove Eventlistener when clicked
event.target.removeEventListener(MouseEvent.ROLL_OUT, bOut);
event.target.removeEventListener(MouseEvent.ROLL_OVER, bRollover);
targetName = event.currentTarget.name + "_ani";
this[targetName].gotoAndStop("Active");
}
As you can see I've added a "sticky" function to keep the mc on click state.

How to apply drag and drop function to all frames in movie clip? Actionscript3

Each frame contain 1 text field. I apply the code on timeline.
But it only gets applied to the last object, which means that I can only drag and drop the last object. Why?
How can I improve this so that I can drag and drop all objects?
for(var j:uint=0; j<3; j++)
{
var q:Ans = new Ans();
q.stop();
q.x = j * 300+50;// set position
q.y = 500;
var r:uint = Math.floor(Math.random() * q_list.length);
q.qface = q_list[r];// assign face to card
q_list.splice(r,1);// remove face from list;
q.gotoAndStop(q.qface+1);
q.addEventListener(MouseEvent.MOUSE_DOWN, startAnsDrag);
q.addEventListener(MouseEvent.MOUSE_UP, stopAnsDrag);
q.addEventListener(Event.ENTER_FRAME, dragAns);
addChild(q);// show the card
}
//----------------------------drag
// offset between sprite location and click
var clickOffset:Point = null;
// user clicked
function startAnsDrag(event:MouseEvent) :void
{
clickOffset = new Point(event.localX, event.localY);
}
// user released
function stopAnsDrag(event:MouseEvent) :void
{
clickOffset = null;
}
// run every frame
function dragAns(event:Event) :void
{
if (clickOffset != null)
{ // must be dragging
q.x = clickOffset.x+mouseX+135;
q.y = clickOffset.y+mouseY;
}
}
Make a new layer in the timeline just for your drag-and-drop code, which you can remove from your other actionscript. Put the code on the first frame in that layer. Now click on and select the last frame on that layer in which you want the code to be effective (probably the last frame of the MovieClip). Press F5 to draw-out the range of frames which will be affected by the code. Voila!

Creating a vector array of movie clips AS3

I have several movie clips on the stage of my main .fla named btn1-btn7 which will act as buttons. I have a class file named Functions.as where an event listener is created when a button is clicked. onButtonClicked is just going to a frame on the timeline.
obj.addEventListener(MouseEvent.CLICK, onButtonClicked);
I would like the ability to set the buttonMode, visibility, etc. of all of the buttons simultaneously. I have been looking into this for a few hours and am not able to find any solutions. I am now looking into adding them to a vector (which is a new concept for me), but I am not sure how to go about executing this properly. This is what I have so far.
public var buttons:Vector.<MovieClip > = new Vector.<MovieClip > ();
function addButtons()
{
buttons.push(btn1,btn2,btn3,btn4,btn5,btn6,btn7);
for (var i:int; i<buttons.length; i++)
{
trace(buttons[i].name);
}
}
How would I go about, for example, adding the event listener to all of the objects? I will also be setting the buttonMode to true, and making them all invisible simultaneously. I don't even know if it's possible to accomplish this. Thank you in advance for any suggestions.
I'm going to asume that you use timeline code, and have instances of the buttons already placed on the stage. So, first, create the vector:
var _btns:Vector.<MovieClip> = new Vector.<MovieClip>;
_btns.push(btn1,btn2,btn43....) //add all the buttons
Than, you can init the properties of all the buttons:
var _mc:MovieClip;//helper var
for(var i:int=0,i<_btns.length;i++)
{
_mc = _btns[i];
_mc.visible = false;
_mc.buttonMode = true;
_mc.addEventListener(MouseEvent.CLICK, onClick);
}
Then, the event handler:
function onClick(e:MouseEvent):void
{
for(var i:int=0,i<_btns.length;i++)//reset all the buttons
{
_btns[i].visible = false;
}
_mc = MovieClip(e.eventTarget);
_mc.visible = true; //make visible the clicked one
}
You just need to do what you are doing with the .name property in your example code. You need to loop thru every single button in your array (or vector, if you prefer). Here is an example how to set the property of buttonMode:
function setButtonMode(b:Boolean):void {
for(var i:int=0; i<buttons.length; i++) {
var btn:MovieClip = buttons[i]; //store the current reference in a var for faster access
btn.buttonMode = b;
btn.mouseChildren = !b;
}
}

Multiple movieclips all go to the same spot; What am i doing wrong?

So I'm trying to shoot multiple bullets out of my body and it all works except I have an odd problem of just one bullet showing up and updating to set position for the new ones.
I have a move able player thats supposed to shoot and I test this code by moving the player and shooting. Im taking it step by step in creating this.
The result of tracing the bulletContainer counts correctly in that its telling me that movieclips ARE being added to the stage; I Just know it comes down to some kind of logic that im forgetting.
Here's My Code (The Bullet it self is a class)
UPDATE*
Everything in this code works fine except for I stated earlier some code seems reduntned because I've resorted to a different approaches.
BulletGod Class:
public class bulletGod extends MovieClip{
//Register Variables
//~Global
var globalPath = "http://127.0.0.1/fleshvirusv3/serverside/"
//~MovieCLips
var newBullet:bulletClass = new bulletClass();
//~Boolean
var loadingBulletInProgress:Number = 0;
var shootingWeapon:Number = 0;
//~Timers
var fireBulletsInterval = setInterval(fireBullets, 1);
var bulletFireEvent;
//~Arrays
var bulletArray:Array = new Array();
var bulletType:Array = new Array();
var bulletContainer:Array = new Array();
//~Networking
var netBulletRequest:URLRequest = new URLRequest(globalPath+"bullets.php");
var netBulletVariables:URLVariables = new URLVariables();
var netBulletLoader:URLLoader = new URLLoader();
//~Bullet Image Loader
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest();
public function bulletGod() {
//Load every bullet for every gun
//Compile data to be requested
netBulletVariables.act = "loadBullets"
netBulletRequest.method = URLRequestMethod.POST
netBulletRequest.data = netBulletVariables;
netBulletLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
netBulletLoader.addEventListener(Event.COMPLETE, getBulletImages);
netBulletLoader.load(netBulletRequest);
}
private function getBulletImages(bulletImageData:Event){
//Request every bullet URL image
//Set vars
var bulletData = bulletImageData.target.data;
//Load images
for(var i:Number = 0; i < bulletData.numBullets; i++){
bulletArray.push(bulletData["id"+i.toString()]);
bulletType.push(bulletData["bullet"+i.toString()]);
//trace(bulletData["id"+i]+"-"+bulletData["bullet"+i]);
}
//All the arrays have been set start firing the image loader/replacer
var imageLoaderInterval = setInterval(imageReplacer, 10);
}
private function imageReplacer(){
//Check to see which image needs replacing
if(!loadingBulletInProgress){
//Begin loading the next image
//Search for the next "String" in the bulletType:Array, and replace it with an image
for(var i:Number = 0; i < bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//Load this image
mRequest = new URLRequest(globalPath+"ammo/"+bulletType[i]);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImage);
mLoader.load(mRequest);
//Stop imageReplacer() while we load image
loadingBulletInProgress = 1;
//Stop this for() loop while we load image
i = 999;
}
}
}
}
private function loadImage(BlackHole:Event){
//Image has loaded; find which array slot it needs to go into
for(var i:Number = 0; i <= bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//We found which array type it belongs to; now replace the text/url location with the actual image data
var tmpNewBullet:MovieClip = new MovieClip;
tmpNewBullet.addChild(mLoader);
//Add image to array
bulletType[i] = tmpNewBullet;
//Restart loadingBullets if there are more left
loadingBulletInProgress = 0;
//Stop for() loop
i = 999;
}
}
}
//###############################################################################################################################################
private function fireBullets(){
//If player is holding down mouse; Fire weapon at rate of fire.
if(shootingWeapon >= 1){
if(bulletFireEvent == null){
//Start shooting bullets
bulletFireEvent = setInterval(allowShooting, 500);
}
}
if(shootingWeapon == 0){
//The user is not shooting so stop all bullets from firing
if(bulletFireEvent != null){
//Strop firing bullets
clearInterval(bulletFireEvent);
bulletFireEvent = null
}
}
}
private function allowShooting(){
//This function actually adds the bullets on screen
//Search for correct bullet/ammo image to attach
var bulletId:Number = 0;
for(var i:Number = 0; i < bulletArray.length; i++){
if(bulletArray[i] == shootingWeapon){
//Bullet found
bulletId = i;
//End For() loop
i = 999;
}
}
//Create new bullet
//Create Tmp Bullet
var tmpBulletId:MovieClip = new MovieClip
tmpBulletId.addChild(newBullet);
tmpBulletId.addChild(bulletType[bulletId]);
//Add To Stage
addChild(tmpBulletId)
bulletContainer.push(tmpBulletId); //Add to array of bullets
//Orientate this bullet from players body
var bulletTmpId:Number = bulletContainer.length
bulletTmpId--;
bulletContainer[bulletTmpId].x = Object(root).localSurvivor.x
bulletContainer[bulletTmpId].y = Object(root).localSurvivor.y
//addChild(bulletContainer[bulletTmpId]);
}
//_______________EXTERNAL EVENTS_______________________
public function fireBullet(weaponId:Number){
shootingWeapon = weaponId;
}
public function stopFireBullets(){
shootingWeapon = 0;
}
}
}
BulletClass:
package com{
import flash.display.*
import flash.utils.*
import flash.net.*
import flash.events.*
public class bulletClass extends MovieClip {
public var damage:Number = 0;
public function bulletClass() {
//SOME MOVEMENT CODE HERE
}
public function addAvatar(Obj:MovieClip){
this.addChild(Obj);
}
}
}
Well ... if I may say so, this code looks quite wrong. Either something is missing from the code or this code will never make the bullets fly.
First off, you can set x and y of the new bullet directly (replace everything after "orientate this bullet from players body" with this):
tmpBulletId.x = Object(root).localSurvivor.x;
tmpBulletId.y = Object(root).localSurvivor.y;
Perhaps this already helps, but your code there should already do the same.
But to let these bullets fly into any direction, you also need to add an event listener, like so:
tmpBulletId.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e:Event) {
var movedBullet:MovieClip = MovieClip(e.currentTarget);
if (movedBullet.x < 0 || movedBullet.x > movedBullet.stage.width ||
movedBullet.y < 0 || movedBullet.y > movedBullet.stage.height) {
// remove move listener, because the bullet moved out of stage
movedBullet.removeEventListener(Event.ENTER_FRAME);
}
// remove the comment (the //) from the line that you need
MovieClip(e.currentTarget).x += 1; // move right
// MovieClip(e.currentTarget).y -= 1; // move up
// MovieClip(e.currentTarget).x -= 1; // move left
// MovieClip(e.currentTarget).y += 1; // move down
}
This example lets your bullet fly to the right. If you need it flying into another direction, just comment out the line with the "move right" comment and uncomment one of the other lines.
This is of course a very simple example, but it should get you started.
I hope this helps, and that my answer is not the wrong answer to the question.
As far as I have expirienced it you can have only one copy of MovieClip object added to specific child. Best approach is to use ByteArray for the clip source and instantiate new MovieClip and pass the ByteArray as a source. It have something to do with child/parent relation since a DisplayObject can have only one parent (and a way to detach the object from scene too).
Well i ended up writeing the whole code from scratch for a 3rd time and ran into a similar problem and just for reference to anybody else that comes to a problem thats random as this one i found that problem was likly does to a conversion error somewhere that doesn't necessarily break any compiling rules. Just that i was calling a movieclip and not the class it self.

AS3, for loop create button inside movieclip and how to call it?

Here is my full code
import fl.controls.*;
var test:MovieClip = new MovieClip();
var btn:Button;
for(var i:int = 1; i<=7; i++){
btn = new Button();
btn.name = "btn" + i;
btn.x = i * 100;
test.addChild(btn);
btn.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent) { nothing(i); });
}
addChild(test);
function nothing(bla:int):void {
trace("You clicked " + bla);
}
Result:
You clicked 8
You clicked 8
You clicked 8...
Is there anyway, such that, I can use for loop to create different name button, and add it to an event listener?
Your problem is the function(evt:MouseEvent){} closure (JavaScript info applies to ActionScript too, as they're both ECMAScript). Here's what you can do:
function makeClickListener(i:int) {
return function(evt:MouseEvent) {
nothing(i);
};
}
...
for(...) {
...
btn.addEventListener(MouseEvent.CLICK, makeClickListener(i));
}
in your example your i is not doing what you think it's doing. You've declared it as a global variable and passing into the function as you're doing is meaningless. In the end your buttons are simply reporting the current value of i (which after the loop is always 8).
I like the other solution offered, but here's a more object oriented solution, which may be of some use depending on what you're doing with your button (or other objects in the future).
public class MyButton extends Button{
public var myIndex:Number;
}
Now you use MyButton instead of Button and in your loop throw in
btn.myIndex = i;
then attach generic event handler
btn.addEventListener(MouseEvent.CLICK, myHandler);
which would look like this:
function myHandler(evt:MouseEvent){
trace(evt.target.myIndex);
}
See... the target of the event will always be the object to which you attached the event. It is to that object that you should attach whatever values you wish it to retain. Personally I prefer this approach because then the information is with the object (and can be used by other elements that might need it) rather than in the handler and only in the handler.
var test:MovieClip = new MovieClip();
var btn:Button;
for(var i:int = 1; i<=7; i++){
btn = new Button();
btn.name = i.toString();
btn.x = i * 100;
test.addChild(btn);
btn.addEventListener(MouseEvent.CLICK, nothing);
}
function nothing(event:MouseEvent):void {
//trace("You clicked " + int( event.currentTarget.name ) );
trace("You clicked " + event.currentTarget.name );
}