jeudi 30 avril 2015

Why does AS3's map callback require an additional two arguments?

Say I have:

myArray = [1,2,3];

And say I have a util function somewhere else:

add3 = function(val) {
   return val+3;
}

Now if I want to use that as the call back for a map function, I have to do something like this:

add3Callback = function(currentValue, index, array) {
    return add3(currentValue);
}

myArray.map(add3Callback);

Attempting myArray.map(add3) results in "argument count mistmatch". It would be better that the map callback doesn't require the extra two arguments, because now I have to add wrappers to all my util functions in order to use them with map, which goes against some of the reasons for using map in the first place.

What am I missing here? Why is having those arguments be compulsory useful, other languages (including Javascript) don't seem to do it.

Action Script 3 Counter/Button Color Change

I am new to Action Script and need assistance.

Essentially, I have 50 buttons, each button is in the shape of its corresponding state of the United States. My intentions are this, I will have a question display with only one correct answer (for example, which state is the sunshine state?) The objective then is to click on the correct state.

My issue is keeping the score, I figured I could go about this two ways, but I am struggling with both. First way would be a counter, if you click on the correct state add a point to the counter, if you click on the incorrect state don't add a point, but wrong or correct, both clicks will take you to the next question. The problem with this is creating a counter, I've tried numerous things and cant seem to get it to work.

The other is option was clicking on the correct state would change the color of that state green, and clicking the wrong state would change the color of the correct state to red with both clicks still taking you to the next question. I've also tried this method and can't seem to figure out how to change the color of the buttons. There isn't much code to show other than the 50 states buttons which I declared (i.e. virginiabutton.addEventListener(MouseEvent.CLICK, virginiabuttonclick);

Thanks

Despite using the same function. it behaves incorrectly one time?

I have the following code, its for a basic top down shooter similar to space invaders. When the player's bullets hit the enemy, the enemy follows the various hit functions correctly and flashes invisible for a third of a second. however when the player gets hit he seems to permanently turn invisible despite using the same functions. Any ideas as to why this happens and where I'm going wrong? My code may be considered messy by those of you with experience so please by all means criticize as much as you can :P The structure and process behind the code makes sense in my mind but if anyone is struggling feel free to ask "wtf are you doing" :P

package  {

import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.geom.ColorTransform;


public class Level1 extends MovieClip {

    public var player:Player; // play
    public var upgrade:blue_wep;
    public var enemy1:fly; // first enemy used for testing

    public var enemyList:Array = [];    // Array similar to bullets but for each enemy

    public var LevelTimer:Timer; // creating a game timer used to see how long the player survived

    public var upgraded:Boolean = false;

    //Code for shooting bullets
    public var bulletList:Array = []; //This array simply contains information for each bullet
    public var enemyBullets:Array = [];
    public var mousePressed:Boolean = false; //boolean similar to player movement but this checks if the mouse button is pressed
    public var weaponSpeed:Number = 1; // This is an amplifier to modify the player's shooting speed when collecting powerups
    public var delayCounter:int = 0; //used to create delay between shots
    public var delayMax:Number = 10 * weaponSpeed; //This is the number that defines how quickly we can shoot

    //The following variables are for when the fly gets hit by a bullet
    public var losingHealth:Boolean = false;
    public var hitTimer:int;
    public var deathTimer:int;
    public var hurt:Boolean = false;
    public var deathFlash:ColorTransform = new ColorTransform;

    public function Level1() {
        // constructor code
        player = new Player(stage, stage.stageWidth/2, stage.stageHeight/2, 100, 100, 10);
        stage.addChild(player);

        upgrade = new blue_wep(stage, stage.stageWidth/6, stage.stageHeight/2, 5);

        enemy1 = new fly(stage, (Math.random() * stage.stageWidth), (Math.random() * stage.stageHeight), player, 100, 100, 20);
        stage.addChild(enemy1);

        LevelTimer = new Timer(1000);

        hitTimer = 0;
        deathTimer = 0;
        deathFlash.color = 0xFFFFFF;

                                                                               // is clicked. This works for single fire
        stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false, 0, true);
        stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, false, 0, true);
        stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true);

    }
    public function loop(e:Event):void { // this function is the loop for adding bullets that move

        if(mousePressed) {
            delayCounter++
            if (delayCounter == delayMax) {
                PlayershootBullet();
                delayCounter = 0;
            }
        }

        if (bulletList.length > 0) { //if there are any bullets on the screen we are going to execute the following code
            for (var i:int = 0; i < bulletList.length; i++) { //the following code will be executed on each bullet
                bulletList[i].loop(); // we are going to use the loop function found in the bullet class file on each bullet
            }

        }

        enemyBullets = enemy1.bulletList;

        collisionCheck(bulletList, player, enemy1);
        if (losingHealth == true) {
            healthLoss(player, enemy1);
        }
        else {
            losingHealth = false;
        collisionCheck(enemyBullets, enemy1, player);
        if (losingHealth == true) {
            healthLoss(enemy1, player);
        }
    }
        }


    public function mouseDownHandler(e:MouseEvent):void {
        mousePressed = true;
    }

    public function mouseUpHandler(e:MouseEvent):void {
        mousePressed = false;
    }

    public function removeUpgrade():void {
        stage.removeChild(upgrade);
    }
    public function PlayershootBullet():void {
        var bullet:Bullet = new Bullet(stage, player.x, player.y, player.rotation, false);
        bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true); //if the bullet goes off the stage
                                                                                          // we will call the bulletremoved function
        bulletList.push(bullet); // add this bullet to the current list
        stage.addChild(bullet);
    }

    public function bulletRemoved(e:Event):void {
        e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved); // remove the listener to stop errors
        bulletList.splice(bulletList.indexOf(e.currentTarget), 1); // remove the bullet thats off the stage from the array
    }

    public function takeHit(wounded, shooter) {
        wounded.life -= shooter.dmg;
        wounded.healthratio = (http://ift.tt/1DYbNTd) * 100;
        trace(wounded.healthratio);

    }

    public function enemyFlash(flasher, shooter) {
        flasher.alpha = 0;
        if (hurt == false) {
            takeHit(flasher, shooter);
        }
    }

    public function hitReset(hostile) {
        trace("hitReset");
        hitTimer = 0;
        losingHealth = false;
        hurt = false;
        hostile.alpha = 1;
    }

    public function removeEnemy(cya) {
        deathTimer = 0;
        cya.removeSelf();
        for (var i = 0; i < bulletList.length;i++) {
            bulletList[i].x = stage.stageWidth + 100;
        }
    }

    public function collisionCheck(bullets, shooter, target) {
        for (var i = 0; i < bullets.length; i++) {
            if (bullets[i].hitTestObject(target)) {
                //bulletList[i].has_hit = true;
                bullets[i].x = stage.stageWidth + 100;
                bullets[i].y = stage.stageHeight + 100;
                losingHealth = true;
                }
            }

            if (target.healthratio <= 0) {
                removeEnemy(target);
            }
    }

    public function healthLoss(shooter, target) {
        hitTimer++;
        if (hitTimer < 10) {
            enemyFlash(target, shooter);
            hurt = true;
        }
        else {
            hitReset(target);
        }
    }
}

}

Simplebutton image is larger than it actually is

I'm creating a button I use beginBitmapFill method to add image to it. Everything works normally, the problem is that the image loaded by a Loader () is greater than it actually is

Class that creates the button

package mode {
        import flash.display.Sprite;
        import org.osmf.net.StreamingURLResource;
        
        public class LoadButton extends Sprite 
        {
                public var Save;
                public function LoadButton(x:uint,save:String,url:String) 
                {
                        var button:CustomSimpleButton = new CustomSimpleButton(url);
                        button.x = x;
                        Save = save;
                        addChild(button);
                }
        }
}

import flash.display.*;
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.events.*;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.geom.Matrix;

class CustomSimpleButton extends SimpleButton 
{
        private var upColor:uint   = 0xFFCC00;
        private var overColor:uint = 0xCCFF00;
        private var downColor:uint = 0x00CCFF;
        private var sizew:uint      = 100;
        private var sizeh:uint      = 88;
        
        public function CustomSimpleButton(url:String) 
        {
                downState      = new ButtonDisplayState(downColor, sizew,sizeh,url);
                overState      = new ButtonDisplayState(overColor, sizew,sizeh,url);
                upState        = new ButtonDisplayState(upColor, sizew,sizeh,url);
                hitTestState   = new ButtonDisplayState(upColor, sizew * 2,sizeh,url);
                hitTestState.x = -(sizew / 4);
                hitTestState.y = hitTestState.x;
                useHandCursor  = true;
        }
}

class ButtonDisplayState extends Shape 
{
        private var bgColor:uint;
        private var size:uint;
        private var sizeh:uint;
        
        public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String) 
        {
                this.bgColor = bgColor;
                this.size    = sizew;
                this.sizeh = sizeh;
                draw(url);
        }
        
        private function draw(url:String):void 
        {
                var myLoader:Loader = new Loader(); 
                var image:Bitmap;
                var uri = new URLRequest(url);
                myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
                {
                        image = new Bitmap(e.target.content.bitmapData);

                        graphics.beginBitmapFill(image.bitmapData);
                        graphics.drawRect(0, 0, 100, 88);
                        graphics.endFill();
                });
                myLoader.load(uri);     
        }
}

How the image is 100x88

How the image is 100x88

as it is

enter image description here

Flash AS3 Error #2101 for login screen

i'm still novice in AS3 Programming i was trying to get a login screen to work on my AIR Application, but i got error #2101 The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.

here's the code for processLogin

            public function processLogin():void {

                if(username.text != "" && password.text != "")
                {
                   var checkName = username.text
                   var checkPass = password.text
                   var resulttext = result_text.text

                   var request:URLRequest = new URLRequest("http://localhost/caservers/aksessistemlogin.php")
                   var loader:URLLoader = new URLLoader()    

                   var variables:URLVariables = new URLVariables()
                       variables.username = checkName            
                       variables.password = checkPass
                       variables.systemResult = resulttext
                   loader.dataFormat = URLLoaderDataFormat.VARIABLES
                   request.data = variables

                   request.method = URLRequestMethod.POST
                   loader.addEventListener(Event.COMPLETE, logincheck)
                   loader.load(request)

               }
               function logincheck (event:Event):void {

                  if (username.text == checkName && password.text == checkPass){
                     gotoAndPlay(2);
                  }else{
                     result_text.text = resulttext ;
                  }
               }
            }

and this one is the code for PHP

      <?php 
          include_once "connect.php";
          $username = $_POST['username'];
          $password = $_POST['password'];
          if ($_POST['systemCall'] == "checkLogin") {
              $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
              $query = mysqli_query($sql);
              $login_counter = mysqli_num_rows($query);
              if ($login_counter > 0) {
              while ($data = mysqli_fetch_array($query)) {

              }
              } else {
                  $systemResult = "The login details don't match our records";
              }
          }
      ?>

