lundi 29 février 2016

AS3: a non systematic XML loading bug

As said in my title, I have a XML loading problem. In my code, I load some XML files for showing the texts included in these XML files. But these texts aren't displayed in the Flash online software.

The language changes with the user choice. It's for every text in the software. When you begin to use the software, after a location files loading and a data conversion for a new format in the database, you arrive on a main menu, not included in the previous version. There are several problems with this bug :

  1. It's a non systematic bug. When I deploy application six times, I would have this problem around only once. I must do deployments for one hour for seeing the bug again. The bug seems to arrive only in an "old version → new version" deployment, too.
  2. In the software, the bug goes away by itself after from five to ten minutes. You can change language. Before the ten minutes, the concerned texts will be empty only in the default language. After the ten minutes, there isn't the bug anymore.
  3. The concerned texts are in new XML tags, not included in the previous version.

Because this is a non systematic bug, it's very laborious to debug this problem (new informations after one hour full of deployments…). Among others, I try to force software to load texts again before the main menu display. Without success…

Unfortunately, I can't send my code, because I haven't my code with me now. I will be able to realize my tests in some hours.

Unload as2 swf nested inside an as3 container

What I'm trying is unload an as2's swf from and as3's swf containner. So It's running okay when loading the as2 swf from an as3 swf cointainner's button as you can see in the next code:

//AS3 cointainner "AS3Loader_TEST1":

var loader:Loader = new Loader();
loader.load(new URLRequest("AS2animation_TEST1.swf"));
addChild(loader);

// and for solving the pitfall, I tryed this:

var AVM_lc:LocalConnection = new LocalConnection(); 

loader.addEventListener(MouseEvent.CLICK, stopandback);
function stopandback(event:MouseEvent):void {
 AVM_lc.send("AVM2toAVM1", "disappear");

}

//then, into the "AS2animation_TEST1.swf" it's written

var AVM_lc:LocalConnection = new LocalConnection();
AVM_lc.dissapear = function(){
animation_mc.unloadMovie();

}

AVM_lc.connect("AVM2toAVM1");

So, the last script unload a movieclip nested in AS2animation_TEST1.swf at addEventListener dispatched from a mouse click into the as3 containner but that's not the way I'm looking for. So, What do you figure out to unload the whole AS2animation_TEST1.swf

loading image from xml issue as3

I have created a Flash CC Professional file that loads XML data that includes links, multiple text sections and an image link. as users progress though the program and text, the corresponding image should load into a mc named imgholder. I have traced the var 'img' from the xml file to the incremental image loader but still can't figure out why the image isn't loading into the container. ...oh and it isn't throwing any errors.

HELP!! thanks in advance!

Frame 1 AS3:

    var questions:Array=new Array();
var answers:Array=new Array();
var numb:Array=new Array();
var rtext:Array=new Array();
var img:Array = new Array();



//XML loader
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, loadXML);
loader.load(new URLRequest("UT_quiz.xml"));
function loadXML(e:Event):void
{
        var myxml = new XML(e.target.data);
        var loop =myxml.ques.length();
                for (var i=0;i<loop;i++){
                    questions[i]=myxml.ques[i].q1;
                    numb[i]=myxml.ques[i].qnum;
                    answers[i]=[myxml.ques[i].op1,myxml.ques[i].op2,myxml.ques[i].op3,myxml.ques[i].op4];
                    rtext[i]=myxml.ques[i].riddle;
                    img[i]=myxml.ques[i].image;


                }//loop
                gotoAndPlay(2);

}
stop();

Frame 2 AS3:

import flash.text.TextField;
import flash.utils.getTimer;
import flash.events.Event;

var qno=0; var rnd1;

function change_question(){
                tick.visible=false;cross.visible=false;
                rnd1=Math.ceil(Math.random()*4);
                q.text=questions[qno];
                qnum.text=numb[qno];
                rtxt.text=rtext[qno];
                imgholder.MovieClip=img[qno];
                if(rnd1==1){opt1.text=answers[qno][0];opt2.text=answers[qno][1];opt3.text=answers[qno][2];opt4.text=answers[qno][3];}
                if(rnd1==2){opt1.text=answers[qno][3];opt2.text=answers[qno][0];opt3.text=answers[qno][1];opt4.text=answers[qno][2];}
                if(rnd1==3){opt1.text=answers[qno][2];opt2.text=answers[qno][3];opt3.text=answers[qno][0];opt4.text=answers[qno][1];} 
                if(rnd1==4){opt1.text=answers[qno][1];opt2.text=answers[qno][2];opt3.text=answers[qno][3];opt4.text=answers[qno][0];}
                }//function change_question

function enable_disable(a){
    if(a==0){shade1.mouseEnabled=false;shade2.mouseEnabled=false;shade3.mouseEnabled=false;shade4.mouseEnabled=false;}
    if(a==1){shade1.mouseEnabled=true;shade2.mouseEnabled=true;shade3.mouseEnabled=true;shade4.mouseEnabled=true;}} 

change_question();


next_b.addEventListener(MouseEvent.CLICK, ButtonAction1);
function ButtonAction1(eventObject:MouseEvent) {

        qno++;change_question();

if(MovieClip(root).currentGalleryItem == 4){
            MovieClip(root).currentGalleryItem--;
            MovieClip(root).slideRight();
        }   
    }

shade1.addEventListener(MouseEvent.CLICK, ButtonAction2);
shade2.addEventListener(MouseEvent.CLICK, ButtonAction3);
shade3.addEventListener(MouseEvent.CLICK, ButtonAction4);
shade4.addEventListener(MouseEvent.CLICK, ButtonAction5);

function ButtonAction2(eventObject:MouseEvent) {if(rnd1==1){tick.visible=true;tick.y=shade1.y;tick.x=shade1.x; score+=50; scorecounter.text = score.toString();}else{cross.visible=true;cross.y=shade1.y;cross.x=shade1.x; score-=25; scorecounter.text = score.toString();}}
function ButtonAction3(eventObject:MouseEvent) {if(rnd1==2){tick.visible=true;tick.y=shade2.y;tick.x=shade2.x; score+=50; scorecounter.text = score.toString();}else{cross.visible=true;cross.y=shade2.y;cross.x=shade2.x; score-=25; scorecounter.text = score.toString();}}
function ButtonAction4(eventObject:MouseEvent) {if(rnd1==3){tick.visible=true;tick.y=shade3.y;tick.x=shade3.x; score+=50; scorecounter.text = score.toString();}else{cross.visible=true;cross.y=shade3.y;cross.x=shade3.x; score-=25; scorecounter.text = score.toString();}}
function ButtonAction5(eventObject:MouseEvent) {if(rnd1==4){tick.visible=true;tick.y=shade4.y;tick.x=shade4.x; score+=50; scorecounter.text = score.toString();}else{cross.visible=true;cross.y=shade4.y;cross.x=shade4.x; score-=25; scorecounter.text = score.toString();}}



var score:Number = 0;

function init():void {
    if (score < 0) {
        score == 0;
    }
    scorecounter.text = score.toString();
}


/*var gameStartTime:uint;
var gameTime:uint;

function currTime(e:Event) {
    gameStartTime = getTimer();
    gameTime = 0;
}

addEventListener(event.ENTER_FRAME,showTime);

function showTime(e:Event) {
    gameTime = getTimer()-gameStartTime;
    gameTimeField.text = "Time: "+gameTime;
}*/

init();

stop();

Dynamic Text of a Movie Clip is not updating

I have a stage set up with a "movie clip" in the frame named jackpotNote. In that movie clip (or symbol), there is a dynamic text field named "jackpotAmt".

What is supposed to happen is that I'm to press the Space Bar on my keyboard and it will trigger the Movie Clip to play out. What's also supposed to happen is that the text is supposed to change as well, here is the current coding:

        if (event.keyCode == Keyboard.SPACE) {

            if (jackpotNote.visible == true) {
                trace("Jackpot amount already shown. Ignored.");
            } else {
                jackpotNote.visible = true;
                jackpotSymbol.visible = true;

                //jackpotSymbol.jackpotAmt.text =  currency_str + String(jackpotamt_int);
                if (jackpotamt_int < 100000) jackpotSymbol.jackpotAmt.text = currency_str + String(jackpotamt_int);
                else if (jackpotamt_int >= 100000 && jackpotamt_int <= 999999) jackpotSymbol.jackpotAmt.text = String(jackpotamt_int);
                else jackpotSymbol.jackpotAmt.text = currency_str + "1MIL+";

                dingsound.play();
                jackpotSymbol.play(); // DO NOT START PLAYING 
                jackpotSymbol.gotoAndPlay(1);

                trace("Jackpot amount shown.");

            }


        }

However when I trigger this event, the following happens:

  • The sound effect jackpotSymbol.play() plays as normal.
  • The jackpotSymbol becomes visible.
  • However, the text is not changed in the following line: jackpotSymbol.jackpotAmt.text = currency_str + String(jackpotamt_int);

This used to run well on Adobe Flash Professional CS6, however when I upgrade to Adobe Animate CC... it broke. (I had to remove all of the TLF fields and make them dynamic again.)

What is missing to make all of this work?

Convert ActionScript 2.0 code to ActionScript 3.0

please help me to convert code to ActionScript 3.0

this is code :

    //***********************************************************
    var theXML:XML = new XML();
    theXML.ignoreWhite = true;
    theXML.onLoad = function() {
    var nodes = this.firstChild.childNodes;
    for (i=0;i<nodes.length;i++){
    theList.addItem(nodes[i].firstChild.nodeValue,i);
    }
    }

    theXML.load("http://localhost/conn.php");
    //***********************************************************

and thank you

Displaying movieclips from an array in sequential order

Here is what I am trying to do:

  1. Establish an array of movie clips in the library
  2. Randomize the order within the array
  3. On enter frame, display the first movie clip in the randomized array
  4. When a "next" button is clicked, the existing clip with unload and the next move clip in the array order will load
  5. Once the last movie clip in the array has been displayed and the "next" button has been clicked, the first movie clip in the array will load.
  6. this will repeat over and over if the user keeps clicking the "next" button.

Here is the code that I have so far that establishes the random array:

var animalArray:Array = ["animal1","animal2","animal3","animal4","animal5","animal6","animal7",]; 
var animalIndex:int = -1; 

function getNextanimal():String {
    if(animalIndex == -1) animalIndex = Math.round(Math.random() * (animalArray.length - 1)); 

    animalIndex++; //increment it
    if(animalIndex >= animalArray.length) animalIndex = 0; 

    return animalArray[animalIndex];
}

this is the code for my button:

button.addEventListener(MouseEvent.CLICK, clickCard);
function clickCard(event: MouseEvent): void {

    var animalCard: String = getNextanimal();
    addChild(animalCard);

}

I only get errors when clicking the button. Any suggestions?

remove allchild form class in by coding in the class

Ok, so I've been stuck on this for about three hours now and I finally feel like asking for help. i have 2 classes ( Rcircle and Rrect with x = -20 and they go down ) and 2 MovieClip on stage ( Rcar , Bcar ) . on main timeline , i add Children from 2 classes , when any children hit to object or MovieClip ( Rcar , Bcar ) the problem happen here .. when it go to nextFrame to show game over the child of 2 classes than added to stage after just game over still go down in mainframe

addEventListener(Event.ENTER_FRAME,rundm);
function rundm(e:Event)
{
    recttimer.start();

    if (Rcircle.score ==250)
    {
        recttimer.stop();
        removeEventListener(Event.ENTER_FRAME,rundm);
        gotoAndStop(4);
        while (mycircle.numChildren > 0) 
        {
        mycircle.removeChildAt(0);
        }
        while (myrect.numChildren > 0) 
        {
        myrect.removeChildAt(0);
        }
    }
    rectcount = Math.random()*2+1;
    scoree.text = String(Rcircle.score);
}