what i'm intend to do is to check if the username and password is match with the one in the database, i followed some tutorials but it ended up advancing to next frame even without typing anything in the text input (just by clicking submit).

any help will be very very appreciated! thanks in advance..

create mx Tree from a custom XML

i have a custom XML, i want to create a mx Tree from that xml, it looks like this one :

  <Saa:Header>
        <Saa:Message>
            <Saa:SenderReference> data
             </Saa:SenderReference>
       </Saa:Message>
        <Saa:Message>
            <Saa:SenderReference> data
             </Saa:SenderReference>
       </Saa:Message>
  </Saa:Header>

and

                    <mx:Tree id="myTreetest"
                     width="100%"
                     height="98%"
                     horizontalCenter="0"
                     labelField="@label"
                                    />

the script should be :

myTreetest.dataProvider = new XML(?);

How can I check if mms connection is alive?

I'm trying to check whether some mms links are alive or broken. I tried using netconnection however it didn't work, I got error.

EDIT: Here's the code I tried:

    // Inside function
    ShowCheckConnectionPopup();

    if (connection_combobox.selectedIndex == 0) {
        urlLoader.load(new URLRequest("http://" + addressStr));
    } else if (connection_combobox.selectedIndex == 1) {
        rtmpVurl = "rtmp://" + rtmpVurl;
        rtmp_test = new RTMP_test();
        addChild(rtmp_test);
        rtmp_test.init(rtmpSid, rtmpVurl);
        rtmp_test.addEventListener(CustomEvent2.PASS_PARAMS, onTestProcessed);
        /*
        rtmp_player.vid.x = 100;
        rtmp_player.vid.y = 100;
        */
    } else if (connection_combobox.selectedIndex == 2) {
        addressStr = "mms://" + addressStr;
        createRtmpConnection(addressStr);
    }
}

var _ncConnection:NetConnection = new NetConnection();
// create a new net connection, add event listener and connect
// to null because we don’t have a media server
_ncConnection = new NetConnection();
_ncConnection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
_ncConnection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
_ncConnection.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
_ncConnection.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
// _ncConnection.addEventListener(AsyncErrorEvent.ASYNC_ERROR,metaHandler);

function createRtmpConnection(s:String) {
    rtmpTimeoutTimer.reset();
    rtmpTimeoutTimer.start();
    _ncConnection.connect(s);
}

ArgumentError: Error #2004: One of the parameters is invalid. at flash.net::NetConnection/connect() at Untitled_02_02_fla::MainTimeline/createRtmpConnection()[Untitled_02_02_fla.MainTimeline::frame1:741] at Untitled_02_02_fla::MainTimeline/onPopupOkBtnClick()[Untitled_02_02_fla.MainTimeline::frame1:568]*

Line 741: _ncConnection.connect(s);

Line 568: createRtmpConnection(addressStr);

displaying data from the database using datagrid , flash , php , mysql , as3

I got the blank fields of the datagrid which does not display any data , when I try the .php or .xml file in the browser it displays the whole xml file.

    billRecords.addEventListener(MouseEvent.MOUSE_DOWN, dbShow);

function dbShow(e: MouseEvent): void {
        data_grid.addColumn("Table No");
        data_grid.addColumn("Date");
        data_grid.addColumn("Items");
        data_grid.addColumn("Quantity");
        data_grid.addColumn("Total");
        data_grid.width = 1150;
        data_grid.rowCount = 100;
        data_grid.move(5, 35);
        addChild(data_grid);

        var urlPhp: String = "billrecords.xml";
        var request: URLRequest = new URLRequest(urlPhp);
        var url_loader: URLLoader = new URLLoader();
        url_loader.addEventListener(Event.COMPLETE, completeHandler);
        url_loader.load(request);

        close_btn.x = 1155;
        close_btn.y = 10;
        addChild(close_btn);
        close_btn.addEventListener(MouseEvent.MOUSE_DOWN, closeDbShow);

    }
    function completeHandler(event: Event): void {
        var ldr: URLLoader = event.currentTarget as URLLoader;

        // create XML datastructure from loaded XML
        var xmlDP: XML = new XML(ldr.data);
        var xmlDoc:XMLDocument = new XMLDocument();
        xmlDoc.ignoreWhite = true;
        xmlDoc.parseXML(xmlDP.toXMLString());


        var dp=new DataProvider(xmlDP);
       trace(dp);

        data_grid.dataProvider = dp ;

    }

When I trace dp it show objects . How can I get these object to show the text in the datagrid . Please guys need help. Does DataGrid Works in Adobe Air apps ?Thank you

Adobe Flash: Manipulate RTMP Video Stream in Buffer Before Playing the Stream

Any Adobe Flash experts out there who can point me in the right direction when it comes to manipulating an RTMP video stream in the buffer before it begins playing in a flash video player such as FlowPlayer or JWPlayer where I have access to the video player's source code?

For example, lets say the video file has some extra data prepended to it that needs to be removed prior to the video actually playing in the flash player. I assume one would need to remove the prepended bytes of data from the stream, in the buffer, prior to it actually being played by the flash player.

Working on 2D arrays for my online class but none of my buttons work

So I'm working on a 2D array program to keep track of student info in a seperate .as3 file as follows
eleve[0] = ["Charles","Westmoreland",78,81,96,76];
I currently have eleve (student) ranging from 0 to 14. None of the buttons I have programmed so far work and the computer teacher at my school isn't familiar with as3 so he tried to help but couldn't.
The code is here (all the code is there so I didn't want to put it in here).
Any help fixing the buttons I have would be highyl appreciated.

How do I access a method of ClassA from classB?

I didn't really know what exactly to ask in the question. So I am going to explain everything here:

I am working on a Desktop AIR Database Application I have a Class named "Database Screen" which is linked to a movie clip:

package  {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.TextField;

public class DatabaseScreen extends MovieClip {

    private var allButtons:Array;
    private var codeSelected:Boolean;
    private var nameSelected:Boolean;
    private var xmlDatabase:XML;
    private var dbFile:File;
    public var xmlList:XMLList;
    private var totalProducts:uint;
    private var totalItems:uint = 0;
    private var productExists:Boolean;
    private var productId:Number;
    private var XMLReader:xmlReader;

    public function DatabaseScreen() {
        allButtons = [searchPanel.search_btn, addNewPanel.addNew_btn, dbStatsPanel.xls_btn, searchPanel.code_radio, searchPanel.name_radio];
        init();
    }

    private function init():void
    {
        XMLReader = new xmlReader();
        //adding event listeners..
        for(var i:int = 0; i<allButtons.length; i++)
        {
            allButtons[i].addEventListener(MouseEvent.MOUSE_OVER, onOver, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.MOUSE_OUT, onOut, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.MOUSE_DOWN, onDown, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.CLICK, onClick, false, 0, true);
            allButtons[i].buttonMode = true;
        }

        //creating a new file for the database
        dbFile = File.documentsDirectory.resolvePath("BlackCat/Database.xml");
        xmlDatabase = new XML();
        getXML();
        saveXML();
        getTotalItems();
        dbStatsPanel.items.text = String(totalItems);
    }
    private function getXML():void
    {
        if(dbFile.exists)
        {
            var stream:FileStream = new FileStream();
            stream.open(dbFile, FileMode.READ);
            xmlDatabase = new XML(stream.readUTFBytes(stream.bytesAvailable));
            stream.close();
            xmlList = xmlDatabase.Product;
            dbStatsPanel.products.text = xmlList.length();
            XMLReader.xmlData = xmlList;
            XMLReader.updateXMLList(xmlList);

        }
        else
        {
            xmlDatabase = <Products></Products>
        }
    }
    public function getXMlList():XMLList
    {
        return xmlList;
    }
    private function getTotalItems():void
    {
        for(var i:int = 0; i < xmlList.length(); i++)
        {
            totalItems += uint(xmlList[i].@Qty);
        }
    }
    private function saveXML():void
    {
        var stream:FileStream = new FileStream();
        stream.open(dbFile, FileMode.WRITE);
        stream.writeUTFBytes(xmlDatabase.toXMLString());
    }
    private function onDown(evt:MouseEvent):void
    {
        evt.target.scaleX = evt.target.scaleY = .8;
    }
    private function onUp(evt:MouseEvent):void
    {
        evt.target.scaleX = evt.target.scaleY = 1;

    }
    private function onOver(evt:MouseEvent):void
    {
        evt.target.alpha = .5;
    }
    private function onOut(evt:MouseEvent):void
    {
        evt.target.alpha = 1;
        evt.target.scaleX = evt.target.scaleY = 1;
    }
    private function onClick(evt:MouseEvent):void
    {
        switch(evt.target.name)
        {
            case "code_radio":
                codeSelected = true;
                nameSelected = false;
                searchPanel.code_radio.gotoAndStop(1);
                searchPanel.name_radio.gotoAndStop(2);
            break;

            case "name_radio":
                nameSelected = true;
                codeSelected = false;
                searchPanel.code_radio.gotoAndStop(2);
                searchPanel.name_radio.gotoAndStop(1);
            break;

            case "addNew_btn":
                //Checking if the product already exists..
                for(var i:int = 0; i < xmlList.length(); i++)
                {
                    if(xmlList[i].@code == addNewPanel.add_code_txt.text)
                    {
                        productExists = true;
                        productId = i;
                    }
                }
                if(productExists)
                {
                    var PQty:uint = uint(xmlList[productId].@Qty);
                    var PQtoAdd:uint = uint(addNewPanel.add_qty_txt.text);
                    PQty += PQtoAdd;
                    xmlList[productId].@Qty = String(PQty);
                    productExists = false;
                }
                else
                {
                    xmlDatabase.appendChild(<Product code={addNewPanel.add_code_txt.text} 
                    name={addNewPanel.add_name_txt.text} Price={addNewPanel.add_price_txt.text} 
                    Qty={addNewPanel.add_qty_txt.text}></Product>);
                }
                totalItems += uint(addNewPanel.add_qty_txt.text);
                xmlList = xmlDatabase.Product;
                dbStatsPanel.products.text = xmlList.length();
                dbStatsPanel.items.text = String(totalItems);
                XMLReader.updateXMLList(xmlList);
                saveXML();
                trace(xmlDatabase);
            break;

        }
    }
    public function setVisiblity(visibility:Boolean):void
    {
        switch(visibility)
        {
            case true:
                this.visible = true;
            break;

            case false:
            this.visible = false;
            break;
        }
    }
    public function getXMLList():XMLList
    {
        return xmlList;
    }


}

}

And I have another class named "NewOrder", in this class I am trying to access the xmlList from the "DatabaseScreen" class but I am unable to do so.

package  {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import com.greensock.TweenMax;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;


public class NewOrder extends MovieClip {
    private var allButtons:Array;
    private var shoppingCart:Array;
    private var scroller:FlickScroll;
    private var db:DatabaseScreen;
    private var XMLReader:xmlReader;

    public function NewOrder() {
        this.visible = false;

        init(db);
    }
    private function init(dbase:DatabaseScreen):void
    {
        XMLReader = new xmlReader();
        trace(XMLReader.xmlData);

        scroller = new FlickScroll(masker, container, 84.05, -500);
        addChild(scroller);
        allButtons = [scan_btn, print_invoice];
        shoppingCart = [];
        for(var i:int = 0; i < allButtons.length; i++)
        {
            allButtons[i].addEventListener(MouseEvent.MOUSE_OVER, onOver, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.MOUSE_OUT, onOut, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.MOUSE_DOWN, onDown, false, 0, true);
            allButtons[i].addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
            allButtons[i].mouseChildren = false;
            allButtons[i].buttonMode = true;
        }
    }

    private function onOver(evt:MouseEvent):void
    {
        evt.target.alpha = .5;
    }
    private function onOut(evt:MouseEvent):void
    {
        evt.target.alpha = 1;
        evt.target.scaleX = evt.target.scaleY = 1;
    }
    private function onDown(evt:MouseEvent):void
    {
        evt.target.scaleX = evt.target.scaleY = .8;
    }
    private function onUp(evt:MouseEvent):void
    {
        evt.target.scaleX = evt.target.scaleY = 1;
        if(evt.target.name == "scan_btn")
        {
            var cartElement:CartElement = new CartElement();
            container.addChild(cartElement);
            cartElement.x = 0;
            cartElement.alpha = 0;
            TweenMax.to(cartElement, .4, {alpha:1});
            shoppingCart.push(cartElement);
            cartElement.id_txt.text = String(shoppingCart.length) + " - ";

            if(shoppingCart.length < 2)
            {
                cartElement.y = container.height - 30;
            }
            else
            {
                cartElement.y = container.height + 5;
            }

        }
    }
}

}

And there is a Main class in which I handle all the screens , e.g DatabaseScreen, NewOrder.. Which means I have added these to the display list in the Main class. To access the xmlList from the DatabaseScreen , I tried creating a new instance in the NewOrder class, but it creates to DatabaseScreen(s). I also tried creating another class named "xmlReader": package {

public class xmlReader {
    public var xmlData:XMLList;

    public function xmlReader() {

    }

    public function updateXMLList(updatedList:XMLList):void
    {
        xmlData = updatedList;
    }

}

}

In the databaseScreen class, as soon as I populate the xmlList , I set the xmlData of the xmlReader class equal to the xmlList from the databaseScreen class. And when I trace the XMLReader.xmlData in the databaseScreen , it works fine . But when I do the same thing in the NewOrder class, I get "null" in the output window. How do I solve this problem. Any help is greatly appreciated.

Is it possible to run Adobe Air application in the browser?

I'm following this tutorial that describes the way of connecting the node.js app with adobe action script 3.0. In that way I could present live video data (received by UDP from different application) to some other user. My question is - is it possible to make the video player with received data embedded on my html/php website? I checked the official documentation and there's a sentence:

The DatagramSocket class can only be used in Adobe AIR applications and only in the application security sandbox.

and on this forum someone wrote:

You can run an Adobe Air application FROM the browser.
But you cannot run an Adobe Air applicatin WITHIN the browser.

Indeed, Adobe Air wraps webkit (a very famous html rendering engine).
Think of Adobe Air as a shell built around an browser.

If you want to run something within the browser you can go with Flash/Flex.

But it's pretty old post, so maybe something has changed? Or maybe there's a way to convert the AIR app to Flash/Flex? Thanks!

Unable to call Javascript method from HTML page while load .swf in Android WebView- Throws: security error: error #2060

I've created a Android App where I've some .swf files inside my asset folder. I'm loading these files in a WebView. For that I've created a HTML page "myHTML.html" which loads the .swf file. Here is my HTML Page:

<!DOCTYPE html>
<html>
<head>
    <script language="javascript">
        function diplayJavaMsg(msg){
            alert(msg);
        }

        function functionCalledFromSWF(Score) {
            alert(Score);
            JsHandler.callToJavaFunction(Score);
        }
  </script>
 </head>
<body>
    <object type="application/x-shockwave-flash" data="Sush19/Games/level/level.swf" width="100%" height="100%">
        <param name="quality" value="high" />
        <param name="allowFullScreen" value="true" />
        <param name="allowScriptAccess" value="samedomain" />
        <param name="base" value="Sush19/Games/level" />
    </object>
</body>
</html>

Following is my Java class

public class MainAct extends Activity implements OnClickListener {

    private WebView webView;
    private Button btn;
    private JsHandler _jsHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);

        WebView webView = (WebView) findViewById(R.id.webView1);
        loadGame(webView);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void loadGame(WebView webViewID) {
        webViewID.getSettings().setJavaScriptEnabled(true);
        webViewID.setBackgroundColor(Color.parseColor("#808080"));
        webViewID.getSettings().setDomStorageEnabled(true);
        webViewID.getSettings().setBuiltInZoomControls(false);
        webViewID.getSettings().setAppCacheMaxSize(1024 * 8);
        webViewID.getSettings().setAppCacheEnabled(true);
        webViewID.getSettings().setAllowFileAccess(true);
        webViewID.getSettings().setPluginState(PluginState.ON);
        webViewID.getSettings().setUseWideViewPort(false);
        webViewID.getSettings().setRenderPriority(RenderPriority.HIGH);
        webViewID.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webViewID.setWebChromeClient(new WebChromeClient());
        webViewID.setWebViewClient(new WebViewClient());
        webViewID.requestFocus(View.FOCUS_DOWN);
        String url = "file:///android_asset/myHTML.html";
        webViewID.loadUrl(url);
    }
}

JS Bridge Class

public class JsHandler {
    Activity activity;
    String TAG = "JsHandler";
    WebView webView;


    public JsHandler(Activity _contxt,WebView _webView) {
        activity = _contxt;
        webView = _webView;
    }

    /**
     * This function handles call from JS
     */
    public void callToJavaFunction(String Score) {

    }

    /**
     * This function handles call from Android-Java
     */
    public void javaFnCall(String jsString) {

        final String webUrl = "javascript:diplayJavaMsg('"+jsString+"')";
        // Add this to avoid android.view.windowmanager$badtokenexception unable to add window
        if(!activity.isFinishing()) 
            // loadurl on UI main thread
        activity.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                webView.loadUrl(webUrl); 
            }
        });
    }
}

Code inside .swf which calls Javascript method: Actionscript method:

public var environment:String="";
environment=ExternalInterface.call("functionCalledFromSWF");

I'm unable to call Javascript method from Actionscript in Android Webview. The .swf file plays fine in the WebView.

Can I use Unity3D in Flash?

I use Unity3D in Flash?
I know Unity3D does not support for Flash anymore.
Recently I'm trying to bring Unity3D in Flash.
But I'm stuck now. so I would like to ask about it can be done.

any comment will be very grateful. Thanks!

Development environment
--------------------------------------
Tool : Flash CC
Language : ActionScript 3.0
SDK : Adobe AIR 17
Platform : Windows OS

Flash and Socket.io can't connect