in class

function rectmove (e:Event)
            {

                var mysoundChannelPosition:Number = 0; 

                if(hitTestObject(Rcar))
                {
                    if (hit)
                    {
                        mychannel=mysound.play()
                        gotoAndPlay(3);
                        this.visible = false;
                        this.y = -3000;
                        hit=false;
                        MovieClip(parent).gotoAndPlay(3);
                        removeEventListener(Event.ENTER_FRAME,rectmove);
                    }
                }
                else if (hitTestObject(Bcar))
                {
                    if (hit)
                    {
                        mychannel=mysound.play()
                        gotoAndPlay(3);
                        this.visible = false;
                        this.y = -3000;
                        hit=false
                        MovieClip(parent).gotoAndPlay(3);
                        removeEventListener(Event.ENTER_FRAME,rectmove)
                        //mychannel.stop()
                    }
                }

so i hope to help me

How to get image if I drag and drop an Image from Google Chrome or Internet Explorer in AS3

I am trying to drag an Image from Google Chrome or Internet Explorer and Drop into my Flex Project but I am unable to get Image directly from temp folder like Mozilla Firefox,

For Example I am using the following codes go get drag drop images from system temp folder in case of Mozilla Firefox:

this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, onNativeDragDrop);

private function onNativeDragDrop(vEvent:NativeDragEvent)
{
    var dropFiles:Array = vEvent.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;

    if(dropFiles && dropFiles.length > 0)
    {
        var original:File = File(dropFiles[0]);
        var nativePath:String = original.nativePath;
    }
}

In nativePath i am getting the path where the image is initially stored like : "C:\Users\User_Name\AppData\Local\Temp\ubeh2wbl.bmp"

But In case of Google Chrome or Internet Explorer I am getting NULL in nativePath.

So I Don't know where Google Chrome or Internet Explorer initially storing the images.

Does anyone have an idea where it is storing or how to solve this problem ?

Remove movieClips using array list?

I've a array of list and created image place holder with the array objects name (Example: myArray[a,b]) and loaded images from there, having array list as folder name. And finally created a movieClip to load on them and display in stage.

Now I want to remove them calling the same array list.

Need help here...

My code below:

for (var l: int = 0; l < ListArray.length; l++) {

    var BookName: MovieClip = new bookThumb();

    trace("\n[" + l + "]: " + ListArray[l]);
    ImageFoldername = ListArray[l];
    var bookImagePath: String = "file://" + File.userDirectory.nativePath.toString() + "/Books/" + ImageFoldername + "/Images/Icon.png";
    trace(bookImagePath);

    var ImagePlacer: Loader = new Loader;
    var ImageURL: URLRequest = new URLRequest(bookImagePath);

    ImagePlacer.load(ImageURL);


    BookName.addChild(ImagePlacer);
    BookName.name = ImageFoldername

    addChild(BookName)

    BookName.x = FirstBook_x;
    BookName.y = FirstBook_y;
    BookName.buttonMode = true;
    BookName.mouseChildren = false;
    BookName.addEventListener(MouseEvent.CLICK, IconSelected);
    BookName.alpha = .8
    BookName.addEventListener(MouseEvent.MOUSE_OVER, IconMouseOver);
    BookName.addEventListener(MouseEvent.MOUSE_OUT, IconMouseOut);

    FirstBook_x = FirstBook_x + 250;

}

Implicit coercion of a value of type Vector.

I've got line of code

var enemies:Vector.<Unit>    = _map.getEnemiesForFraction(_fraction);

where _map.getEnemiesForFraction(_fraction) is

public function getEnemiesForFraction(fraction:String):Vector.<Unit>
{
    return _enemiesByFraction[fraction];
}

It compiles and works fine, but FlashBuilder keep annoying me with error

Implicit coercion of a value of type Vector.<Unit> to an unrelated type Vector.<Unit>.

Why? How to get rid of this? Neither restart nor clean, doesn't work.

Play a youtube video inside an AIR app (AS3)

I'd like to know if it's possible to play a youtube video inside an AIR app using AS3 code.

It seems that youtube API is deprecated...

If anybody knows a way or a good tutorial.

Thx

dimanche 28 février 2016

load and remove swf

i have a problem in my app i set many buttons in the main swf each button load different swf the problem happens when i load a swf that contain sound even i remove it to load another one the sound still play in the background i can't find a way to remove the swf with its sound

if(e.target.name=="gamepage")
    {
        removeChildAt(0)
        mycontent.addChild(myLoader);
        myLoader.load(new URLRequest("game.swf"));
        nextpage.visible=false
        prevpage.visible=false;
        nextbtn.visible=false;
        prevbtn.visible=false;
        Tweener.addTween(mycontent, {rotation:360, time:5});
        i=0;
        }

i also used the unloadandstop but it didn't work

Loader(mycontent.getChildByName("myloader")).unloadAndStop();
        mycontent.removeChild(mycontent.getChildByName("myloader"));

AS3 Error 2025 When Game Restart

I'm trying to remove objects when game is over by using the removeChild function. But I got error 2025 and the debugger freeze when I restart the game. Any help is greatly appreciated!

import control.Joystick;
import objects.PauseButton;

public class Engine extends MovieClip {

    public function Engine() {

    private var numStars: int = 80;
    public static var enemyList: Array = new Array();
    private var ourShip: Ship;
    private var joystick: Joystick;
    private var scoreHUD: ScoreHUD;
    public var pausebutton: PauseButton;

    public function GameStart(evt: Event): void {

        ourShip = new Ship(stage);
        ourShip.x = stage.stageWidth / 2;
        ourShip.y = stage.stageHeight / 2;
        ourShip.addEventListener("hit", shipHit, false, 0, true);
        stage.addChild(ourShip);

        joystick = new Joystick(300, 70, ourShip);
        stage.addChild(joystick);

        scoreHUD = new ScoreHUD(stage);
        stage.addChild(scoreHUD);

        pausebutton = new PauseButton(stage);
        stage.addChild(pausebutton);

        for (var i: int = 0; i < numStars; i++) {
            stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip));
        }

        addEventListener(Event.ENTER_FRAME, loop, false, 0, true);

        function loop(e: Event): void {

            if (Math.floor(Math.random() * 20) == 5) {
                var enemy: Stinger = new Stinger(stage, ourShip);
                enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
                enemy.addEventListener("killed", enemyKilled, false, 0, true);
                enemyList.push(enemy);
                stage.addChild(enemy);
            }

            else if (Math.floor(Math.random() * 80) == 5) {
                var enemy2: Stinger2 = new Stinger2(stage, ourShip);
                enemy2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
                enemy2.addEventListener("killed", enemyKilled, false, 0, true);
                enemyList.push(enemy2);
                stage.addChild(enemy2);
            }
        }

        function enemyKilled(e: Event) {
            scoreHUD.updateKills(1);
            scoreHUD.updateScore(e.currentTarget.points);
        }

        function removeEnemy(e: Event) {
            enemyList.splice(enemyList.indexOf(e.currentTarget), 1);
        }

        function shipHit(e: Event) {
            scoreHUD.updateShields(-1);
        }

        stage.addEventListener("gameOVER", GameOver);
        function GameOver(e: Event) {
            new GameOverMenu(stage).load();
            removeEventListener(Event.ENTER_FRAME, loop);
            stage.removeChild(ourShip);
            stage.removeChild(joystick);
            stage.removeChild(scoreHUD);
            stage.removeChild(pausebutton);
        }

    }

}

I also tried to change the removeChild to the script below but still no luck.

if(ourShip.parent) {
    ourShip.parent.removeChild(ourShip);
}

createjs hitTest works just on moving without hitting the object

when i touch the circle to the rect then alpha should be 0.1 but unfortunately alpha becomes 0.1 once i move circle . perhaps its happening for upF(e) . but i tried to keeping bold code inside all function and even outside the scope . but nothing worked.i have uploaded here http://ift.tt/21AWtqS

/* js 

var t1 = this;
t1.circle.addEventListener('mousedown', downF)
function downF(e) {
stage.addEventListener('stagemousemove', moveF);
stage.addEventListener('stagemouseup', upF);
};

function upF(e) {

    var pt = t1.globalToLocal(stage.mouseX, stage.mouseY);
if (t2.hitTest(pt.x, pt.y)) {
  t1.alpha=0.1;
}
  stage.removeAllEventListeners();
}
function moveF(e) {
t1.circle.x = stage.mouseX;
t1.circle.y = stage.mouseY;
}


// to move a rect here is the code
var t2 = this;
t2.rect.addEventListener('mousedown', downFr)

function downFr(e) {
stage.addEventListener('stagemousemove', moveFr);
stage.addEventListener('stagemouseup', upFr);
};
function upFr(e) {
stage.removeAllEventListeners();
}
function moveFr(e) {
t2.rect.x = stage.mouseX;
t2.rect.y = stage.mouseY;
}

*/

samedi 27 février 2016

Split if letters > at 10 in AS3

I'm trying to split every words that contains more than 10 letters.

How can I do ?

I did :

if (item.title.length > 10){
        trace("item.length>10"); // 0
// What should I put here in order to erase the letters after the 10th one ?
}

open file using navigateToURL

I'm making an android file browser app designed with as3. I finished designing every thing now I just need a way to open a file (image, video, pdf.. etc). right now I'm using this code:

navigateToURL(new URLRequest(File.desktopDirectory.url + "/" + fileName, "_blank"));

on pc it opens the file in the default web browser but on android device it only opens the file in "google drive" app as a pdf and shows error message that the choosen file is not a pdf file and when disabling "google drive" it does nothing.
can you please tell me whats wrong? or give me a way to open a file?
I know this is a dublicate but none of other solutions worked for me.

Randomizer and library?

I am making an RPG card game and I need to know how to make a randomizer set so if it lands on a number, it'll go to the frame assigned? Also need to know if I need a certain library for this. Haven't touched one yet.

AS3 Error 1009 when Debugging

I'm trying to create a game over screen for my space ship game, when player's shields reach 0 it goes to game over screen and stop the gameplay. The game over screen is working, but I can't stop the gameplay. I tried to set the Ship to null when player's shields reach 0 but I got error 1009. And all the gameplay objects (Ship, Enemy...) will loaded to the stage when "public function fGameStart(evt: Event): void {" executes, is there a way that I can stop this function from running when game over? Any help is greatly appreciated!

public class Engine extends MovieClip {
    private var preloader: ThePreloader;

    public function Engine() {
        stage.addEventListener("gameSTART", fGameStart);
        stage.addEventListener("gameOVER", fGameOver);
    }

    private var numStars: int = 80;
    public static var enemyList: Array = new Array();
    private var ourShip: Ship;

    public function fGameStart(evt: Event): void {

        ourShip = new Ship(stage);
        ourShip.x = stage.stageWidth / 2;
        ourShip.y = stage.stageHeight / 2;
        ourShip.addEventListener("hit", shipHit, false, 0, true);
        stage.addChild(ourShip);

        for (var i: int = 0; i < numStars; i++) {
            stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip));
        }

        addEventListener(Event.ENTER_FRAME, loop, false, 0, true);

        function loop(e: Event): void {

            if (Math.floor(Math.random() * 20) == 5) {
                var enemy: Stinger = new Stinger(stage, ourShip);
                enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
                enemy.addEventListener("killed", enemyKilled, false, 0, true);
                enemyList.push(enemy);
                stage.addChild(enemy);
            }

            else if (Math.floor(Math.random() * 80) == 5) {
                var enemy2: Stinger2 = new Stinger2(stage, ourShip);
                enemy2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
                enemy2.addEventListener("killed", enemyKilled, false, 0, true);
                enemyList.push(enemy2);
                stage.addChild(enemy2);
            }
        }
    }

    public function fGameOver(e: Event) {
        gotoAndStop(4);
        ourShip = null;
    }


}

How to fix or correctly make an undo button using sharedObject, without the 2 shared objects syncing?

In short i'm trying to make an undo button by using 2 save files, it's probably something really simple but i just can't seem to see why i'm getting the same data in both shared objects.

Ideally i would like the first mouse click to save array = [0] into load1dataobject

the second to save array [0,1] into load2dataobject

the third to save array[0,1,2] into load1dataobject //here if i used undo, i'd want to load load2dataobject which was array [0,1]

and so forth...

thanks in advance

import flash.net.SharedObject;

var load1DataObject:SharedObject = SharedObject.getLocal("Undo1");
var load2DataObject:SharedObject = SharedObject.getLocal("Undo2");
var array:Array = [];
var undoFunctionSwitch = 0;
var i = 0;

stage.addEventListener (MouseEvent.CLICK,clicked);

function clicked (MouseEvent)
{
        array[i] = i;
        i ++;
        undoFileSwitch ();

        trace (load1DataObject.data.array);
        trace (load2DataObject.data.array);
}

function undoFileSwitch ()
{
        if (undoFunctionSwitch == 0)
        {
                trace ("saved1");
                saveFile1 ();
                undoFunctionSwitch++;
        }
        else
        {
                trace ("saved2");
                saveFile2 ();
                undoFunctionSwitch--;
        }
}

function undoFile ()
{
        if (undoFunctionSwitch == 0)
        {
                loadFile1 ();
        }
        else
        {
                loadFile2 ();
        }
}

function saveFile1 ()
{
    load1DataObject.data.array = array;
    load1DataObject.flush();
}

function saveFile2 ()
{
    load2DataObject.data.array = array;
    load2DataObject.flush();
}

function loadFile1 ()
{
        array = load1DataObject.data.array;
}

function loadFile2 ()
{
        array = load1DataObject.data.array;
}

vendredi 26 février 2016

typeerror : 2007 actionscript3

I am running the following piece of code:

function letterclick(e:MouseEvent)
{
    myxmllist = new XMLList(myxml.word.(@clas==e.target.name).@wordname);
    for each (var word:XML in myxmllist)
    {
        var btn:MovieClip = createbtn(myxmllist[i]);
        btn.x = 100;
        btn.y = 130 + n;
        addChild(btn);
        n +=  50;
        btn.addEventListener(MouseEvent.CLICK,wordclick);
        i++;
    }
    var a:String = e.target.name
    if (a=="xx") a="x"
    else if (a=="yy") a="y"
    else if (a=="zz") a="z" 
    activeletter.text = a.toUpperCase()
}

but i have TypeError: Error #2007: Parameter text must be non-null. Can anyone tell me what is going on and how to remove this error.

Movieclip problems in AS3 tile based

I'm making the TonyPa ISO tutorials in AS3. I've traduced the code to AS3 and works well but I have a question because I can't solve the problem.

When I create the tiles, I create an empty MC to hold it, making this:

var tiles: MovieClip = new MovieClip();
var back: MovieClip = new MovieClip();
tiles.name = "tiles";
addChild(tiles);
tiles.addChild(back);

Then, I attach the tiles doing that:

game.clip = tiles;
var namer: String = "t_" + y + "_" + x;
game[namer] = new game["Tile" + map[y][x]]();
var myTile: _myTile = new _myTile();
game.clip.addChild(myTile);
myTile.name = namer;
myTile.x = (x * game.tileW);
myTile.y = (y * game.tileH);
myTile.gotoAndStop(game[namer].frame);
trace(game.clip[namer]);

But the trace says "undefined". I know, the correct code for show the name is changing the tracer to

trace(myTile.name);

But in another function, I have to change the tiles, and when I try to get the name of the tile, it says is "undefined", because I ned to get the name using this:

game[namenew] = new game["Tile"+map[ynew][xnew]]();
game.clip[nameold].namer = namenew;
game.clip[namenew].gotoAndStop(game[namenew].frame);
game.clip[namenew].x = (xnew*game.tileW);
game.clip[namenew].y = (ynew*game.tileH);

The variables namenew, ynew, xnew, nameold, etc. are defined in the entire function, It doesn't matter. What I want to know is, how I can attach the Movieclip _myTile to game.clip? The old AS2 code is this:

var name = "t_"+i+"_"+j;
game[name] = new game["Tile"+map[i][j]]();
game.clip.attachMovie("tile", name, i*100+j*2);
trace (trace(game.clip[name]); // Shows the name 4example: level10.tiles.t_3_5

Thanks!

Adobe AIR CameraUI photo orientation

Im having some issues some Android devices when trying to take a photo using CameraUI class.

My AIR app is portrait only autoOrients = false, but for some reason, when taking a photo in portrait orientation, the image will return as rotated 90 degrees to the right.

This happens only on Samsung S6, but doesnt for example on HTC M8.

Is there a fix to this problem or is this just one of the eternal bugs in Adobe bugbase?

Is using ANE my best bet to fix this problem?

Getting 499 status code on PHP Nginx server using flash(AS3) client app with no reason

I have experienced some strange behaviour on our PHP Nginx server and couldn’t find explanation to that behaviour so I would like to ask for some help from community.

We have a PHP back-end application with something about 500 req. per sec. coming from flash front-end app.

We noticed that we get same error continually from flash requests named “I/O error (code: #2032)”. Frequency is 0.3 to 1 req. per sec continually with visits (approximately 1000-3000 errors per hour) out of those 500 requests per second. There is no possibility to track this status code or any response in flash(AS3) when you get this error.

Sometimes there is peak for few minutes where almost every person in game can get this error.

I created solution to track and analyse those errors. After some time I can confirm that this strange behaviour is based on two status codes that are fired from Nginx no matter if request hits our back-end application behind Nginx server or not. Status codes are 499 and 408.

I found that cause of this error can be “client_body_timeout” setup in Nginx or anything connected to huge request size but some of those requests are almost empty or there is no difference from other that have successfull story.

Another strange thing is that I have a proof that some of error requests has been evaluated as I/O error on client(499 or 408 status code from Nginx) but on back-end application was task coming from request executed successfully and all data are stored in DB for example.

There is no pattern in Internet browser usage, OS, device, client IP, back-end IP behind load balancer or specific country visit.

Any suggestions?

AS3 - How do I import an external image to the stage while my program is running?

I've been trying to find a solution to this question for weeks but I haven't had any success so now it's finally time I turn to stackOverflow. I really hope you guys can help me out with this.

I'll explain a little better what exactly I'm trying to make and get done here.

I'm making a program in which I can make cards for my own cardgame. An important part of the program is that I can import images into the card-layout. The problem however, is that I have no clue how to program such a thing.

What I want (as I think it's the simplest way): I have a box with certain dimensions. When you click it, I want it to open the directory and allow you to import an image (JPG, PNG, etc.) and then I want the box to replace it's color with the image. (automatically cropped to the dimensions of the box) I only want it to change the color of the box to the image and not that it replaces the whole object, because I want to be able to still select another image if I want to.

I hope this isn't all too vague and that someone will be able to help me out here. A huge thanks already for your time even reading this!

jeudi 25 février 2016

AS3 TextField: How do I Turn Off Long Keypress Extended Characters?

In Flash/AS3 (in AIR on OSX), I have a TextField object that is a child of a different display object. The TextField is set to type DynamicText. If any object but the TextField is clicked (or just the stage), pressing and holding down a key will result in repeat KeyDown messages, which is fine.

However, if the TextField object is clicked/selected, and I hold down a key, I get the "extended character selector" popup (for alternate Unicode characters associated with that key). There does not seem to be an event for this, and I haven't found any documentation that describes this situation.

Can this feature (long press results in extended character selector) be turned off? How?

This image demonstrates the popup when the "S" key is held down: Long Press Extended Character Example

using Action Script 3 remove an object that appeared in the run time

I use this code to create list of words from an array and make them act like buttons in the main page i have 2 buttons that activate the for loop to create the list of words the problem is when i hit the second button in the main the list of words of the first button still shown on the screen, i need to remove the list first then activate the second loop i used the removeChildAt() function but it didn't worked what should i do ?

var words:Array = [];
var word:MovieClip=new MovieClip();

if(e.target.name=="glossumbolA"){

words=['School1','School2','School3','School4','School5','School6']

for (var j:int = 0; j < words.length; j++)
{
    word = createTextButton(words[j]);
        addChild(word);
    word.addEventListener(MouseEvent.CLICK, wordButtonClick);
}
}



else if(e.target.name=="glossumbolB"){

words=['Class1','Class2']

for (var i:int = 0; i < words.length; i++)
{

     word = createTextButton(words[i]);
     addChild(word);
     word.addEventListener(MouseEvent.CLICK, wordButtonClick);
}

    }


function createTextButton(){

//code to make the word in the array a button

}

function wordButtonClick(){

//code to make an action when the word in the array clicked
} 

import from xml to fla error

i have this xml tree

<?xml version="1.0" encoding="UTF-8"?>
<letters>
 <all>
      <explain>
          <word>slope</word>
      </explain>
      <description>
          <definition>a</definition>
      </description>
  </all>

   <all>
      <explain>
          <word>slope2</word>
      </explain>
      <description>
          <definition>b</definition>
      </description>
  </all>
</letters>

i want to get the word as " slope " from xml to button in swf . when i click this button it will get definition as " a " .. i think that i will get word and definition both of them once time but definition will be in textarea and it will be hidden and with click it will be visible .. so i made that but i have a problem .. help me

import flash.events.MouseEvent;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.Sprite;
import flash.display.MovieClip;
import fl.controls.TextArea;

stop();
var ChangebtnPosition:int = 50;
var definition:Array = new Array  ;
var MydataAreaPosition:int = 580;

var myLoader:URLLoader= new URLLoader();
myLoader.load(new URLRequest("eL366.xml"));
myLoader.addEventListener(Event.COMPLETE,loadXML);
function loadXML(e:Event)
{
    var myxml:XML = new XML(e.target.data);
    var lenngth:int = myxml.children().length();
    for (var i:int = 0; i < lenngth; i++)
    {
        var btn:MovieClip = ButtonForWord(String(myxml.all.explain[i - 1].word));
        var aTa:TextArea = new TextArea();
        aTa.move(130,MydataAreaPosition);
        aTa.setSize(200, 200);
        aTa.condenseWhite = true;
        aTa.htmlText = String(myxml.all.description[i - 1].definition);
        addChild(aTa);
        aTa.visible = false;
        MydataAreaPosition +=  40;
        btn.x = 165;
        btn.y = 165 + n;
        addChild(btn);
        ChangebtnPosition +=  50;
        btn.addEventListener(MouseEvent.CLICK,aTaShow);
    }
}
function ButtonForWord(label:String):MovieClip
{
    var txt:TextField = new TextField();
    txt.defaultTextFormat = new TextFormat('Cooper Black',20,0x8b3a3a);
    txt.text = label;
    txt.autoSize = TextFieldAutoSize.LEFT;
    txt.background = txt.border = false;
    txt.selectable = false;
    var btn:MovieClip = new MovieClip();
    btn.mouseChildren = false;
    btn.buttonMode = true;
    btn.addChild(txt);
    btn.label = label;
    return btn;
}
function aTaShow()
{
    addChild(aTa);
}

AS3 help needed if button1 of a movieclip && button2 of another movieclip clicked then gotoAndPlay

I made a memory cards game which has 24 card images from which the user has to find 7 images in order to win. I am a begginer of actionscript 3 all the code is on frames instead of document or class files. All 24 card images are movieclips, on the set of 7 images i made a button with the second state in the same layer with the win image. All the cards are created dynamically from the library and not in the stage. My problem is what i ever have tried untill now for the last code in order to win had no success i'm very desperate please help me .....I cannot make two movieclips to communicate via variables.

enter image description here

Main timeline frame 6 has this code

import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.*;
import flash.ui.Mouse;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.text.*;
import flash.display.Stage;

var objImage1:logo1 = new logo1;
var objImage2:pic2 = new pic2;
var objImage3:pic3 = new pic3;
var objImage4:logo2 = new logo2;
var objImage5:pic5  = new pic5;
var objImage6:pic6 = new pic6;
var objImage7:pic7 = new pic7;
var objImage8:logo3 = new logo3;
var objImage9:pic9 = new pic9;
var objImage10:pic10 = new pic10;
var objImage11:logo4 = new logo4;
var objImage12:pic12 = new pic12;
var objImage13:pic13 = new pic13;
var objImage14:pic14 = new pic14;
var objImage15:pic15 = new pic15;
var objImage16:logo5 = new logo5;
var objImage17:pic17 = new pic17;
var objImage18:logo6 = new logo6;
var objImage19:pic19 = new pic19;
var objImage20:pic20 = new pic20;
var objImage21:logo7 = new logo7;
var objImage22:pic22 = new pic22;
var objImage23:pic23 = new pic23;
var objImage24:pic24 = new pic24;
var sourceDeck:Array =[objImage1,objImage2,objImage3,objImage4,objImage5,objImage6,objImage7,objImage8,objImage9,objImage10,objImage11,objImage12,objImage13,objImage14,objImage15,objImage16,objImage17,objImage18,objImage19,objImage20,objImage21,objImage22,objImage23,objImage24];
var shuffledDeck:Array = new Array ();
var xValues:Array =["121","321","521","731","937","1136","120","320","520","732","938","1138","120","321","520","730","938","1135","121","322","520","732","938","1135"];
var yValues:Array =["173","173","173","173","173","173","346","346","346","346","346","346","534","534","534","534","534","534","716","716","716","716","716","716"];

function placeCards():void
{
for (var i:int = 0; i<sourceDeck.length; ++i)
{
    addChild(sourceDeck[i]);
    sourceDeck[i].x = int(xValues[i])+20;
    sourceDeck[i].y = int(yValues[i]);  
}
}
placeCards();
function removeCards():void
{
for (var i:int=0;  i<sourceDeck.length; ++i)

{
    removeChild(sourceDeck[i]);

}
}
    function shuffleCards():void
{
while(sourceDeck.length >0)
{
    var r:int=Math.floor(Math.random()*sourceDeck.length);
    shuffledDeck.push(sourceDeck[r]);
    sourceDeck.splice(r,1);
}
}
function placeShuffledCards():void
{
for (var i:int=0; i<shuffledDeck.length; ++i)
{
    addChild(shuffledDeck[i]);
    shuffledDeck[i].x = int(xValues[i]);
    shuffledDeck[i].y = int(yValues[i]);

}
}


function showShuffledCards():void

{   
removeCards();
shuffleCards();
placeShuffledCards();

}
showShuffledCards();
foo();

function foo():void {
    var x:int = 2; // you can use variables as you would normally

    // do something here

    var timer:Timer = new Timer(5000);
    var afterWaiting:Function = function(event:TimerEvent):void {
   timer.removeEventListener(TimerEvent.TIMER, afterWaiting);
   timer = null;
   // 5 seconds have passed, now do something more


   objImage1.gotoAndPlay(10);
   objImage2.gotoAndPlay(10);
   objImage3.gotoAndPlay(10);
   objImage4.gotoAndPlay(10);
   objImage5.gotoAndPlay(10);
   objImage6.gotoAndPlay(10);
   objImage7.gotoAndPlay(10);
   objImage8.gotoAndPlay(10);
   objImage9.gotoAndPlay(10);
   objImage10.gotoAndPlay(10);
   objImage11.gotoAndPlay(10);
   objImage12.gotoAndPlay(10);
   objImage13.gotoAndPlay(10);
   objImage14.gotoAndPlay(10);
   objImage15.gotoAndPlay(10);
   objImage16.gotoAndPlay(10);
   objImage17.gotoAndPlay(10);
   objImage18.gotoAndPlay(10);
   objImage19.gotoAndPlay(10);
   objImage20.gotoAndPlay(10);
   objImage21.gotoAndPlay(10);
   objImage22.gotoAndPlay(10);
   objImage23.gotoAndPlay(10);
   objImage24.gotoAndPlay(10);
   // the scope is retained and you can still refer to the variables you
   // used earlier
   x += 2;
 }
 timer.addEventListener(TimerEvent.TIMER, afterWaiting);
    timer.start();

}

on each one of the seven buttons that each one is inside a movie clip I have this code:

import flash.display.Sprite; 
import flash.text.*;
import flash.display.MovieClip;
import flash.events.MouseEvent;
var success:Boolean = false;
var butpic1:SimpleButton;
butpic1.enabled = true;
addChild(butpic1);

butpic1.addEventListener(MouseEvent.CLICK, clickpics);

function clickpics(event:MouseEvent):void {
gotoAndPlay(1);
var myTextBox:TextField = new TextField();    
    myTextBox.text = "Σωστό Συνέχισε!";  
myTextBox.border = true;    
    myTextBox.borderColor = 0x000000; 
myTextBox.width = 180;    
myTextBox.height = 87;    
myTextBox.x = -77;    
myTextBox.y = -126; 
var myFormat:TextFormat = new TextFormat(); 
myFormat.color = 000000;    
    myFormat.size = 24;
myFormat.align = TextFormatAlign.CENTER
myTextBox.background = true;    
myTextBox.backgroundColor = 0xFFF000;
myTextBox.setTextFormat(myFormat);
    addChild(myTextBox);  

/*var Success=true;*/
//MovieClip(parent).Success2();
//trace(event.target.name);
var success=true;
if(MovieClip(root).butpic3 && butpic1 == success)
    {

    MovieClip(root).gotoAndPlay("win");
    } 
//checking();
//trace(event.target);
//MovieClip(this.parent).success2();
//checking();
//MovieClip(root).check();
//trace("click: " + event.currentTarget.name);
}
//trace(MovieClip(root).but.butpic2);
/*function checking():void
{
if(butpic1 && MovieClip(root).butt.butpic3)
    {
    MovieClip(parent).gotoAndPlay("win");
    } else {
MovieClip(parent).gotoAndPlay("win");
}
}*/

/*function checking():void
{
if(MovieClip(root).Symbol1 && MovieClip(root).button2)
    {

    MovieClip(parent).gotoAndPlay("win");
    } 
}*/

AS3 Increment Timer by User Input

I am a noob to AS3 so excuse me, please.

I have a timer on my app that I am trying to use as a stop watch, What I would like to do is start it at a specified time not always at 0?

I would like the user to enter in a text box a value of 1 to 99 and the timer starts from there entered value.

Thanks in advance.

Uploading large apk based on flash to google play

I would like to upload large apk (more than 200 MB) to google play The application consists of: main.swf which navigates to all folders folder1: contains many swf files reached through main.swf folder2: as folder1 and there are some other folders

The question is, how can I make apk only with the main file main.swf and make the other folders uploaded as expansion files

I would like to make sell the apk on google play with all its components but it is not supported to add large files

please advice

Change MovieClip size with input textbox (Flash AS3)

I have a project where MovieClips can be dragged and dropped.

I would like to know how to make an input textbox appear after clicking on the MovieClip, where the user is able to put in a number in the input textbox that increases the size of the MovieClip according to the number entered.

After the number is entered I would like the textbox to dissappear, and only reappear when MovieClip is clicked again.

Example illustration below:

Example

Can anyone explain me how to record user audio using as3 from very basic?

I am a beginner to actionscript-3. I want to develop an application where I will be needing to record user audio and store it. Can anyone help me to learn the topic from very basic?

mercredi 24 février 2016

ActionScript 3.0 import swf

i've little bit trouble with imported swf. Problem is that imported swf has movie clip which exported as movie clip class. Code is here: Imported swf:

 class myBooks(){

    var myBg:MovieClip = new backGround();
    stage.addChild(myObjects);

and HOLDER flash file:

    var txt:String = "Project/book2.swf";
    var myLoader:Loader = new Loader();
    var url:URLRequest = new URLRequest(txt); 
    myLoader.load(url); 
    addChild(myLoader);

when i try to run , it shows me error like this:

   TypeError: Error #1009 cannot access a property or method of a null object reference at actions::myBooks()

Automatically search for trailer on web with only the title AS3- AIR

I'm making an AIR app with theaters hours for movies.

The movies titles are retreive from a database.

Is it possible to add in my AIR app a youtube video of the trailer, based on the title. Exemple :

if `item.title` (where item is an object) == "Star Wars 7" {
video trailer of item.title 
}

Do you think it's faisable or impossible ?

detect if htmlText contains a particular word in AS3

I've got this code :

movieDetailsClip.detailsTxt.htmlText = "<U>hours:</U> " + item.moviehour;

where item.moviehour is some hours taking from my database (item:Object)

How can I tell the code :

if item.moviehour contains the word "2D"{
</BR> after "2D"
}

I suppose it's simplier to put item.moviehour into a string.

So I've added :

 strMovie = item.moviehour;

Searching the word "2D" is :

var searchWord:int = strMovie.indexOf("2D");

Now, how can I tell to go to the line () after the word "2D" ?

Thanks

How can I call timeline-specific methods from an external file in AS3?

I'm creating a game is Flash CS5 with ActionScript 3. To simplify things, I've created a file (Game.as) in the top layer of my source folder. My Game.as file looks as follows:

package {
    public class Game {
        public static function fail():void {
            stop();

            var restart:RestartButton = new RestartButton();
            addChild(restart);

            restart.x = stage.stageWidth/2;
            restart.y = stage.stageHeight/2;

            Game.createButton(restart, function(e:MouseEvent):void { gotoAndPlay (1, "Title Sequence") });
        }
    }
}

I would supposedly call Game.fail () from a frame on a timeline a scene, but I get these compiler errors:

Line 11 1180: Call to a possibly undefined method stop. Line 19 1180: Call to a possibly undefined method gotoAndPlay. Line 17 1120: Access of undefined property stage. Line 16 1120: Access of undefined property stage. Line 14 1180: Call to a possibly undefined method addChild.

Why are these errors happening? What can I do to fix them?

Thanks for your help in advance.

Error 1119 when using Inspectable in class extending a parent also with Inspectable properties

Short description:

I have a class C which is extending a class P. Class P has a few Inspectable properties.

I added a few Inspectable properties to class C, linked C to a component in library and added C as the class of the Component Definition of that component. I could, at that point, read and set the Inspectable properties(that belong to P and C) of the instances of that component that were on stage through Component Parameters section of Properties window.

However, if I set even a single Inspectable property of class C through Component Parameters, when I try to export an .swf, I get a different compiler error 1119 for each Inspectable property of C(even if I did not set it and left its default value), saying that I am referencing possibly undefined property childProperty through a reference with static P.

Detailed description:

I have a class ChildClass, which extends a class ParentClass and I am trying to declare a few public attributes of ChildClass as Inspectable. ParentClass, too, has a few Inspectable getters and setters helping access corresponding protected attributes in the parent.

For the sake of completeness, consider that there is an inspectable property of ChildClass named childProperty. Consider also that there is an object of type ContainingClass which has a public attribute childClassInstance of type ChildClass. ContainingClass is linked to a library component which does have a ChildClass instance as a child. Finally, note that ChildClass is in samplePackageB.a while ParentClass is in samplePackageA.

So the code looks like this:

    package samplePackageA
    {
        public class ParentClass extends MovieClip
        {
            protected var _parentValue:String;
            [Inspectable(defaultValue="")]
            public function get parentValue():String { return _parentValue; }
            public function set parentValue(value:String):void {
                _parentValue = value;
            }
            ...
        }
    }

    package samplePackageB.a
    {
        import samplePackageA.ParentClass;
        public class ChildClass extends ParentClass
        {
            [Inspectable(defaultValue="1.0")]
            public var childProperty:Number;
            ...
        }
    }

    package samplePackageB.b
    {
        import samplePackageB.a.ChildClass;
        public class ContainingClass extends MovieClip
        {
            public var childClassInstance:ChildClass;
            ...
        }
    }

I added ChildClass to the Component Definition of a library component. and I could read/set inspectable properties of both ParentClass and ChildClass in the Component Parameters of an instance of that library component which was on stage.

However, when I try to export a .swf of this .fla file, I get compiler error 1119, stating that I am "accessing (of) possibly undefined property childProperty through a reference with static type ParentClass".

The only similar issue I found can be viewed here but it seems it wasn't conclusively solved(or explained) then, either.

ContextMenu detection

(Apache Flex) Right Click brings up the ContextMenu, which I have changed the contents of. All works fine except the MOUSE pointer was hidden to use a custom pointer. The problem is my custom pointer does not move while the context menu is active, nor does the system pointer show because it is hidden. How do I detect the Activation and Deactivation of the Context Menu? An event listener would toggle Mouse show/hide to cure the problem, but I cannot find one for Context Menu De/Activation.

Reducing png file size in as3

I tried to reduce the size of the png file in AS3

I used mLoader to load the png file and got the png's bitmap

public function savePng(bitmap:Bitmap,scale:Number):void
{
  var bitmapData:BitmapData = new BitmapData(bitmap.width*scale,bitmap.height*scale);
  bitmapData.drawWithQuality(mLoader,new Matrix(scale,0,0,scale), null, null, null , true, StageQuality.BEST);
  var pngEncorder:PNGEncoder = new PNGEncoder();
  var bytes:ByteArray = pngEncorder.encode(bitmapData);
}

But when I saved the image,it appeared jagged. I also used nid.image.encoder.PNGEncoder and PNGEncoder2,they were all useless.

Adobe Flash CS6

We've created an application using Adobe Flash CS6. There are videos imported it is properly running but when it is tested on mobile devices the videos won't work. We already installed all applications needed for the flash to run but still doesn't work. Please help us. We badly needed it for our thesis. Thank you.

How to Restrict the Drag option of an object within a particular area in ActionScript3

I have two Objects

  • one created with scale-factor 0.8 and with height 450 and with width 650.

  • And another one created with scale-factor 1.2 and with height 450 and with width 650

When i tried to restrict the drag option of these two objects to a certain rectangle then i found that one object (i.e first one) is moving within the given rectangle boundary but second one is not moving within the rectangle boundary that means it is also moving out side the boundary.

Following are my codes:

var rect:Rectangle = new Rectangle(200 , 0 , 800 , Capabilities.screenResolutionY);
obj.startDrag(false , rect);

I found that starting x and y co-ordinate point for the both objects are same means these are not moving below x coordinate (i.e 200) but the set width and height of the rectangle is different where i an providing same height and width for the both object.

So i don't know why it is happening like this.

Does anyone have an idea where I'm doing wrong?

AS3 - Endless Vertically Scrolling Background

As my first AS3 project, I'm developing a simple space shooter/bullet hell game. I looked online for a way of producing an infinite background scrolling effect and found this working code.

    public function backgroundScroll (evt:Event):void
    {
        background1.y -= scrollspeed;
        background2.y -= scrollspeed;
        if (background1.y <= -background2.height)
        {               
            background1.y = background2.y + background2.height;
        }
        else if (background2.y <= -background2.height)
        {
            background2.y = background1.y + background1.height;
        }           
    }   

This causes the background to infinitely scroll upwards from the bottom of the screen without fail, but no matter what I try, I cannot cause it to instead infinitely scroll down from the top of the screen. Any help would be greatly appreciated.

mardi 23 février 2016

How to add CuePoint to a rtmp stream with ActionScript 3.0

I am trying to build a teaching application using flash player. My idea is that when the teacher does something, such as changing the slides, the javascript calls the SWF interface which adds CuePoints to the rtmp stream, while the students listening on the CuePoint event, they are able to synchronize what the teacher is doing.

So I did my research and found out that I had to write some server-side script/module to support this. I tried Wowza Server and wrote a Java Module which defined a handler function so the AS was able to call

netconnection.call("handler_function", null, "myStream", arg1, arg2);

But sadly, I am using a third-party streaming cloud so I can't write server-side code. Is there any way to add the CuePoint only on the client side with ActionScript?

display text in different position when loading from a php to AIR app

I've got a database with multiple lines of "title".

I asking my AS3 code to load theses lines like that :

urlReqSearchAll.method = URLRequestMethod.POST;  
loader5.load(urlReqSearchAll);
loader5.addEventListener(Event.COMPLETE,complete);
}

function complete(e:Event):void {
 addChild(list);
   products = JSON.parse(loader5.data) as Array;
     products.reverse();
    for(var i:int = 0; i < products.length; i++){
        createListItem(i, products[i]);
}
function showList():void {
    list.visible = true;
    searchList.visible = false;
}

function createListItem(index:int, item:Object):void {

    var listItem:TextField = new TextField();
    var myFormat:TextFormat = new TextFormat();
    myFormat.size = 25
    myFormat.color = 0x000000;
    myFormat.font = "Mohave";
    listItem.defaultTextFormat = myFormat;
    listItem.text = item.title;
    listItem.x = 2;
    listItem.y = 75+ index * 40;
    listItem.width = 350;
    listItem.height = 80;

 listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
        showDetails(item);
    });
    list.addChild(listItem);
    str = item.title;

}

The list is created in my textField listItem. But it's like that :

item1
item2
item3
..

Is it possible to display it like that ? :

item1                          item2                         item3

item4      

If so, how ?

Thx

NativeProcess communication giving error

I am trying to communicate to a python script through actionscript. it gives me error on line "var stdOut:ByteArray = process.standardOutput;" Error is: Implicit coercion of a value with static type IDataInput to a possibly unrelated type ByteArray. I am following the same approach as on Adobe's page:

package
{
    import flash.display.Sprite;
    import flash.desktop.NativeProcessStartupInfo;
    import flash.filesystem.File;
    import flash.desktop.NativeProcess;
    import flash.events.ProgressEvent;
    import flash.utils.ByteArray;

    public class InstaUtility extends Sprite
    {
        public var nativeProcessStartupInfo:NativeProcessStartupInfo = new     NativeProcessStartupInfo();
        public var file:File = new File("C:/Python27/python.exe");
        public var process:NativeProcess = new NativeProcess();
        public function InstaUtility()
        {
            nativeProcessStartupInfo.executable = file;
            nativeProcessStartupInfo.workingDirectory =     File.applicationDirectory.resolvePath(".");
            trace("Location " + File.applicationDirectory.resolvePath(".").nativePath);
            var processArgs:Vector.<String> = new Vector.<String>();
            processArgs[0] = "test.py";
            nativeProcessStartupInfo.arguments = processArgs;
            var process:NativeProcess = new NativeProcess();
            process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData); 
            process.start(nativeProcessStartupInfo); 
        }   
        public function onOutputData(event:ProgressEvent):void 
        { 
            var stdOut:ByteArray = process.standardOutput; //error
            var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable); 
            trace("Got: ", data); 
        }

    }
}