I have a server with Node.js and socket.io but I can not connect to a Web application in flash with socket.io. anyone knows of any examples that can guide me?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(//io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
 io.set('transports', ['websocket','flashsocket']);
 io.set('flashPolicyServer', true);
 io.set('flash policy port', 3000);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

io.on('connect', function(socket){
 console.log('connect');
});

http.listen(3000, function(){
  console.log('listening on *:3000');

Tell Target code (convert to as3)

This is the code which I used in AS2

on (release) {
 tellTarget ("/incorrect")
 {
  nextFrame();
 }
}

How do I do this in AS3 (AIR) ?

Thank you.

AS3 multi level menu whith PDF

There are 30 PDF files with instructions. It is necessary to place them in a multi-level menu. The final level is to run PDF files via fscommand. How to implement a similar task with the minimum knowledge of AS3? http://ift.tt/1bgYIdd

mercredi 29 avril 2015

Displaying the total sum of values from strings

My project is a simple shopping game where the user types in the quantity amount, and the value of the individual prices appears and then a total sum can appear below.

I have managed to create the part of displaying the individual product price but i am confused on how to add the total sum and display correctly at the instance that i defined.

Some info

Actionscript will check for keypress event

sample of code snippet:

    if(e.keyCode == 49){ //1
    trace("Key Code Pressed: " + e.keyCode);
    amount1.text = "1.00"
    }

From the code above, when the user types 1, the price will change to "1.00" on the price instance field (dynamic text type).

Picture below:

A sample of my game running: enter image description here

Total price should be $13.00 dollars..

Is there any way to make this happen? I believe is it something to do with parseint.

Really Appreciate your time!!

How do I use a button that I referenced from with library with Actionscript 3?

Hi I'm a newbie at using Stack Overflow so bear with me if my formatting or explanation seems shabby.

Currently in my code I have it set up so that when a certain condition happens, one of my movie clips from my library gets added to the stage, which is what I wanted. However in addition to this I'd like to use a button that is within that movie clip to reference another scene and send the user there, but I can't figure out how to do that.

Any help would be helpful, thanks!

In AS3, why doesn't Changing List class's selectedIndex doesn't update the cellrenderer skins at either index

I am listening to the ListEvent.ITEM_CLICK of "myList".

I am able to change the "selectedIndex" of the list, but the "selectedUpSkin" still appears on the item that was clicked, not the item that's specified. I am just looking for the correct way to update the list visuals.

public function OnMyListItemClick(listEvent:ListEvent):void
{
    // I expect none of the cell renderers 
    ///to draw the selectedUpSkin if I do this
    //myList.selectedIndex = -1; 


    // I expect the second cell renderer to use the selectedUpSkin
    // if I do this 
    myList.selectedIndex = 1;
}

Despite various attempts, the item clicked on remains the only one that looks "selected".

I've even tried

myList.invalidate() 

which causes the list to flicker, but the button skins are unaffected.

What am I doing wrong? Maybe it's because my cell renderers extend ImageCell, which extend Button. I've had general problems with button skins updating when their "selected" state changes as well.

Flash Webcam Capture

I am trying to build AS3 web audio/video capture. I have successfully tried to display the webcam stream with the help of this great tutorial. The next step is how do i capture the video when the user starts recording. Below is my code:

// video stuff
        private var camW:int = 300;
        private var camH:int = 300;
        private var video:Video;

        // block stuff
        private var rows:int = 3;
        private var cols:int = 3;
        private var blockW:int = camW/cols;
        private var blockH:int = camH/rows;
        private var pointArray:Array = new Array();

        public function Main():void {

            // Checks if camera is installed
            if (Camera.names.length > 0) { 
                trace("User has at least one camera installed."); 
                var camera:Camera = Camera.getCamera();
                camera.setMode(camW, camH, 30);
                camera.addEventListener(StatusEvent.STATUS, statusHandler); 
                video = new Video(camW, camH);
                video.attachCamera(camera);

                initBlocks();
                addEventListener(Event.ENTER_FRAME, updateBlocks);
            }else { 
                trace("User has no cameras installed."); 
                var text:TextField = new TextField();
                text.text = "Device Not Found! Please check if the camera is installed.";
                text.x = 20;
                text.y = 20;
                text.width = 500;
                addChild(text);
            }

            function statusHandler(event:StatusEvent):void {
                // This event gets dispatched when the user clicks the "Allow" or "Deny" 
                // button in the Flash Player Settings dialog box. 
                trace(event.code); // "Camera.Muted" or "Camera.Unmuted"

                switch (event.code) {
                    case "Camera.Muted": 
                        trace("User clicked Deny.");
                        var text:TextField = new TextField();
                        text.text = "Device Denied Permission! Please provide permission to record video!";
                        text.x = 20;
                        text.y = 20;
                        text.width = 500;
                        addChild(text);
                        break; 
                    case "Camera.Unmuted": 
                        trace("User clicked Accept."); 
                        break; 
                } 
            }

        }

        private function initBlocks():void {
            for (var r:int = 0; r < rows; r++) {
                for (var c:int = 0; c < cols; c++) {
                    var newBlock:Sprite = new Sprite();
                    newBlock.name = "block" + r + c;
                    var p:Point = new Point(c * blockW, r * blockH);
                    newBlock.x = c * (blockW) + 20;
                    newBlock.y = r * (blockH) + 20;
                    pointArray[newBlock.name] = p;

                    var bmpd:BitmapData = new BitmapData(blockW, blockH);
                    var bmp:Bitmap = new Bitmap(bmpd);
                    bmp.name = "myBmp";

                    newBlock.addChild(bmp);
                    addChild(newBlock);             
                }
            }           
        }

        private function updateBlocks(e:Event):void {
            var srcBmpd:BitmapData = new BitmapData(camW, camH);
            srcBmpd.draw(video);
            for (var r:int = 0; r < rows; r++) {
                for (var c:int = 0; c < cols; c++) {
                    var b_mc:Sprite = this.getChildByName("block" + r + c) as Sprite;
                    var bmp:Bitmap = b_mc.getChildByName("myBmp") as Bitmap;
                    var p:Point = pointArray[b_mc.name];

                    bmp.bitmapData.copyPixels(srcBmpd, new Rectangle(p.x, p.y, blockW, blockH), new Point());
                }
            }
        }

I am completely new to AS3, just started 2 days ago. What is the logic for audio/video capture in AS3? Any pointers/demo/tutorials/books appreciated

Adding MovieClips in a grid to stage from based on keyPresses

Looking to see if anyone can help me out with this before i lose my mind! I am required to add movieclips for each of the alphabetical keys (a to z) the user presses on the keyboard, on the stage commencing at the top left corner of the stage proceeding horizontally across the stage towards the right. key on the stage, commencing at the top left corner of the stage and proceeding horizontally across the stage for each subsequent character. I currently have this code however the movieclips that are entered into a container overlap as the user presses the keys on the keyboard. Help desperately needed!

import flash.display.MovieClip;
var nextYPos:int = 25;
var i:int = 0;

var A_mc = new AKey();
var B_mc = new BKey();
var C_mc = new CKey();
var D_mc = new DKey();
var E_mc = new EKey();
var F_mc = new FKey();
var G_mc = new GKey();//declare lose movieclip variable
var H_mc = new HKey();
var I_mc = new IKey();
var J_mc = new JKey();
var K_mc = new KKey();
var L_mc = new LKey();
var M_mc = new MKey();//declare lose movieclip variable
var N_mc = new NKey();
var O_mc = new OKey();
var P_mc = new PKey();
var Q_mc = new QKey();
var R_mc = new RKey();
var S_mc = new SKey();//declare lose movieclip variable
var T_mc = new TKey();
var U_mc = new UKey();
var V_mc = new VKey();
var W_mc = new WKey();
var X_mc = new XKey();
var Y_mc = new YKey();
var Z_mc = new ZKey();

var container:Sprite = new Sprite();
addChild(container);
container.x = 50;
container.y = 30;
//container.width = 30;

stage.addEventListener(KeyboardEvent.KEY_DOWN, letters);

function letters(e:KeyboardEvent):void{

    if (e.keyCode == Keyboard.A){
            container.addChild(A_mc);
            // A_mc = textinput;
            //A_mc.x = 50;//x value for lose movieclip addChild
            //A_mc.y = 30;//y value for lose movieclip addChild
             A_mc.x = nextYPos;

    }if (e.keyCode == Keyboard.B){
            container.addChild(B_mc);
            //B_mc = textinput;
            //B_mc.x = 75;
            //B_mc.y = 30;
             B_mc.x = nextYPos;


    }if (e.keyCode == Keyboard.C){
            container.addChild(C_mc);
            //C_mc.x = 100;
            //C_mc.y = 30;

    }if (e.keyCode == Keyboard.D){
            container.addChild(D_mc);
            //D_mc.x = 125;
            //D_mc.y = 30;

    }if (e.keyCode == Keyboard.E){
            container.addChild(E_mc);
            //E_mc.x = 150;
            //E_mc.y = 30;

    }if (e.keyCode == Keyboard.F){
            container.addChild(F_mc);
            //F_mc.x = 175;//x value for lose movieclip addChild
            //F_mc.y = 30;//y value for lose movieclip addChild

    }if (e.keyCode == Keyboard.G){
            container.addChild(G_mc);
            //G_mc.x = 195;
            //G_mc.y = 30;

    }if (e.keyCode == Keyboard.H){
            container.addChild(H_mc);
            //H_mc.x = 220;
            //H_mc.y = 30;

    }if (e.keyCode == Keyboard.I){
            container.addChild(I_mc);
            //I_mc.x = 245;
            //I_mc.y = 30;

    }if (e.keyCode == Keyboard.J){
            container.addChild(J_mc);
            //J_mc.x = 255;
            //J_mc.y = 30;

    }if (e.keyCode == Keyboard.K){
            container.addChild(K_mc);
            //K_mc.x = 275;//x value for lose movieclip addChild
            //K_mc.y = 30;//y value for lose movieclip addChild

    }if (e.keyCode == Keyboard.L){
            container.addChild(L_mc);
            //L_mc.x = 300;
            //L_mc.y = 30;

    }if (e.keyCode == Keyboard.M){
            container.addChild(M_mc);
            //M_mc.x = 320;
            //M_mc.y = 30;

    }if (e.keyCode == Keyboard.N){
            container.addChild(N_mc);
            //N_mc.x = 350;
            //N_mc.y = 30;

    }if (e.keyCode == Keyboard.O){
            container.addChild(O_mc);
            //O_mc.x = 375;
            //O_mc.y = 30;

    }if (e.keyCode == Keyboard.P){
            container.addChild(P_mc);
            //P_mc.x = 400;//x value for lose movieclip addChild
            //P_mc.y = 30;//y value for lose movieclip addChild

    }if (e.keyCode == Keyboard.Q){
            container.addChild(Q_mc);
            //Q_mc.x = 50;
            //Q_mc.y = 80;

    }if (e.keyCode == Keyboard.R){
            container.addChild(R_mc);
            //R_mc.x = 75;
            //R_mc.y = 80;

    }if (e.keyCode == Keyboard.S){
            container.addChild(S_mc);
            //S_mc.x = 100;
            //S_mc.y = 80;

    }if (e.keyCode == Keyboard.T){
            container.addChild(T_mc);
            //T_mc.x = 120;
            //T_mc.y = 80;

    }if (e.keyCode == Keyboard.U){
            container.addChild(U_mc);
            //U_mc.x = 140;//x value for lose movieclip addChild
            //U_mc.y = 80;//y value for lose movieclip addChild

    }if (e.keyCode == Keyboard.V){
            container.addChild(V_mc);
            //V_mc.x = 165;
            //V_mc.y = 80;

    }if (e.keyCode == Keyboard.W){
            container.addChild(W_mc);
            //W_mc.x = 190;
            //W_mc.y = 80;

    }if (e.keyCode == Keyboard.X){
            container.addChild(X_mc);
            //X_mc.x = 220;
            //X_mc.y = 80;

    }if (e.keyCode == Keyboard.Y){
            container.addChild(Y_mc);
            //Y_mc.x = 245;
            //Y_mc.y = 80;

    }if (e.keyCode == Keyboard.Z){
        container.addChild(Z_mc);
        //Z_mc.x = 270;
        //Z_mc.y = 80;

    }else {
    }
}

enter image description here

sound coding for flash as3

I'm a beginner for flash as3 coding, and am in the process of making a flash game for class; I have the player (spaceCat) collect stars (s1, s2, s3, etc.) on the screen, and every time a star is collected, there is a sound (audio is named 'collect', with hitTestObject for each star). My questions are:

  1. How to I disable the sound from playing when at the starting/instruction screens, (stars and player are invisible but it seems like they are colliding while invisible)
  2. How do I disable the sound from playing when it goes to the Try Again and Credits screens,
  3. How do I make it so that when all stars disappear/are collected, it makes the Game Complete screen objects appear,
  4. Lastly, how do I code so that when the tryAgain (tryAgn) button is clicked, it resets the game to the same things as in the spaceCat layer?

This project is due next Monday (5/4/15) so any help is appreciated.

Here's my code for each layer that contains code (all coding is on Frame 1):

tryAgain

tryAgn.addEventListener(MouseEvent.CLICK, TAClickHandler);
function TAClickHandler(event:MouseEvent):void
{

}

quit1.addEventListener(MouseEvent.CLICK, Quit1ClickHandler);
function Quit1ClickHandler(event:MouseEvent):void
{
    failed.visible=false;
    quit1.visible=false;
    tryAgn.visible=false;
    bg.visible=true;
    mission.visible=true;
    info.visible=true;
    earth.visible=true;
    m1.stop();
    m2.stop();
    m3.stop();
    m4.stop();
    m5.stop();
    stage.removeEventListener(Event.ENTER_FRAME,followcat);
}

pauseScreen

pause.addEventListener(MouseEvent.CLICK, pauseGame);
function pauseGame(e:MouseEvent):void{
    pause.visible=false;
    pause_txt.visible=true;
    pauseScreen.visible=true;
    stage.frameRate = 0;
}

playBtn.addEventListener(MouseEvent.CLICK, resumeGame);
function resumeGame(e:MouseEvent):void{
        pause_txt.visible=false;
        pauseScreen.visible=false;
        pause.visible=true;
        stage.frameRate = 25;
}

spaceCat

//healthBar status

var maxHP:int = 100;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;

function updateHealthBar():void
{
    percentHP = currentHP / maxHP;
    healthBar.barColor.scaleX = percentHP;
}

stage.addEventListener(Event.ENTER_FRAME,followcat);

//makes cat move along with cursor
function followcat(event:Event):void 
{
var dx:int = spaceCat.x - mouseX;
var dy:int = spaceCat.y - mouseY;
spaceCat.x -= dx / 5;
spaceCat.y -= dy / 5;
CheckHit1();
CheckHit2();
}


//when spacecat collides with meteoroid, health depletes.
function CheckHit1():void
{


    if (spaceCat.hitTestObject(m1) == true)
    {
        currentHP -= 10;
        if(currentHP <= 0)
            {
                currentHP = 0;
                spaceCat.visible=false;
                playBtn.visible=false;
                pause.visible=false;
                healthBar.visible=false;
                failed.visible=true;
                tryAgn.visible=true;
                quit1.visible=true;
                bg.visible=false;
                m1.visible=false;
                m1.stop();
                m2.visible=false;
                m2.stop();
                m3.visible=false;
                m3.stop();
                m4.visible=false;
                m4.stop();
                m5.visible=false;
                m5.stop();
                timeStatic.visible=false;
                timer.visible=false;
            }
        updateHealthBar();  
    }

    if (spaceCat.hitTestObject(m2) == true)
    {
        currentHP -= 11.2;
        if(currentHP <= 0)
            {
                currentHP = 0;
                spaceCat.visible=false;
                playBtn.visible=false;
                pause.visible=false;
                healthBar.visible=false;
                failed.visible=true;
                tryAgn.visible=true;
                quit1.visible=true;
                bg.visible=false;
                m1.visible=false;
                m1.stop();
                m2.visible=false;
                m2.stop();
                m3.visible=false;
                m3.stop();
                m4.visible=false;
                m4.stop();
                m5.visible=false;
                m5.stop();
                timeStatic.visible=false;
                timer.visible=false;
            }
        updateHealthBar();  
    }

        if (spaceCat.hitTestObject(m3) == true)
    {
        currentHP -= 11.2;
        if(currentHP <= 0)
            {
                currentHP = 0;
                spaceCat.visible=false;
                playBtn.visible=false;
                pause.visible=false;
                healthBar.visible=false;
                failed.visible=true;
                tryAgn.visible=true;
                quit1.visible=true;
                bg.visible=false;
                m1.visible=false;
                m1.stop();
                m2.visible=false;
                m2.stop();
                m3.visible=false;
                m3.stop();
                m4.visible=false;
                m4.stop();
                m5.visible=false;
                m5.stop();
                timeStatic.visible=false;
                timer.visible=false;
            }
        updateHealthBar();  
    }

        if (spaceCat.hitTestObject(m4) == true)
    {
        currentHP -= 11.2;
        if(currentHP <= 0)
            {
                currentHP = 0;
                spaceCat.visible=false;
                playBtn.visible=false;
                pause.visible=false;
                healthBar.visible=false;
                failed.visible=true;
                tryAgn.visible=true;
                quit1.visible=true;
                bg.visible=false;
                m1.visible=false;
                m1.stop();
                m2.visible=false;
                m2.stop();
                m3.visible=false;
                m3.stop();
                m4.visible=false;
                m4.stop();
                m5.visible=false;
                m5.stop();
                timeStatic.visible=false;
                timer.visible=false;
            }
        updateHealthBar();  
    }

        if (spaceCat.hitTestObject(m5) == true)
    {
        currentHP -= 11.2;
        if(currentHP <= 0)
            {
                currentHP = 0;
                spaceCat.visible=false;
                playBtn.visible=false;
                pause.visible=false;
                healthBar.visible=false;
                failed.visible=true;
                tryAgn.visible=true;
                quit1.visible=true;
                bg.visible=false;
                m1.visible=false;
                m1.stop();
                m2.visible=false;
                m2.stop();
                m3.visible=false;
                m3.stop();
                m4.visible=false;
                m4.stop();
                m5.visible=false;
                m5.stop();
                timeStatic.visible=false;
                timer.visible=false;
            }
        updateHealthBar();  
    }

}

//when spacecat collides with a star, star disappears and makes sound
function CheckHit2():void

{

    if (spaceCat.hitTestObject(s1) == true)
    {
        s1.visible=false;
        var mySound1:Sound = new collect(); 
        mySound1.play();

    }

    if (spaceCat.hitTestObject(s2) == true)
    {
        s2.visible=false;
        var mySound2:Sound = new collect(); 
        mySound2.play();
    }

    if (spaceCat.hitTestObject(s3) == true)
    {
        s3.visible=false;
        var mySound3:Sound = new collect(); 
        mySound3.play();
    }

    if (spaceCat.hitTestObject(s4) == true)
    {
        s4.visible=false;
        var mySound4:Sound = new collect(); 
        mySound4.play();
    }

    if (spaceCat.hitTestObject(s5) == true)
    {
        s5.visible=false;
        var mySound5:Sound = new collect(); 
        mySound5.play();
    }

    if (spaceCat.hitTestObject(s6) == true)
    {
        s6.visible=false;
        var mySound6:Sound = new collect(); 
        mySound6.play();
    }

    if (spaceCat.hitTestObject(s7) == true)
    {
        s7.visible=false;
        var mySound7:Sound = new collect(); 
        mySound7.play();
    }

    if (spaceCat.hitTestObject(s8) == true)
    {
        s8.visible=false;
        var mySound8:Sound = new collect(); 
        mySound8.play();
    }

    if (spaceCat.hitTestObject(s9) == true)
    {
        s9.visible=false;
        var mySound9:Sound = new collect(); 
        mySound9.play();
    }

    if (spaceCat.hitTestObject(s10) == true)
    {
        s10.visible=false;
        var mySound10:Sound = new collect(); 
        mySound10.play();
    }

    if (spaceCat.hitTestObject(s11) == true)
    {
        s11.visible=false;
        var mySound11:Sound = new collect(); 
        mySound11.play();
    }

    if (spaceCat.hitTestObject(s12) == true)
    {
        s12.visible=false;
        var mySound12:Sound = new collect(); 
        mySound12.play();
    }

    if (spaceCat.hitTestObject(s13) == true)
    {
        s13.visible=false;
        var mySound13:Sound = new collect(); 
        mySound13.play();
    }

    if (spaceCat.hitTestObject(s14) == true)
    {
        s14.visible=false;
        var mySound14:Sound = new collect(); 
        mySound14.play();
    }

    if (spaceCat.hitTestObject(s15) == true)
    {
        s15.visible=false;
        var mySound15:Sound = new collect(); 
        mySound15.play();
    }

    if (spaceCat.hitTestObject(s16) == true)
    {
        s16.visible=false;
        var mySound16:Sound = new collect(); 
        mySound16.play();
    }

    if (spaceCat.hitTestObject(s17) == true)
    {
        s17.visible=false;
        var mySound17:Sound = new collect(); 
        mySound17.play();
    }

    if (spaceCat.hitTestObject(s18) == true)
    {
        s18.visible=false;
        var mySound18:Sound = new collect(); 
        mySound18.play();
    }

    if (spaceCat.hitTestObject(s19) == true)
    {
        s19.visible=false;
        var mySound19:Sound = new collect(); 
        mySound19.play();
    }

    if (spaceCat.hitTestObject(s20) == true)
    {
        s20.visible=false;
        var mySound20:Sound = new collect(); 
        mySound20.play();
    }

    if (spaceCat.hitTestObject(s21) == true)
    {
        s21.visible=false;
        var mySound21:Sound = new collect(); 
        mySound21.play();
    }

    if (spaceCat.hitTestObject(s22) == true)
    {
        s22.visible=false;
        var mySound22:Sound = new collect(); 
        mySound22.play();
    }

    if (spaceCat.hitTestObject(s23) == true)
    {
        s23.visible=false;
        var mySound23:Sound = new collect(); 
        mySound23.play();
    }

}

instructionPage3

var nCount:Number = 59
var myTimer:Timer = new Timer(1000, nCount);

next3.addEventListener(MouseEvent.CLICK, clickNext2);

function clickNext2(event:MouseEvent):void
{
    next3.visible=false;
    instruction3.visible=false;
    example.visible=false;
    spaceCat.visible=true;
    bg.visible=true
    playBtn.visible=true;
    pause.visible=true;
    var mySound:Sound = new stars(); 
    mySound.play(0, 8);
    healthBar.visible=true;
    timeStatic.visible=true;
    timer.visible=true;
    m1.play();
    m2.play();
    m3.play();
    m4.play();
    m5.play();
    s1.visible=true;
    s2.visible=true;
    s3.visible=true;
    s4.visible=true;
    s5.visible=true;
    s6.visible=true;
    s7.visible=true;
    s8.visible=true;
    s9.visible=true;
    s10.visible=true;
    s11.visible=true;
    s12.visible=true;
    s13.visible=true;
    s14.visible=true;
    s15.visible=true;
    s16.visible=true;
    s17.visible=true;
    s18.visible=true;
    s19.visible=true;
    s20.visible=true;
    s21.visible=true;
    s22.visible=true;
    s23.visible=true;


    timer.text = nCount.toString();
    myTimer.start()

    myTimer.addEventListener(TimerEvent.TIMER, countdown);

    function countdown(e:TimerEvent):void
    {
        nCount--;
        timer.text = nCount.toString();

        if( nCount ==0  )
        {
            spaceCat.visible=false;
            playBtn.visible=false;
            pause.visible=false;
            healthBar.visible=false;
            failed.visible=true;
            tryAgn.visible=true;
            quit1.visible=true;
            bg.visible=false;
            m1.visible=false;
            m1.stop();
            m2.visible=false;
            m2.stop();
            m3.visible=false;
            m3.stop();
            m4.visible=false;
            m4.stop();
            m5.visible=false;
            m5.stop();
            timeStatic.visible=false;
            timer.visible=false;
            s1.visible=false;
            s2.visible=false;
            s3.visible=false;
            s4.visible=false;
            s5.visible=false;
            s6.visible=false;
            s7.visible=false;
            s8.visible=false;
            s9.visible=false;
            s10.visible=false;
            s11.visible=false;
            s12.visible=false;
            s13.visible=false;
            s14.visible=false;
            s15.visible=false;
            s16.visible=false;
            s17.visible=false;
            s18.visible=false;
            s19.visible=false;
            s20.visible=false;
            s21.visible=false;
            s22.visible=false;
            s23.visible=false;
        }
}

}

instructionPage2

next2.addEventListener(MouseEvent.CLICK, clickNext1);

function clickNext1(event:MouseEvent):void
{
    //moves to 3rd instruction page
    next2.visible=false;
    instruction2.visible=false;
    cursorMove.visible=false;
    instruction3.visible=true;
    next3.visible=true;
    example.visible=true;
}

instructionPage1

next1.addEventListener(MouseEvent.CLICK, clickNext3);

function clickNext3(event:MouseEvent):void
{
    //moves to 2nd instruction page
    next1.visible=false;
    instruction1.visible=false;
    instruction2.visible=true;
    next2.visible=true;
    cursorMove.visible=true;

}

titlePage

spaceCat.visible=false;
instruction1.visible=false;
next1.visible=false;
cursorMove.visible=false;
instruction2.visible=false;
next2.visible=false;
instruction3.visible=false;
next3.visible=false;
example.visible=false;
pause.visible=false;
pause_txt.visible=false;
pauseScreen.visible=false;
playBtn.visible=false;
quit1.visible=false;
tryAgn.visible=false;
failed.visible=false;
quit2.visible=false;
complete.visible=false;
completeStar.visible=false;
healthBar.visible=false;
earth.visible=false;
mission.visible=false;
info.visible=false;
timeStatic.visible=false;
timer.visible=false;
m1.stop();
m2.stop();
m3.stop();
m4.stop();
m5.stop();
s1.visible=false;
s2.visible=false;
s3.visible=false;
s4.visible=false;
s5.visible=false;
s6.visible=false;
s7.visible=false;
s8.visible=false;
s9.visible=false;
s10.visible=false;
s11.visible=false;
s12.visible=false;
s13.visible=false;
s14.visible=false;
s15.visible=false;
s16.visible=false;
s17.visible=false;
s18.visible=false;
s19.visible=false;
s20.visible=false;
s21.visible=false;
s22.visible=false;
s23.visible=false;
//displays title page
startBtn.addEventListener(MouseEvent.CLICK, clickStart);

function clickStart(event:MouseEvent):void
{
    //moves to next instruction page
    title.visible=false;
    titleStars.visible=false;
    startBtn.visible=false;
    instruction1.visible=true;
    next1.visible=true;
    bg.visible=false;
}

How to insert a movie clip from the library in a specific layer using ActionScript 3.0?

I haven't found anything about this and it's really intriguing me. Here's an example:

var example1:example1_mc = new example1_mc();
addChild(example1);

It comes on top of all layers in my scene and I wanted to assign it to the back.

Receiving Type Error 1009, while trying to play a MC

Though I once knew Flash, I haven't kept up with it over the last decade and am now very out of date.

My goal with this is to create a simple animation that is progressed by each keystroke. The words are predetermined so I created them as a text on my stage. I then keyed out a mask to reveal each letter. Each keystroke moves the animation along to a label defined by an array. At the end of the array, at "wrong", I'm trying to have a movie clip play once then stop, the mc is referred to as mc_Shake.

Currently I can't get the mc to play, and receive the error 1009, or if I do it to play I compromises the rest of the animation and it plays through on a loop.

import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.text.TextField;


stop();

var Password:Array = ["Start","a","n","n_2","e","m","u","r","r_2","y", "Wrong"]
var nextLetter:String;
var inc:int = 1;

stage.addEventListener(KeyboardEvent.KEY_DOWN, clickNextSection);
stage.addEventListener(KeyboardEvent.KEY_DOWN, ResetScene);

function clickNextSection(e:KeyboardEvent):void
{
    if (inc <= 9)
    {
        nextLetter = String(Password[inc]);
        gotoAndStop(nextLetter);
        trace("Button Works");
        inc++;

    }
    else
    {
        trace("greater then 12");
        trace("No Works");
        inc++;
    }

}

function ResetScene(e:KeyboardEvent):void
{
    if (inc >= 10)
    {
        mc_Shake.play();
        trace("Button Works");
        inc++;

    }
    else
    {
        trace("Under11");
        trace("No Works");

}

}

Remove duplicate enteries/items from XML in AS3

I'm getting duplicate results from an XML file. I want to delete the excess ones but am having trouble achieving this using splice and indexOf. Can someone point me in the right direction??

var xmlLoader:URLLoader = new URLLoader();
var xmlReq:URLRequest = new URLRequest("data.xml");

xmlLoader.load(xmlReq); 

var background:bkg;  var textvar:TextField = new TextField;         
xmlLoader.addEventListener(Event.COMPLETE, convertdata);

function convertdata(event:Event){  
    var xmlinfo:XML = new XML(event.target.data);   
    //trace(xmlinfo);


    var list:XMLList = xmlinfo.profile.photography;

    var totalimage:Number = list.length();

    trace("length " + totalimage);

    enterbtn.addEventListener(MouseEvent.CLICK, entersite);

    function entersite(event:MouseEvent){
        for (var i:int =0; i<totalimage; i++){
            trace(xmlinfo.profile.photography[i]);

            background = new bkg();
            background.y = i*40;
            background.x =80;
            addChild(background);

            textvar = new TextField();
            textvar.text = list[i];    
            background.addChild(textvar);
        }

    }   
}

XML File

        <profile>
            <first_name>ann</first_name>
            <last_name> lee</last_name>
            <photography>sport</photography>
            <photography>landscape</photography>
            <photography>still life</photography>           
            <image>img1.jpg</image>

        </profile>

        <profile>   
            <first_name>john</first_name>
            <last_name> thomas</last_name>
            <photography>wildlife</photography>
            <photography>landscape</photography>
            <image>img2.jpg</image>
        </profile>

removeChild when object leaves the stage. Code works but gives Error #2025 message

I'm having this weird issue while removing an object once it leaves the stage. The code is functional but it gives the Error #2025 message either once or infinitely. It seems like the code dislikes the term enemy.width within the context of this line of code, but no matter how I rewrite an equation to give the same result, the error message pops up. I'm posting all of the code I believe is relevant to the issue.

var enemyType:Array = [Enemy1, Enemy2, Enemy3, Enemy4, Enemy5];
var enemyTypeRandomNumber:int = Math.random() * (enemyType.length);
var enemy = new enemyType[enemyTypeRandomNumber];

public function checkEveryFrame(event:Event):void
{
    // remove enemy if it leaves the stage
    //if (enemy.x <= enemy.width * -0.5) // Works but spits out error message every frame. Error #2025: The supplied DisplayObject must be a child of the caller.
    //if (enemy.x == enemy.width * -0.5)// Works but gives error only once at the start. Error #2025: The supplied DisplayObject must be a child of the caller.
    if (enemy.x == 0) // works but removes the enemy object when it is only half off the screen.
    {
            removeChild (enemy);
    }
}

Custom Event Listener not working

I am new to as3 and I recently saw creation of custom events in as3 in a tutorial and I wanted to incorporate in my game. When i did the tutorial, it all seemed well for that project. But it doesnt seem to work with the new project.

Here is my code :

package 
{

        import flash.display.MovieClip;
        import flash.utils.Timer;
        import flash.events.TimerEvent;

        public class FashionFrenzy extends MovieClip
        {
                
                public var Buyer_mc:Buyer;
                public var Buyers:Array;
                public var gameTimer:Timer;

                public function FashionFrenzy()
                {
                        
                        GameTimeController();
                        GenerateBuyers();
                        addEventListener(ReachMallDoorEvent.CHECK, OnReachMallDoor);

                }

                
                public function GameTimeController()
                {
                        gameTimer = new Timer( 25 );
                        gameTimer.start();
                }
                public function GenerateBuyers()
                {
                        Buyers = new Array  ;
                        Buyer_mc = new Buyer(533.2,0)  ;
                        addChild(Buyer_mc);
                        gameTimer.addEventListener( TimerEvent.TIMER, BuyerEnter );
                        
                        
                        if(Buyer_mc.y==377.25)
                        {
                                dispatchEvent( new ReachMallDoorEvent( ReachMallDoorEvent.CHECK ) );
                        }
                                        
                        
                        
                }
                
                public function BuyerEnter(event:TimerEvent)
                {

                        Buyer_mc.Enter();
                }
                
                public function OnReachMallDoor(event:ReachMallDoorEvent)
                {
                        
                        trace("my timer starts now");
                }
                
                

        }

}

Here, OnReachMallDoor never seems to run because there is something wrong. I cant see the output saying "My timer starts now". But there is no error in the code and output doesnt show any runtime errors either. Where have I gone wrong? I want OnReachMallDoor function to run when my y coordinate is in desirable position and the event is dispatched.

Flash object cannot not connecting to remote server

My company design digital signage solutions for companies. The animated widgets are typically produced in Flash.

In a current project I'm experiencing a bit of an odd issue. The screen is split into 3 areas: Video, RSS Ticker, and Weather. The RSS and Weather objects are created using Flash. Each object is it's own Flash file.

Both Flash object utilize the same method to connect to the remote servers:

function loadWeatherFromUrl():void
{
    var urlRequest:URLRequest  = new URLRequest("MY URL");

    var urlLoader:URLLoader = new URLLoader();
    urlLoader.addEventListener(Event.COMPLETE, completeHandler);

    try{
        urlLoader.load(urlRequest);
    } catch (error:Error) {
        trace("Cannot load : " + error.message);
    }
}

function completeHandler(event:Event):void {
    var loader:URLLoader = URLLoader(event.target);
    //Do stuff with the data...
}

When testing in the IDE, both the Weather object and the RSS object work fine, as seen below:

Working RSS object

Once deployed to the signage software it doesn't work anymore. However, the Weather object works as expected. The Flash object doesn't encounter a URL loading error either. Compare pic #2 and pic #3 to see how I view errors.

Image of signage application

If I try to preview both the Weather object and the RSS object locally in a web-browser (IE, Firefox), I do get local permission errors, as expected.

Permission error

So any ideas why one would work and the other wouldn't? If it had something to do with CORS (Cross Origin Resource Sharing) wouldn't both fail? I have tried both options (local only / network only) in the Publish -> Playback settings.

The weather object is powered by Yahoo:

Yahoo Weather

and the RSS object is powered by CTV News (Canadian Television Network):

CTV RSS Feed

iOS AIR app not getting user input after closing barcode reader ANE

I have a simple AIR app for iOS which has a text field along with a scan button. On pressing the Scan button the app launches an ANE based on the pdf417.mobi SDK which uses the iPad camera to decode PDF417 barcodes. The ANE works all fine and returns any scans back to AIR.

On closing, it closes the camera and returns back to AIR but I can't interact with the AIR app at all. No touches recognized whatsoever.

I've added an ENTER_FRAME event to trace continuously just so I can check if the app is still alive after closing the ANE and it keeps on tracing. It's just the user input that doesn't work.

Any ideas?

Thanks.

AS3 Append data to local file

I have an AS3 game that will be played on local desktops (not on network) and I need to save the players details after every game. I have tried a few methods (filestream, sharedObject, XML) but so far none have worked. The details to be saved are variables player_name and player_score. I just need these added to an existing file, they don't have to be sorted or filtered.

Is that possible to access the cam and mic of remote user in video chat using actionscript3.?

I am working on actionscript3.
Here i am using the av-chat module for video chat.i add up the recording functionality in it.Now i also want to record the remote user video in it.
Is that possibility in Action script to Access the cam and mic of remote user.??
Thanks in advance.

AS3: How can I stop and loop FLV playback?

I'm trying to make a credits page with a video playing in the background and when the menu button on screen is clicked you will be taken to the main menu and the video will stop. When debugging my app though, the following code cause it to cycle through all 5 scenes at lightspeed, not sure what causes this. I'll show you what code it likes and what code it doesn't.

Bugged code:

stop();

import fl.video.*;
import flash.events.VideoEvent;

Playback.source = "TONIGHT'S THE NIGHT.flv";

Playback.addEventListener(VideoEvent.COMPLETE, FLVDone);
function FLVDone(event:VideoEvent):void{
event.target.stop();
}

//Menu Button
btnMenu.addEventListener(MouseEvent.MOUSE_UP, Menu5Clicked);

function Menu5Clicked (e:MouseEvent){
gotoAndStop(1)
FLVDone()
}

Working Code with no stop feature:

stop();

import fl.video.*;
import flash.events.VideoEvent;

Playback.source = "TONIGHT'S THE NIGHT.flv";

//Menu Button
btnMenu.addEventListener(MouseEvent.MOUSE_UP, Menu5Clicked);

function Menu5Clicked (e:MouseEvent){
gotoAndStop(1)
}

code is not working for rewinding a dynamically added video

i have loaded a flv video dynamically from as3 library.now i want to rewind it..but code is not working. showing "Scene 1, Layer 'Layer 1', Frame 1, Line 64 1119: Access of possibly undefined property playheadTime through a reference with static type flash.media:Video.". here is my code.i could not find the problem..any help would be great..

stage.displayState = StageDisplayState.FULL_SCREEN; 
import flash.media.Video;
 import fl.video.FLVPlayback;
var connection:NetConnection = new NetConnection();
var stream:NetStream;
var Speed:Number;
var SeekPoint:Number;
var Rewind:Boolean ;
var  Forward:Boolean ;
var video:Video = new Video(1130,510);
var metaObj:Object = new Object();

function onMetaData(data:Object):void
{

}

connection.connect(null);
stream = new NetStream(connection);
stream.client = metaObj;
metaObj.onMetaData = onMetaData;
video.attachNetStream(stream);
addChild(video);
stream.play("Sequence 01_1.flv");
video.x = 0;
video.y = 0;
rw.addEventListener(MouseEvent.MOUSE_DOWN,  rw_CLICK);
function rw_CLICK(event:MouseEvent):void 
{

        trace("StartForward Called");
        Speed = Speed +10;
        trace("SeekSpeed: " + Speed);
        SeekPoint = video.playheadTime;
        trace("Initial PlayHead Time: " + SeekPoint);
        video.stop();
        Rewind = false
        Forward= true;
        //video.addEventListener(Event.FRAME_CONSTRUCTED,OnConstructFrame);

    }


function OnConstructFrame(event:Event):void
    {

        if(Forward)
        {
            if(video.playheadTime >= SeekPoint)
            {
                trace("Before Seek Cal.: " + SeekPoint);
                SeekPoint = SeekPoint + Speed;
                trace("After Seek Cal.: " + SeekPoint);
                video.seek(SeekPoint);
               /* if(SeekPoint > ftime)
                {
                    Forward=false;
                  //  video.removeEventListener(Event.FRAME_CONSTRUCTED,OnExitFrame);
                }*/
            }

        }
    }

AS3: repeating function in sigle frame timeline

I'm very new in action script. I have single frame timeline and there is function that moves movie clip verticaly. i want to repeat this only three times. The code works, I'm just not sure if this is the correct way or if it's too complicated.

var pocet:Number = 0;

pruh.addEventListener(Event.ENTER_FRAME, fl_AnimateVertically);

function fl_AnimateVertically(event:Event)
{
if (pruh.y >= stage.stageHeight) {
    pocet++;
}
if (pruh.y < stage.stageHeight) {
pruh.y += 3;
}
else {
    pruh.y = 0 - pruh.y;
}
if (pocet == 3) {
    pruh.removeEventListener(Event.ENTER_FRAME, fl_AnimateVertically);
}
}

thanx

Actionscript 3 : get time to specific timezone (not the computer one)

I have an UTC timestamp and I would like to display the corresponding date and hour in a specific timezone (e.g. France local time) which is not the local timezone of the computer which might be in US. It seems complicated to take into account Daylight saving time.

On Flash/as3 documentation, I only found the Date class which have no function to specify the timezone (only use local time or UTC).

Adobe AIR UDP protocol receive latency

Somebody know a workflow, how can I measure the latency time over UDP protocol.

So I have to measure the time from the sending (iOS/Android) to receive (Desktop).

mardi 28 avril 2015

In actionscript, how to convert a function variable into a string

In actionscript3, i have a function variable that is assigned to one of 100 functions.

During execution, i want to be able print out the name of the function it assigned to. Unfortunately if you say trace (f) where f is function variable, it merely reports the parameter types and return value type of the function, doesn't mention its name, even if the function is static. Anyone know a trick to get the string representation of the function variable? Too bad Adobe didn't think of this issue, it is a helpful thing when debugging.

Most efficient way to look for files in a directory tree that match a regular expression

I am writing a little app that will enable users to specify a regular expression that will specify what files to copy to a location. The expression might look something like this:

\w\:\/rootFolderOne\/subFolderTwo/\w+/fileName\d+.mpg

So my question is how do I efficiently find all files on a drive that match this pattern?

I have to load the contents of each folder one by one. I could just traverse the directory tree and load every folder in the whole file system and then compare each file's entire path with the regular expression. This would be very wasteful as loading the contents of rootFolderTwo or even subFolderThree would not provide any valid results.

At the root level how do I know to load rootFolderOne but not rootFolderTwo?

Creating variables in a systematical way using loops in AS3?

Is there? Like Let's say I need 5 variables in ActionScript 3.0 and would like to name them as follows:

var myVar_1 = "things";
var myVar_2 = "things";
var myVar_3 = "things";
var myVar_4 = "things";
var myVar_5 = "things";

But instead of having to type them 1 by 1, would it work in a loop? I can't seem to make it work and would really love some help/advice on this matter.

AS3: How can I check a variable with an if statement?

So this bit of code seems like it should run smoothly to me but i can't seem to be able to use an if statement to check the score then make the button appear. Any suggestions?

//Score variable
var score = 0;

//Multiplier variable
var multiplier = 1;

//Point Scorer
function PointScore() {
score = score + multiplier;
}

//update score function
function updateScore() {
txtPlayerScore.text = "Smash Points: " + score;
}

//Score Text
txtPlayerScore.text = "Smash Points: " + score;

//Make Power Up button invis
btnPowerUp.visible = false;

//If the score is 50 the button is now visible
if (score == 50){
btnPowerUp.visible = true;
}

//Power Up button
btnPowerUp.addEventListener(MouseEvent.MOUSE_DOWN, UpClicked);

function UpClicked (e:MouseEvent){
multiplier = 5;
}

Change symbol of Mute button spark component

How can I change the symbol of mute button using Mxml skin file. This is what I have right now. I can change the color and everything how can I change the icon. There is no reference of Icon or anything.

<!-- host component -->
<fx:Metadata>
    /** 
     * @copy spark.skins.spark.ApplicationSkin#hostComponent
     */
    [HostComponent("spark.components.mediaClasses.MuteButton")]
</fx:Metadata>

<fx:Script fb:purpose="styling">
    <![CDATA[
        /* Define the skin elements that should not be colorized. */
        static private const exclusions:Array = ["volumeSymbol"];

        /**
         * @private
         */
        override public function get colorizeExclusions():Array {return exclusions;}

        /* Define the symbol fill items that should be colored by the "symbolColor" style. */
        static private const symbols:Array = ["trapezoid1", "trapezoid2", "bar1_1", "bar1_2", 
                                              "bar1_3", "bar2_1", "bar2_2", "bar2_3", "bar3_1", 
                                              "bar3_2", "bar3_3", "bar4_1", "bar4_2", "bar4_3"];

        /**
         * @private
         */
        override public function get symbolItems():Array {return symbols};

        /**
         * @private
         */
        override protected function initializationComplete():void
        {
            useChromeColor = true;
            super.initializationComplete();
        }
    ]]>
</fx:Script>

<fx:Script>
    <![CDATA[
        import mx.events.FlexEvent;
        import spark.components.mediaClasses.VolumeBar;

        private function init():void
        {
            // this is essentially just binding code.  Anytime the volume changes, 
            // let us know.
            volume = hostComponent.muted ? 0 : hostComponent.volume;
            hostComponent.addEventListener(FlexEvent.VALUE_COMMIT, valueCommitHandler);
            hostComponent.addEventListener(FlexEvent.MUTED_CHANGE, valueCommitHandler);
        }

        private function valueCommitHandler(event:Event):void
        {
            volume = hostComponent.muted ? 0 : hostComponent.volume;
        }

        private var _volume:Number = 1;

        /**
        *  The volume of the video player, specified as a value between 0 and 1.
        */
        public function get volume():Number
        {
            return _volume;
        }

        public function set volume(value:Number):void
        {
            if (value == _volume)
                return;

            _volume = value;

            var bar1:Array = [bar1_1, bar1_2, bar1_3]; // 0-.25
            var bar2:Array = [bar2_1, bar2_2, bar2_3]; // .25-.5
            var bar3:Array = [bar3_1, bar3_2, bar3_3]; // .5-.75
            var bar4:Array = [bar4_1, bar4_2, bar4_3]; // .75-.1
            var bars:Array = [bar1, bar2, bar3, bar4];

            var curValue:Number = 0;
            for (var i:int = 0; i < bars.length; i++)
            {
                if (value <= curValue)
                    setAlphaTo(bars[i], 0);
                else if (value >= (curValue + 0.25))
                    setAlphaTo(bars[i], 1);
                else
                    setAlphaTo(bars[i], (value-curValue)*4);

                curValue += 0.25;
            }
        }

        private function setAlphaTo(bar:Array, alpha:Number):void
        {
            for (var i:int = 0; i < bar.length; i++)
            {
                bar[i].alpha = alpha;
            }
        }
    ]]>
</fx:Script>


<!-- states -->
<s:states>
    <s:State name="up" />
    <s:State name="over"/>
    <s:State name="down" />
    <s:State name="disabled" />
</s:states>

<!-- layer 1: fill -->
<s:Rect left="1" right="1" top="1" bottom="1">
    <s:fill>
        <s:LinearGradient rotation="90">
            <s:GradientEntry color="0xFFFFFF"
                             color.over="0xCACACA"
                             color.down="0xA8A8A8" />
            <s:GradientEntry color="0xDCDCDC"
                             color.over="0x8D8D8D" 
                             color.down="0x6B6B6B"/>
        </s:LinearGradient>
    </s:fill>
</s:Rect>

<!-- layer 2: One pixel stroke inside border (exclude in down) -->
<s:Rect left="1" right="1" top="1" bottom="1" excludeFrom="down">
    <s:stroke>
        <s:LinearGradientStroke weight="1" rotation="90">
            <s:GradientEntry color="0xFEFEFE" alpha.over="0.22" />
            <s:GradientEntry color="0xEAEAEA" alpha.over="0.22" />
        </s:LinearGradientStroke>
    </s:stroke>
</s:Rect>

<!-- layer 3: fill highlight  (exclude in down) -->
<s:Rect left="1" right="1" top="1" height="11" excludeFrom="down">
    <s:fill>
        <s:SolidColor color="0xFFFFFF" 
                    alpha="0.3" 
                    alpha.over="0.12" />
    </s:fill>
</s:Rect>

<!-- layer 4: downstate inset border  (include only in down) -->
<s:Rect left="1" top="1" right="1" height="1" includeIn="down">
    <s:fill>
        <s:SolidColor color="0x000000" alpha="0.4" />
    </s:fill>
</s:Rect>
<s:Rect left="1" top="2" right="1" height="1" includeIn="down">
    <s:fill>
        <s:SolidColor color="0x000000" alpha="0.12" />
    </s:fill>
</s:Rect>
<s:Rect left="1" top="1" bottom="1" width="1" includeIn="down">
    <s:fill>
        <s:SolidColor color="0x000000" alpha="0.12" />
    </s:fill>
</s:Rect>
<s:Rect right="1" top="1" bottom="1" width="1" includeIn="down">
    <s:fill>
        <s:SolidColor color="0x000000" alpha="0.12" />
    </s:fill>
</s:Rect>

<!-- layer 5: border - put on top of the fill so it doesn't disappear when scale is less than 1 -->
<s:Rect left="0" right="0" top="0" bottom="0" width="38" height="24">
    <s:stroke>
        <s:SolidColorStroke color="0x131313" />
    </s:stroke>
</s:Rect>

<!--- Defines the volume symbol. -->
<s:Group horizontalCenter="0" verticalCenter="0" id="volumeSymbol">

    <!-- big trapezoid in center -->
    <s:Path winding="evenOdd" data="M 9 13 L 9 0 L 4 4 L 4 9 L 9 13 Z">
        <s:fill>
            <!--- @private -->
            <s:SolidColor color="0x212121" alpha=".85" id="trapezoid1"/>
        </s:fill>
    </s:Path>

    <!-- small trapezoid on left -->
    <s:Path winding="evenOdd" data="M 3 9 L 3 4 L 0 5 L 0 8 L 3 9 Z">
        <s:fill>
            <!--- @private -->
            <s:SolidColor color="0x212121" alpha=".75" id="trapezoid2"/>
        </s:fill>
    </s:Path>

    <!-- volume bars -->

    <!-- big volume bar representing volume values [.75, 1] -->
    <s:Line yFrom="0" yTo="12" x="16">
        <s:stroke>
            <s:LinearGradientStroke rotation="90">
                <!--- @private -->
                <s:GradientEntry color="0x272727" ratio=".1" id="bar4_1" />
                <!--- @private -->
                <s:GradientEntry color="0x3D3D3D" ratio=".2" id="bar4_2" />
                <!--- @private -->
                <s:GradientEntry color="0x484848" ratio=".3" id="bar4_3" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Line>

    <!-- middle volume bar representing volume values [.5, .75] -->
    <s:Line yFrom="2" yTo="10" x="14">
        <s:stroke>
            <s:LinearGradientStroke rotation="90">
                <!--- @private -->
                <s:GradientEntry color="0x272727" ratio=".1" id="bar3_1" />
                <!--- @private -->
                <s:GradientEntry color="0x3D3D3D" ratio=".2" id="bar3_2" />
                <!--- @private -->
                <s:GradientEntry color="0x484848" ratio=".3" id="bar3_3" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Line>

    <!-- middle volume bar representing volume values [.25, .5] -->
    <s:Line yFrom="3" yTo="9" x="12">
        <s:stroke>
            <s:LinearGradientStroke rotation="90">
                <!--- @private -->
                <s:GradientEntry color="0x272727" ratio=".1" id="bar2_1" />
                <!--- @private -->
                <s:GradientEntry color="0x3D3D3D" ratio=".2" id="bar2_2" />
                <!--- @private -->
                <s:GradientEntry color="0x484848" ratio=".3" id="bar2_3" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Line>

    <!-- small volume bar representing volume values [0, .25] -->
    <s:Line yFrom="5" yTo="7" x="10">
        <s:stroke>
            <s:LinearGradientStroke rotation="90">
                <!--- @private -->
                <s:GradientEntry color="0x272727" ratio=".1" id="bar1_1" />
                <!--- @private -->
                <s:GradientEntry color="0x3D3D3D" ratio=".2" id="bar1_2" />
                <!--- @private -->
                <s:GradientEntry color="0x484848" ratio=".3" id="bar1_3" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Line>
</s:Group>

manipulate xml data actionscript

Ok. so i have imported my data from the XML file and used a movie clip to add a bkg to the text. I want to create a button instead of this bkg but am having trouble with the addChild event(seeing as its static as far as i can make out).

How can I bring in the data into a button where i can then click and it will load load the name field of the data from the XML file.

Is this a good way to access the data from the XML file or is there a better way that i should look into. I have tried looking for a solution but have not been unsuccessful so apologies if this has been asked before. As you may guess my AS skills are pretty sketchy

function convertdata(event:Event){

var xmlinfo:XML = new XML(event.target.data); 


var list:XMLList = xmlinfo.profile.photography;

var totalimage:Number = list.length();
trace("length" + totalimage);

for (var i:int =0; i<totalimage; i++){
    trace(xmlinfo.profile.photography[i]);


    //bkg.addEventListener(MouseEvent.CLICK,gotodata);
    this["textf" + i] = new TextField();
    this["bkg" + i] = new bkg();
    addChild(this["bkg" + i]);
    this["bkg" + i].y = i*40;
    this["bkg" + i].x = 20;

    this["textf" + i].text = list[i];

    this["bkg" + i].addChild(this["textf" + i]);
    }

}

the XML FILE

<profile>   

        <name>ann lee</name>
        <photography>sport</photography>
        <photography>landscape</photography>
        <photography>still life</photography>           
        <image>img1.jpg</image>


<profile>   
        <name>john</name>
        <photography>wildlife</photography>
        <photography>landscape</photography>
        <image>img2.jpg</image>

How can I use ByteArray to access a graph tree of 1 million leaves?

I have a dictionary of words and I want to make a search algorithm to determine if a given string (with length at least 3, maximum 10) exists in the dictionary.

What I thought to do was a tree where each level is a consecutive letter from the tested word. If I try to get a child for the next letter and there is none, then the word does not exist.

For example, for the word "weed", the root is w, is there a child "e" ? Yes? Does that have a child "e" ? Yes? Does THAT have a child "d" ? No? Word does not exist. Yes? Word exists.

The problem is the sheer size of the dictionary. It takes so much time to build that immense tree from a text file that my application freezes and it takes too many seconds (around 8, depends on the pc) and might trigger browsers with "swf stopped responding, stop it?"

What I want is to pre-build the tree in AIR then save it as binary. The last step is to extract the prebuilt tree, somehow. Not using readObject because that builds the giant tree with new I somehow want to cast the bytearrary as Object and access that from memory, but I have no clue how to start doing this.

I need help on creating "unlockable" levels in flash (AS3)

Allright,

First of all, i am a graphic game design student but unfortunately have to do the programming also on an assignment for my internship. The game which i am making is in flash (and thus it's coding in AS3). I'm creating a search-and-find game and previously i managed to get a similair game working which consisted of 1 level. Now i have to create one with multiple levels which can be unlocked by finishing the previous ones.

so my question is: is there a way for me to simply make a level layout with levels which unlock after having cleared the previous one (like angry birds has for example) and without much complex coding? (since when i hear words like array, int variable, class etc my head already starts spinning and i easly get lost.)

kill setTimeOut in removed swf

I import a swf file into main swf, when I click on next button to remove it and load a new swf file still there are sounds playing from previous swf when a new swf loaded into main swf. SoundMixer.stopAll(); doesn't work out. System.gc(); also dosnt work. main cause is that I use setTimeOut to play sound. Even I remove swf, settimeout works after estimated time. Any suggestion will be appriciated.

How to access a frame inside a movieclip from within another movieclip

I have a problem regarding movieclips...

On my main timeline there are 2 MCs and inside MC1 there is a button, which - when clicked - should get me to Frame 10 of MC2 (on the main timeline)...

My button code (inside mc1):

btn_standard.addEventListener(MouseEvent.CLICK, standard_click);

function standard_click(myNextEvent:MouseEvent):void { 
    MovieClip(root).mc2.gotoAndPlay(10);
} 

There is no error, but however the button won't work... Can anyone please help me! :-(

Range request byte units are equal in flowplayer actionscript

Range request byte units are equal when i'am trying to seek in flowplayer,thats why in response content length iz 1 .

Remote Address:89.218.14.80:80 Request URL:http://ift.tt/1GAXXHq Request Method:GET Status Code:206 Partial Content Request Headersview source Accept:/ Accept-Encoding:gzip,deflate,sdch Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Cookie:_ga=GA1.2.590404840.1430127637; _gat=1; __utmt=1; __utma=29888440.590404840.1430127637.1430210839.1430214610.3; __utmb=29888440.1.10.1430214610; __utmc=29888440; __utmz=29888440.1430127637.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _ym_visorc_24318361=w; csrftoken=IFA2XL7hxPpiCP67DplixeBfRGlbgDwG Host:vasabi.tv If-Range:Mon, 26 Jan 2015 00:31:44 GMT Range:bytes=7976008-7976008 User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36 Response Headersview source Cache-Control:max-age=1209600 Connection:keep-alive Content-Length:1 Content-Range:bytes 7976008-7976008/557865749 Content-Type:video/mp4 Date:Tue, 28 Apr 2015 09:56:38 GMT Expires:Tue, 12 May 2015 09:56:38 GMT Last-Modified:Mon, 26 Jan 2015 00:31:44 GMT Last-Modified:: 1430214998 Server:nginx

Add a button to save the picture in AIR or AS3

I have a file attachment here:

http://ift.tt/1b96Qwj

I tried I try to add a button for interface to download the image in the phone folder in AIR or AS3 Or make a photo wallPaper for phon. Can anyone help me?? And experience it in the attached file .

enter image description here

How to read data from Id3 tag string using ActionScript?

I want to read ID3 data in as3 using ID3 tag specification, i do not have any idea of how frames are divided, but after reading ID3 specification and background work i wrote the following code which gives me the following output.

The following string, i get at client side. Basically it is injected id3 tag data which has timed metadata.

var id3Data:String = "4944330400000000001d5449543200000013000003312e34323932373430323738353545313200"
var byteArray:ByteArray = Hex.toArray(id3Data);
trace(byteArray.readMultiByte(3, "iso-8859-1"));
trace(byteArray.readMultiByte(3, "iso-8859-1"));
trace(byteArray.readMultiByte(6, "iso-8859-1"));
trace(byteArray.readMultiByte(6, "iso-8859-1"));
trace(byteArray.readMultiByte(18, "iso-8859-1"));

It prints "ID3       TIT2       1.429274027855E12";

Sometimes i get End Of File Exception , How to read data exactly from id3 string.How to get how many bytes of data to read from header so that i do not get EOF exception, Finally "1.429274027855E12" is time in UTC which i needed.