My createsjs preloader works well for previous version createjs but does not work for latest

My preloader works fine with previous version of createjs but latest version of createjs it does not work. so what the update needed ?

loader.onProgress = handleProgress;
    stage = new createjs.Stage(canvas);
    createjs.Ticker.setFPS(22);
    createjs.Ticker.addEventListener("tick", stage);


    var progress = new createjs.Shape();
    var progressBellow = new createjs.Shape();
    var txt = new createjs.Text();


    progress.graphics.beginStroke("#280000").drawRect(115,112,400,40);
    progressBellow.graphics.beginStroke("#280000").drawRect(115,112,400,40);
txt.x = 150;
txt.y = 190;
txt.font = ("25px Verdana");
txt.color = ("#f11c35");
function handleProgress(event) {
    progress.graphics.clear();
    // Draw the progress bar
    progress.graphics.beginFill("#92ba17").drawRect(115,112,400*(event.loaded / event.total),40);
txt.text = ("Loading " + 100*(event.loaded / event.total) + "%");
}


stage.addChild(progress,progressBellow,txt);
stage.update();

Trying to add an event listener for PLAYING/PAUSED_STATE_ENTERED, returning error 1119

Basically I have a very simple video gallery set up. I want it so that when the video is paused some buttons will become visible on the screen and when it is playing these buttons will not be visible. This is my code:

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

videoOne.addEventListener(Event.PLAYING_STATE_ENTERED, hideInfo());
videoOne.addEventListener(Event.PAUSED_STATE_ENTERED, showInfo());

function showInfo() {
    thumbnailOne.visible = true;
    thumbnailTwo.visible = true;
    thumbnailThree.visible = true;
    videoGalleryInfo.visible = true;
    infoHidden = 0;
}

function hideInfo() {
    thumbnailOne.visible = false;
    thumbnailTwo.visible = false;
    thumbnailThree.visible = false;
    videoGalleryInfo.visible = false;
    infoHidden = 1;
}

I have tried using Event instead of VideoEvent and so on as this fixed an issue with adding another event listener earlier on for the COMPLETE event, but I'm always returned with

Video gallery, Layer 'ActionScript', Frame 77, Line 22  1119: Access of possibly undefined property PLAYING_STATE_ENTERED through a reference with static type Class.

Video gallery, Layer 'ActionScript', Frame 77, Line 23  1119: Access of possibly undefined property PAUSED_STATE_ENTERED through a reference with static type Class.

I do not understand what I'm doing wrong. Shouldn't the properties be defined through importing fl.video.*; and flash.events.Event;?

AS3 Apache Flex: click randomly not updating stage until mouse moves

I have a SWF that displays a field of stars as a single BITMAP added to the Stage. The image is dynamically generated through the Bitmap's BitmapData, to allow trackball interaction with the star field. Planets and other buttons are also on the stage with hint Labels underneath.

All works as expected. However, sometimes clicking a button, performs an operation, that does not show up until the mouse moves. For example, clicking the button to toggle planet labels, will immediately update the stage with labels turning on and off. But sometimes, the click does nothing, until the mouse is moved, or another click is made and then both clicks activate in series.

Same goes for a button that resets the star field to show either the Sun to Earth or Earth to Sun view. Click the image (button) and the background star field updates immediately. However, sometimes it does nothing until the mouse moves. It seems like an interface timing issue beyond my control.

Anybody encounter this situation? Working on MAC with Firefox, all latest updates.

AS3 How to call a button from another class?

I'm trying to create a button that when you click on it, the ship fires a laser, but the button isn't working. I mean I didn't get any error when debugging, however it won't allow me to click on the button, but instead it allows me to click on my ship to fire. Any help is greatly appreciated, thanks!

Part of my button.as

package {

import flash.events.Event;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.MouseEvent;

import objects.Ship;

public class Fire extends MovieClip {

    public function Fire {

    addEventListener(MouseEvent.MOUSE_DOWN, shipfire);

    private function shipfire(event:MouseEvent):void
    {
        Ship.addEventListener(MouseEvent.MOUSE_DOWN, init)
    }

    }
}

}

part of my ship.as

package {

import flash.display.MovieClip;
import flash.display.Stage; 
import flash.ui.Mouse;
import flash.events.MouseEvent;
import flash.events.Event;

import control.Fire;    

public class Ship extends MovieClip
{

    private var stageRef:Stage;

    public function shipfire(e:Event) : void
    {   
        fireLaser();
    }
}

}

Photoshop Imaegmerge script

I need to do this on photosohp cs6, I have many folders named like "770_1" , "770_2" , "771_1", etc.

Each folder has 5-15 pictures inside which need to be merged using automerge on photoshop. The images inside each folder are automerged, and a file named "770_1_merged" , "770_2_merge" etc is created and placed in a folder named "merged_photos".

The photos are either .TIF or .JPG extension Does that sound doable?

Image format with Subimages or layers

So let's say that i have a paint program like adobe ilustrator(currently refering to Krita software). And let's say i made 5 layers and paint a simple stickman. 1 layer is transperent canvas, 2 is two legs, 3 is body, 4 hands, 5 head. All those layers combined made a stickman(that fine). now i load this picture into actionsript3. But now lets say that i want to move only legs by 10pixels without moving rest body. I won't be able to do this, maximum what i can is move whole stickman by 10pixel. Is there a format that will save whole image but also will indicate 5 subgroup(subimages, subdata.... call it what you want) like legs, body and others. Goal of this is that sometimes i want to rotate all stickman but sometimes i want to move only specific part like legs. Or the only way is to make 4 pictures of every body part and load them 1 by 1 into as3 and after combine into 1 single stickman?

hope this picture will help you a little

http://ift.tt/1QAHTh6

Subsribe to InlineGraphicElement mouse click

How can I implement this simple thing without getting list of all gaphic elements and adding listner to each? I can listen for mouse click event and get target as Loader which has parent.parent property as TextLine but I can't get InlineGraphicElement reference from it. Is there any functionality to determine which float element is under mouse pointer?

MovieClips scale down when StageScaleMode.NO_BORDER

I have my stage aligned to TOP_LEFT and scaled to StageScaleMode.NO_BORDER, the width and height of my SWF are : width = 1920 and height = 1080.

The thing is when my i change the SWF size to bigger (height/width) the movieClips on the stage scale up and that's a good thing for me, but when i reduce the size of my SWF to smaller values (smaller than the default size), the movieClips get reduced as well, aren't they supposed to stay the same, if not is there a way to make that happen ?

How to write multiple files using adobe flex

I have a string array where each object has comma separated and new line delimiters. Now i want to write these string objects to multiple CSV files. But I am able to write only one CSV file as below:-

        /**
         * callback method for exportCollection, results are in format of Map<String, String>
         **/
        protected function exportListResultHandler(event:ResultEvent):void {
            if (event.result != null )
            {
                for (var key:* in event.result) {
                    var value:String=event.result[key];
                    var fileName:String=key;
                    exportStringToFile(value.toString(), fileName);
                }
            }
        }

        private function exportStringToFile(stringToExport:String, filename:String=null):void
        {               
            //file refernce for import/export functionality. 
            var fileRef:FileReference = new FileReference(); 

            try{
                fileRef.addEventListener(Event.COMPLETE, finishUpload);            
                fileRef.addEventListener(IOErrorEvent.IO_ERROR, handleError);
                fileRef.save(stringToExport, filename);                
            }catch (error:Error){
                logger.error("Unable to save file. Error: ", error);  

        }

Mine existing codes do not allow me to use File class from flash.filesystem package. Even arrays of FileReference did not helped me. I want to save multiple file at one location.

I am new to Adobe flex and flash builder, Any help would be great. Thanks a a lot

embedding Articulate SWF in flex project

In one of my project I have to use swf generated using Articulate storyline 2 in Flex 4.7. I have added swf using SWELoader in my MXML file as follows:

<s:SWFLoader id="loader" top="0" left="0" bottom="0" right="0" source="assets/study/english/1/story.swf" />

And tried to run the course using following code:

protected function btnHelp_clickHandler(event:MouseEvent):void
{
var flashMovie:MovieClip = loader.content as MovieClip;

flashMovie.play();

}

But I am getting error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.articulate.bw.v3_0::bwPlayer/StartLoad()
at com.articulate.bw.v3_0::bwPlayer()

How can I make it run and also how to catch the relevant events to track the progress in my flex project?

Regards

lundi 22 février 2016

Flash AS3 MouseOver not working

I am having trouble getting a MOUSE_OVER event to fire consistently and as intended. I have a custom cursor (movieclip) attached to my mouse and it has 2 frames (1st frame cursor is black and second frame it is white).

Here is code from my cursor script:

    private function onAddedToStage(event:Event):void
    {
        gotoAndStop(1);
        this.mouseChildren = false;
        this.mouseEnabled = false;
    }
    public function rollover():void
    {
        gotoAndStop(2);
        trace("change cursor");
    }

Here is the class for an object that will react when the cursor moves over it:

public class DoorHS01 extends MovieClip
{
    public var cursor:Cursor;
    public function DoorHS01() 
    {
        cursor = new Cursor();

        this.addEventListener(MouseEvent.MOUSE_OVER, rollover);
    }

    public function rollover(e:MouseEvent):void
    {
        cursor.rollover();
        trace("rollover");
    }
}

}

So in the DoorHS01 class the MouseEvent doesn't always fire or it will be really delayed. The cursor.rollever function gets called and it executes in the cursor class (I know from the traces) but the cursor never changes.

What am I missing?

Error #1009- Only when there is code present in main class

Please do forgive me if this is a stupid question, by I really need to know the solution. So here I have a program that generates particles every set distance of space. My program consists of a document class, called supportForce and an object class(of the particle) called TheDot. In the TheDot object class, I have the following code-

    package 
    {

        import flash.display.MovieClip;
        import flash.events.Event;
        public class TheDot extends MovieClip
        {
            var base:Object = MovieClip(root);
            public function TheDot()
            {
                this.addEventListener(Event.ENTER_FRAME, eFrame);
            }
            private function eFrame(event:Event):void
            {
                if (base.currentFrame == 1){
                    trace ("G");
                }
            }
        }

    }

This code works perfectly (outputs G) until I add the following code into the document class, suportForce, under an ENTER_FRAME event-

var ctX:int = 0,ctY:int = 0,done:Boolean = false; 
while (done == false)
            {
                var dots:TheDot = new TheDot  ;
                dots.alpha = 0;
                dots.x +=  (25 * ctX);
                dots.y +=  (25 * ctY);
                ctX++;
                if (ctX == 22 && ctY == 20)
                {
                    done = true;
                    break;
                }
                else if (ctX == 22)
                {
                    ctX = 0;
                    ctY++;
                }
                stage.addChild(dots);
            }

So now, there is an Error #1009: Cannot access a property or method of a null object reference at TheDot/eFrame(). I have declared all the variables in the correct place, and also the functions. Thanks in advance. I have the link to the .fla and .as files in my drive here, do use it if necessary. http://ift.tt/1PU7Dle

Connection from flash v11+ to to nodejs using TLS (SSL)

I recently started creating a server for a mmorpg im building all by myself and i used node js as the server language. I've searched around on the net and figured that using TLS was the way to go for authentification and creating a secure session over TCP/IP. Everything works fine, i created a certificate and self signed it with openssl using some commands on the web i found and it gave me the key and certificate i can use with my server. I tryed connecting with openssl and everything worked fine. The certificate node js use is in PEM format.

Thats the server code i am using:

var tls = require('tls');
var fs = require('fs');

var options = {
    key: fs.readFileSync(__dirname + '/server.key'),
    cert: fs.readFileSync(__dirname + '/server.crt'),
    //requestCert: true,
   //rejectUnauthorized: false,
};

tls.createServer(options, function(sock) {
    //stuff here
}).listen(PORT, HOST);

Now, my game is made in flash. So i try to connect using SecureSocket that come in flash player version 10+ i believe. The problem is that flash use a DER X.509 certificate format. So i converted the .PEM file into a .DER file using openssl and loaded it into flash. When i try to connect to my server (which is both on localhost, wanted to mention incase it change something), i can see the connection attempt on my server but it instantly close connection.

This is the error from flash:

Secure socket supported: true
ioErrorHandler: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2031: Erreur de socket. URL: localhost"]
securityErrorHandler: [SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048: Violation de la sécurité Sandbox : file:///C|/Users/DevilCult/Desktop/Flash%20Game/tcp%20test/Untitled%2D1.swf ne peut pas charger de données à partir de localhost:8089."]

But like i said, i can see the connection server side even if the error says the host is not valid. I Do the same without TLS socket and it work like a charm.

In my flash code i used addBinaryChainBuildingCertificate like this:

secureSocket.addBinaryChainBuildingCertificate(new key(), true);
secureSocket.connect("localhost", 8089);

this is the key() class:

package
{
 import flash.utils.ByteArray;

 [Embed(source="server.der", mimeType="application/octet-stream")]
 public class key extends ByteArray
 {
 }
}

I tryed to look around node js for information about loading the same kind of certificate (in DER format) but node js documentations says it only accept PEM format. And flash only accept DER format. And i guess using diff format on each machine doesnt work well together and that could be why my connection is dropping.

Anyway from now, i dont know where to go. There must be a way to use a DER format in node js. Ive been searching around and couldnt find anything.

Anyone have encoutered this problem before?

create different buttons in the runtime using actionscript

I need to create a number of buttons in the run time, each button has its own behavior like the style and the functionality what function shoud i use to give instance name to the button? as when i trace the name target it generated randomly as instance2 , instance6 and so on thank you

here is what i tried i create a class called glosbtn

import flash.events.MouseEvent;
import flash.events.Event;

for(var i:int=0;i<4;i++)
{
    for(var j:int=0;j<6;j++)
{
var btn:glosbtn= new glosbtn();
addChild(btn);
btn.x=50*j;
btn.y=50*i;
btn.addEventListener(MouseEvent.CLICK,glosbtnclick)

}
}

function glosbtnclick(e:Event){
    trace(e.target.name)
    // do my stuff
}

Is there a way to make clicking a button in Adobe Flash open multiple hyperlinks?

Simply put, is there a way to make clicking a button object in Flash Actionscript 3.0 open two hyperlinks in a browser? I've tried messing with the Actionscript and adding multiple functions, to no avail.

function(data:Object) as3

How can i get the data from this function in as3? or how to migrate it to as3?

mc.itemRollOut = function(data:Object)
{
trace(data + " : " + data.data);
}

The class that return's the data has the function:

public function itemRollOut(data:Object)
{
}

Thanks In Advance.

Play sound at the position x by means of "read/write"

Belwo is a exmple (from adobe) which works fine. But how can I play the sound at a certain position? E.g. after 10-Second. Something like

mySound.play(10000);

It is to use "read/write" commands, because I intend to change the speed of sound.

var mySound:Sound = new Sound(); 
var sourceSnd:Sound = new Sound(); 
var urlReq:URLRequest = new URLRequest("test.mp3"); 
sourceSnd.load(urlReq); 
sourceSnd.addEventListener(Event.COMPLETE, loaded); 
function loaded(event:Event):void 
{ 
    mySound.addEventListener(SampleDataEvent.SAMPLE_DATA, processSound); 
    mySound.play(); 
} 
function processSound(event:SampleDataEvent):void 
{ 
        var bytes:ByteArray = new ByteArray(); 
        sourceSnd.extract(bytes, 8192); 
        event.data.writeBytes(upOctave(bytes)); 
} 
function upOctave(bytes:ByteArray):ByteArray 
{ 
    var returnBytes:ByteArray = new ByteArray(); 
    bytes.position = 0; 
    while(bytes.bytesAvailable > 0) 
    { 
        returnBytes.writeFloat(bytes.readFloat()); 
        returnBytes.writeFloat(bytes.readFloat()); 
        if (bytes.bytesAvailable > 0) 
        { 
            bytes.position += 8; 
        } 
    } 
    return returnBytes; 
}

Thanks in advance.

Static variables initialized with returned value by a static function?

When I initialize a static const variable with the string returned by a static function, it is wrong, and the value of the static const variable is "". The code is as follow:

public static const BALL_TIP:String = Lang.getInstance.parse(LangConst.BALL_TIP);

I think the possible reason is that the static variable is initialized in the phase that function is can't be called.

please help me know why it is. Thank you very much.

dimanche 21 février 2016

Flash hangs when I execute this particular loop

Please do forgive me if this question is very stupid, but I couldn't figure out what to do, which is why I ask it. Here, I declared a small white square as a movieclip symbol(Dot) and I wish to generate it after a specific gap on the entire screen. So, when I execute this (test it) code on Flash CS6, it hangs. After that I will be forced to end the program without doing anything further.

import flash.ui.*;
stop();
Mouse.hide();
var ctX:int = 0,ctY:int = 0,done:Boolean = false;
var base:Object = MovieClip(root);
this.addEventListener(Event.ENTER_FRAME, eFrame);
function eFrame(event:Event):void
{
    while (done == false)
    {
        var dots:Dot = new Dot  ;
        dots.x +=  (50 * ctX);
        dots.y +=  (50 * ctY);
        ctX++;
        if (ctX == 11)
        {
            ctX = 0;
            ctY++;
        }
        else if (ctX == 11 && ctY == 10)
        {
            done = true;
            break;
        }
        stage.addChild(dots);
    }
}

Thank you in advance. I have attached a screenshot of the situation.

push notifications with adobe AIR (flash) works on iOS, not on Android

I have gotten push notifications to work on iOS using the milkman games "easy push" plugin. But I cant get it to work on android. The app crashes at the initManual() method(I have my own backend). This is the relevant error output:

Error: Failed creating EasyPush Extension Context.
at com.milkmangames.nativeextensions::EasyPush$/initContext()[D:\data\svn.milkmangames\trunk\ane\easypush\swclibrary\src\as3\com\milkmangames\nativeextensions\EasyPush.as:240]
at com.milkmangames.nativeextensions::EasyPush$/initManual()[D:\data\svn.milkmangames\trunk\ane\easypush\swclibrary\src\as3\com\milkmangames\nativeextensions\EasyPush.as:61]

If anyone happens to have experience with this plugin, please reply, or if you can suggest an entirely new route, I'm open. Thanks, - Corbin.

Changing the value of scaleX on a health bar when objects collide

I have been trying loads of different ways to make my health bar scaleX increase by 25% incrementally when it hits targets.

So far the closest I've come is with else if statements. The problem is actionscript runs through the else if statements and doesn't stop, it does all of the calculations and makes my health bar full every time I hit something. I understand why this is happening (the else if statements are becoming true as AS3 runs through them) but I don't know how to stop it. Any help is appreciated

var health:Number = 0;
var fullHealth:Number = 100;

healthBar.scaleX = health / fullHealth;

//collision

    if(dog_mc.hitTestObject(deadRat_mc)){
    deadRat_mc.visible=false;

      if (healthBar.scaleX==0){
         healthBar.scaleX =+.25;

        }
        else if (healthBar.scaleX==.25){
            healthBar.scaleX =+.50;
        }
        else if (healthBar.scaleX==.50){
            healthBar.scaleX =+.75;
        }
        else if (healthBar.scaleX==.75){
            healthBar.scaleX =+1;

        }

}

Why is the total size of bars in a flex stacked bar chart only equal the largest item?

I have created a vertical stacked bar chart using mxml & actionscript. The problem is;

The height of each bar is only as high as the largest item in the stack. So if I have two items, "a = 1.5" and "b = 2.75", the first item, "a", goes to the about the 1.5 grid line, but the total height of the bar only goes to about the 2.75 mark on the grid leaving the "b" portion of the stack smaller than the "a" portion and the overall height wrong.

I would expect in the example above that the bar would go to the 4.25 mark on the grid.

Here is the mxml;

            <mx:ColumnChart id="myChart" dataTipFunction="formatDataTip" maximumDataTipCount="1" dataProvider="{_acChartData}" showDataTips="true"
                        height="100%" width="100%">

            <mx:horizontalAxis>
                <mx:CategoryAxis dataProvider="{_acChartData}" categoryField="ActivityDate" title="Dates"/>
            </mx:horizontalAxis>
            <mx:horizontalAxisRenderer>
                <mx:AxisRenderer showLabels="true" labelRotation="0" labelGap="1" tickPlacement="inside"/>
            </mx:horizontalAxisRenderer>

            <mx:verticalAxis>
                <mx:LinearAxis id="lnaChart" minimum="0" maximum="24" maximumLabelPrecision="2" interval="2" title="Hours"/>
            </mx:verticalAxis>
            <mx:verticalAxisRenderer>
                <mx:AxisRenderer showLabels="true" labelGap="1"/>
            </mx:verticalAxisRenderer>

            <mx:series>
                <mx:ColumnSet type="stacked" id="csDays" allowNegativeForStacked="false" baseline="0" dataProvider="{_acChartData}">
                </mx:ColumnSet>
            </mx:series>

        </mx:ColumnChart>

Here is the actionScript to build the series;

        public function rebuildStack(ev:Event):void
        {
            var seriesArray:Array = new Array();
            acData.removeEventListener("listChanged", rebuildStack);
            var seriesActivity:ColumnSeries;
            var intMaxMinutes:int = 0;
            var intDayMinutes:int = 0;
            for (var i:int = 0; i < acCategory.length; i++)
            {
                seriesActivity = new ColumnSeries();
                seriesActivity.yField = acCategory[i]["CATEGORY"];
                seriesActivity.displayName = acCategory[i]["DESCRIPTION"];
                seriesArray.push(seriesActivity);
            }
            csDays.series = seriesArray;
            _acChartData = new ArrayCollection;
            var dtCurrentDate:Date;
            var objData:Object = new Object;
            for (i = 0; i < acData.length; i++)
            {
                if (dtCurrentDate == null)
                {
                    dtCurrentDate = acData[i]["TIMELOGS_TRANS_DATE"];
                }
                if (dtCurrentDate != acData[i]["TIMELOGS_TRANS_DATE"])
                {
                    _acChartData.addItem(objData);
                    dtCurrentDate = acData[i]["TIMELOGS_TRANS_DATE"];
                    objData = new Object;
                    if (intMaxMinutes < intDayMinutes)
                        intMaxMinutes = intDayMinutes;
                    intDayMinutes = 0;
                }
                objData["ActivityDate"] = dfMMDD.format(acData[i]["TIMELOGS_TRANS_DATE"]);
                for (var j:int = 0; j < acCategory.length; j++)
                {
                    var nbrMinutes:Number = 0;
                    if (acData[i]["CATEGORY"] == acCategory[j]["CATEGORY"])
                    {
                        nbrMinutes = Number(acData[i]["TIME_WORKED"]);
                    }
                    if (objData.hasOwnProperty(acCategory[j]["CATEGORY"]))
                    {
                        objData[acCategory[j]["CATEGORY"]] += nbrMinutes / 60;
                    }
                    else
                    {
                        objData[acCategory[j]["CATEGORY"]] = nbrMinutes / 60;
                    }
                    intDayMinutes += nbrMinutes;
                }
            }
            lnaChart.minimum = 0;
            lnaChart.maximum = Math.round((intMaxMinutes / 60) * 100) / 100;
            _acChartData.addItem(objData);
            _acChartData.refresh();
            _objAppUtilities.loadDataGrid(_acChartData, grid, true);
            acData.addEventListener("listChanged", rebuildStack);
        }

The chart is to display the number of hours worked in a given day for the last 30 days based on activity. The bars are the days, the items stacked are the activities. One purpose is to be able look at a give day and see the total hours worked, and all the activities that made up the work day.

Adobe air import SOL file with FileStream

I currently have a function that opens up a file browser and limits the selection to the .sol format. I want this function available for easier backwards compatibility support instead of moving the .sol file to the programs appdata folder. When the user selects a .sol, this function is called:

public function onSelect_sol(event: Event): void {
        var file: File = File(event.target);
        var fileStream: FileStream = new FileStream();
        fileStream.open(file, FileMode.READ);
        savedData = fileStream.readObject();
        trace(savedData);
        fileStream.close();
    }

However the information I get back from the trace is "null". What do I have to do to make it so I can use the information is the sol? I know this can be done, as the minerva sol editor uses adobe air and can open .sol files: http://ift.tt/NHOp6R

Actionscript 2 to 3 conversion

this is a sample of my game im trying to convert the code from actionscript 2 to 3. Ive looked up tutorials and sadly still dont have a clue. I would more than greatly appreciate it. If you would include why you changed.., Im hoping this is easier than it seems. Thank you... Also a couple tips or samples on what i need to look for in the future.

   class Human
    {
       function Human(nmc)
       {
          this.mc = nmc;
          this.pts = new Array(11);
          this.size = 3;
          var _loc4_ = 4;
          var _loc3_ = 6;
          var _loc2_ = 4;
          this.pts[0] = new Vec(0,(- this.size) * 2.5);
          this.pts[1] = new Vec(0,- this.size);
          this.pts[2] = new Vec(0,_loc2_ * this.size);
          this.pts[3] = new Vec((- _loc4_) * this.size,0);
          this.pts[4] = new Vec(_loc4_ * this.size,0);
          this.pts[5] = new Vec(- this.size,_loc2_ * this.size + _loc3_ * this.size);
          this.pts[6] = new Vec(this.size,_loc2_ * this.size + _loc3_ * this.size);
          this.pts[7] = new Vec((- _loc4_) * 2 * this.size,0);
          this.pts[8] = new Vec(_loc4_ * 2 * this.size,0);
          this.pts[9] = new Vec(- this.size,_loc2_ * this.size + _loc3_ * 2 * this.size);
          this.pts[10] = new Vec(this.size,_loc2_ * this.size + _loc3_ * 2 * this.size);
          this.pts[0].addLink(this.pts[1]);
          this.pts[1].addLink(this.pts[2]);
          this.pts[1].addLink(this.pts[3]);
          this.pts[1].addLink(this.pts[4]);
          this.pts[2].addLink(this.pts[5]);
          this.pts[2].addLink(this.pts[6]);
          this.pts[3].addLink(this.pts[7]);
          this.pts[4].addLink(this.pts[8]);
          this.pts[5].addLink(this.pts[9]);
          this.pts[6].addLink(this.pts[10]);
          this.left_wire = new Wire(this.mc,this.left_hand());
          this.right_wire = new Wire(this.mc,this.right_hand());
          this.left_wire.trans(this.left_hand());
          this.right_wire.trans(this.right_hand());
          this.walk_state = 0;
          this.on_the_ground = 0;
          this.use_left = true;
       }
       function left_hand()
       {
          return this.pts[8];
       }
       function right_hand()
       {
          return this.pts[7];
       }
       function trans(v)
       {
          var _loc2_ = 0;
          while(_loc2_ < this.pts.length)
          {
             this.pts[_loc2_].x = this.pts[_loc2_].x + v.x;
             this.pts[_loc2_].y = this.pts[_loc2_].y + v.y;
             this.pts[_loc2_].px = this.pts[_loc2_].px + v.x;
             this.pts[_loc2_].py = this.pts[_loc2_].py + v.y;
             _loc2_ = _loc2_ + 1;
          }
          this.left_wire.trans(v);
          this.right_wire.trans(v);
       }

AS3 - Numbers won't display in dynamic text field

I am writing a program that my brother needs for a project he is working on. It "solves" a password and then shows the number of loops the program goes through before figuring out the solution. I've gotten everything working but the program won't show the numbers in the dynamic text field. It only shows the letters.

Here's the code:

import flash.events.MouseEvent;

button1.addEventListener(MouseEvent.CLICK, solvePassword);

function solvePassword(e:MouseEvent):void
{
var pass:Number = Number(inputText.text);
var attempts:Number = 0;
var i:String = pass.toString();
var passLength:Number = i.length;
var n:Number = 0;

while(n != pass)
{
    if(passLength == 1)
    {
        n += 1;
        attempts += 1;
    }
    if(passLength == 2)
    {
        n += 1;
        if(n < 10) { n = 10 }
        attempts += 1;
    }
    if(passLength == 3)
    {
        n+=1;
        if(n < 100) { n = 100 }
        attempts += 1;
    }
    if(passLength == 4)
    {
        n+=1;
        if(n< 1000) { n = 1000 }
        attempts += 1;
    }
    if(passLength == 5)
    {
        n+=1;
        if(n < 10000) { n = 10000 }
        attempts += 1;
    }
    if(passLength == 6)
    {
        n+=1;
        if(n < 100000) { n = 100000 }
        attempts += 1;
    }
    if(passLength == 7)
    {
        n+=1;
        if(n < 1000000) { n = 1000000 }
        attempts += 1;
    }
}

i =  "Attempts: " + String(attempts);

trace(i);

aBox.text = i;

Any info would help, thank you!

alphabetic glossary xml by actionscript3

Glossary will navigate to Glossary page that will show alphabetic letters according to the English language , when click in each letter will show words that start with this letter , when click in each word will show the definition of the word . so i made alphabetic letters as buttons in fla . when i click on word the definition didn't show anything but trace is right

import flash.events.MouseEvent;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.Sprite;
import flash.display.MovieClip;
stop();
var n:int = 50;
var myLoader:URLLoader= new URLLoader();
myLoader.load(new URLRequest("rr55.xml"));
myLoader.addEventListener(Event.COMPLETE,loadXML);
var myxml:XML = new XML(myLoader.data);
function loadXML(e:Event)
{
    var myxml:XML = new XML(myLoader.data);
    for (var m:int=0; m<1; m++)
    {
        var btn:MovieClip = qwe(String(myxml.a));
        btn.x = 165;
        btn.y = 165 + n;
        addChild(btn);
        addEventListener(MouseEvent.CLICK,ghj);
        n +=  50;
        trace(n);
    }
}
function qwe(label:String):MovieClip
{
    var txt:TextField = new TextField();
    txt.defaultTextFormat = new TextFormat('Cooper Black',20,0x8b3a3a);
    txt.text = label;
    txt.autoSize = TextFieldAutoSize.LEFT;
    txt.background = txt.border = false;
    txt.selectable = false;
    var btn:MovieClip = new MovieClip();
    btn.mouseChildren = false;
    btn.buttonMode = true;
    btn.addChild(txt);
    btn.label = label;
    return btn;
}
function ghj(Event:MouseEvent)
{
    var btn2:MovieClip = qwe(String(myxml.a));
    btn2.buttonMode = false;
    btn2.x = 300;
    btn2.y = 165 + n;
    n +=  50;
    addChild(btn2);
    trace(btn2.y)
}

and my xml is

<?xml version="1.0" encoding="UTF-8"?>

<a>
    worda start with a
    worda2 start with a
    worda3 start with a
</a>

<b>
    wordb start with b
    wordb2 start with b
    wordb3 start with b
</b>

<worda> 
    the definition
</worda>

<worda2>    
    the defenition
</worda2>

<worda3>    
    the defenition
</worda3>

Connect to AS3 socket server with NODEJS

I'm triying to connect to a socket server wich the client is using new Socket() AS3 Class to connect. I'm triying to do something like the AS3 Socket class in nodeJS, how can I do that ? Is there any ready-made library ?

Action Script 3- Assigning index to a reference variable or comparing two index numbers

I am writing a program in Action Script 3 to assign a name to a matching month using two arrays. I have it so it already checks to see if the name matches one in the array and likewise with the month array, but I am having trouble with the final if statement asking whether the index numbers of the two match.

var Name:Array = new Array("John", "Mike", "Ben", "Thomas", "Chuck", "Charlie", "Peter", "Robert", "Dick", "Tracey", "Brienne", "Tywin");
var Month:Array = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

var Wrong:String = new String("Sorry, Wrong Input");

stop();

startButton.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);

function fl_MouseClickHandler(event:MouseEvent):void
{
// Start your custom code
var xName = NameInput.text;
var xMonth = MonthInput.text;
if (Name.indexOf(xName) != -1)
{
NameMatchOutput.text = xName;
}
else
{
NameMatchOutput.text = Wrong;
}

if (Month.indexOf(xMonth) != -1)
{
MonthMatchOutput.text = xMonth;
}
else
{
MonthMatchOutput.text = Wrong;
}
if (Name.indexOf(xName) = (Month.indexOf(xMonth)))
{
NameMonthMatchOutput.text = "They Match";
}
else
{
NameMonthMatchOutput.text = "They Don't Match.";
}

// This example code displays the words "Mouse clicked" in the Output panel.
trace("Mouse clicked");
// End your custom code
}   



trace(Name);
trace(Month);

How to use the standard output by Flash Air?

I want to make a command line tool by Flash Air, but there is not any api of AS3 to output content to standard output.

Then, I try to use ANE to solve my problem(By making a windows ane and use C's printf function to output content), but it doesn't work.

Is there any methods to use the standard output by Flash air, or to make a command line tool by Flash Air?

The code of dll written by c++ is:

FREObject add(FREContext ctx, void* functionData, uint32_t argc, FREObject argv[])
{
    int32_t x,y;
    FREGetObjectAsInt32(argv[0], &x);
    FREGetObjectAsInt32(argv[1], &y);


    int32_t result = x + y;
    FREObject resObj;
    FRENewObjectFromInt32(result, &resObj);

    //I want to use the "printf" to print content to the console
    printf("print by dll: the result is %d\n", result);

    return resObj;
}

samedi 20 février 2016

AS3: Flash throwing Type Error #1006 value is not a function for what seems to be no reason; is this a bug?

Flash seems to be screwing with me and is throwing this error:

TypeError: Error #1006: value is not a function.
    at sweg::Force/setTxt()[C:\Users\lamide97\Google Drive\OneDrive\COMP4\sweg\Force.as:459]
    at Main/CheckOnStage()[C:\Users\lamide97\Google Drive\OneDrive\COMP4\Main.as:248]
    at sweg::Force/removed()[C:\Users\lamide97\Google Drive\OneDrive\COMP4\sweg\Force.as:192]
    at flash.display::DisplayObjectContainer/removeChild()
    at Main/init()[C:\Users\lamide97\Google Drive\OneDrive\COMP4\Main.as:310]
    at Main/Start()[C:\Users\lamide97\Google Drive\OneDrive\COMP4\Main.as:107]

for what seems to be no reason. I looked around at several other #1006 TypeError questions but they didn't have the same problem as mine. So I was resolved to fix it myself. Surprisingly it didn't take very long; the solution was a single trace statement. But I'm stumped as to why simply tracing a value solved it.

Here's the premise: I have a Force class that once added to stage will set the text in a textbox on stage with it's magnitude property. The textbox's text it assigns is respective to the Force's name.

Here's the code:

public function setTxt():void
    {
        switch (this.name)
        {
            case "Force 1" :
                _magtText.text = "P";
                _forceFormat.color = 0x33CCFF
                //trace(_magt); If I uncomment this line then everything works
                (this.parent as MovieClip).force1.text = String(Math.round(_magt * 100) / 100);
                //line above is throwing error.
                break;

            case "Force 2" :
                _magtText.text = "Q";
                _forceFormat.color = 0xFF6600;
                (this.parent as MovieClip).force2.text = String(Math.round(_magt * 100) / 100);
                break;

            case "Force 3" :
                _magtText.text = "F";
                _forceFormat.color = 0x003300;
                (this.parent as MovieClip).force3.text = String(Math.round(_magt * 100) / 100);
                break;

            case "Force 4" :
                _magtText.text = "A";
                _forceFormat.color = 0xFF00FF;
                (this.parent as MovieClip).force4.text = String(Math.round(_magt * 100) / 100);
                break;

            case "Tension 1" :
            case "Tension" :
                _magtText.text = "T";
                _forceFormat.color = 0x003300;
                (this.parent as MovieClip).force3.text = String(Math.round(_magt * 100) / 100);
                break;

            case "Tension 2" :
                _magtText.text = "T`";
                _forceFormat.color = 0xFF00FF;
                (this.parent as MovieClip).force4.text = String(Math.round(_magt * 100) / 100);
                break;

            case "Resultant F" :
                _magtText.text = "R";
                _forceFormat.color = 0xFF0000;
                (this.parent as MovieClip).resBox.text = String(Math.round(_magt * 100) / 100);
                (this.parent as MovieClip).resAng.text = roundNum(_degrees.toFixed(3));
                break;

            default :
                _magtText.text = "X";
        }
        _magtText.setTextFormat(_forceFormat);
    }

I suspect it has something to do with the _magt property, because I encountered a similar problem in my Weight subclass that inherits Force prior to this, and the problem seemed to solve itself after I appended some semicolons.

if (_magt >= 0)
    {
        drawForce();
    }
    else
    {
        drawForce(0x33CCFF, 0xCCCCCC, 0.3);
    }

    (this.parent as MovieClip).weightBox.text = roundNum(_magt.toFixed(3))
    (this.parent as MovieClip).particle.mass = _magt;
    //Line above throws a "Call to a possibly undefined method _magt" error. Doesn't work without the semi-colon.
    (this.parent as MovieClip).massNum.text = roundNum(Number(_magt / 9.8).toFixed(3))
    (this.parent as MovieClip).weightSlider.value = _magt;
    //Line above throws the same error; also doesn't work without semi colon.
    (this.parent as MovieClip).massSlider.value = _magt / 9.8

    (this.parent as MovieClip).dragCalc(this);

I don't know why flash would seem to think that the _magt property, which I declared as Number, is a method. I do however have a get magt function but to my knowledge I don't think Flash would confuse the function and property with each other since they don't share a namespace.

What's even more strange is that when I have a force named "Resultant F" it doesn't seem have problems with its _magt but all the other ones do.

My initial guess was that at some point somewhere, _magt was NaN. But I knew that couldn't be possible because the force is instantiated with a _magt of 147, which is what the traced magnitude displayed, and it isn't assigned a new value anywhere else.

I don't know if this is some low-key syntax error, as I'm still a beginner and there may be something hugely obvious that I'm not seeing.

Although technically I've already solved this problem, I'd like to know what's causing it because I have a feeling it might creep up on me later on.

Thank you for reading.