dimanche 26 mars 2017

How Can I convert Parts of Scripts to where it's Readable

I'm trying to Decode some .as and some .hex in order to get the Codes. This Code is from the Game War Commander.

  private static const const_792:Vector.<uint> = new <uint>[16763904,7535299];

  private static const const_1016:Vector.<uint> = new <uint>[530,530];

The part I need help is, How or Where Can I decode the: [16763904,7535299]; In doing so, I think that might be the Unit codes for the Phantom. Here is the Whole class:

public class PhantomReticle extends class_724 {

  private static const const_4425:String = "ui/phantom_unit/PhantomReticle.xml";

  private static const const_5194:String = "phantomReticleA";

  private static const const_3919:String = "phantomReticleB";

  private static const const_792:Vector.<uint> = new <uint>[16763904,7535299];

  private static const const_1016:Vector.<uint> = new <uint>[530,530];

  private static const const_5133:int = 2;

  private static const const_7028:Number = 10;

  private static const const_5629:Number = 100.0;

  private static const const_4926:int = 100;

  private var var_2288:int;

  public function PhantomReticle()
     this.var_2288 = const_4926;

  public function method_8357(param1:int) : void
     this.var_2288 = param1;

  override public function get maxReticlesUsed() : int
     return const_5133;

  override protected function method_2306() : String
     return const_4425;

  override protected function setup() : void

  protected function method_5112() : void
     var _loc1_:Number = this.var_2288 / const_1016[0];
     var _loc2_:Number = this.var_2288 / const_1016[1];
     var_242[0].container.scaleX = _loc1_;
     var_242[0].container.scaleY = _loc1_ * 0.5;
     var_242[1].container.scaleX = _loc2_;
     var_242[1].container.scaleY = _loc2_ * 0.5;

Parsing Javascript variable to AS3

I'm trying to write a simple 2 way chat but got a problem. I'm sure it's very basic but couldn't figure out since I'm new to this.

Below is my JS code to pass a streamID to AS3:

    url: ajaxurl,
    type: 'POST',
    data: 'action=sd_chat_code&chat_code='+chat_code,
    success: function(data){
    error: function(data) {

and in AS file, I got the streamID passed through as below:

public function streamCompanion(data):void {
    var netStreamObj:NetStream = new NetStream(_nc);

the variable "data" above return "12345" correctly, I tried to output is via JS and there's nothing wrong:

ExternalInterface.class("function() { console.log("+data+") }")

the problem is netStreamObj.play(data) not working, but if I manually type in netStreamObj.play('12345'), it's working correctly.

Any advice would be greatly appreciated.

Array: Term is undefined & has no properties

c is just a letter that I used for the array set. The bold line is the main problem.

function coinsCollect()

    This line simply calls on all the objects in the specified array (i.e. coins) amd applies the codes to all objects in the array.

    for(var c:int = 0; c < coins.length; c++) 
        for more precise collision, use hitTestPoint

sound effect for coin sounds; same sound channel is used for all sound effects
            //frame 2 of coins is a blank keyframe

ActionScript 3 mx mx:HorizontalList set columns per row

I have a Flex HorizontalList like so:

<mx:HorizontalList id="myList" width="1462" height="878" columnCount="3" rowHeight="475" columnWidth="350" dataProvider="{floorPlans}" itemRenderer="FloorplanItems">


I am trying to set 3 columns per a row, I thought columnCount would do it, but either its not working and or is not doing what I thought it would be doing.

How can I set 3 columns per a row?

samedi 25 mars 2017

Actionscript 3 setStyle is not a function

I am trying to style a Flex 4 GridItem using actionscript, I have tried the following:

    height="878" width="1920"
    xmlns:s="library://ns.adobe.com/flex/spark" xmlns:local="*" creationComplete="addStyles()">


            public var selectedLot:String = "";

            private function addStyles():void
                testBorder.setStyle("borderThickness", "3");

but I get the following error:

setStyle is not a function.

Am I missing something?

The GridItem is inside a repeater.

Adobe Flex 4.6 Remove Gap in between GridItems

I am using Flex 4.6 and I am fairly new to it...I am using a Grid and inside my Grid is a GridRow and inside this GridRow are 3 GridItems, each item has a border, but there is a gap in between each item and I can't figure out how to get ride of them...here is my code:

                                                                        <mx:GridItem width="101" height="52.25" horizontalAlign="center" verticalAlign="middle" borderStyle="solid" borderColor="gray">
                                                                            <mx:Image source="assets/ruler-icon.png" />
                                                                            <s:Label text="{r.currentItem.sqft} sq.ft." fontSize="10" color="#808080" fontFamily="Helvetica" />
                                                                        <mx:GridItem width="101" height="52.25" horizontalAlign="center" verticalAlign="middle" borderStyle="solid" borderColor="gray">
                                                                            <mx:Image source="assets/bed-icon.png" />
                                                                            <s:Label text="{r.currentItem.bed}" fontSize="10" color="#808080" fontFamily="Helvetica" />
                                                                        <mx:GridItem width="101" height="52.25" horizontalAlign="center" verticalAlign="middle" borderStyle="solid" borderColor="gray">
                                                                            <mx:Image source="assets/bath-icon.png" />
                                                                            <s:Label text="{r.currentItem.bath}" fontSize="10" color="#808080" fontFamily="Helvetica" />

Any help will be much appreciated.

How can I efficiently update animations in my game?

For each character skin, it has 4 MovieClips corresponding to each possible direction (up, down, left, and right).


For my Player 1 skin, it would be like this.

Player 1 Up Animation (P1UAnim_mc)

Player 1 Down Animation (P1DAnim_mc)

Player 1 Left Animation (P1LAnim_mc)

Player 1 Right Animation (P1RAnim_mc)

Now, the way my movement works is we have a Movieclip that matches the size of the animations (they don't change in size), and this Movieclip is invisible, and this is what moves when we tell it to (I call it a player position keeper). This is done by clicking a direction on the DPAD, where we then move the player in the appropriate direction with the coressponding walkspeed for that direction, then we check if we hit something in my array of obstacles. If we did, we move the player back.

So now that we have that out of the way, I need to have animations that correspond to the direction and character skin the player is using/going in.

One idea I had, had an event listener for every time we enter a frame, where we check what charSkin the player is using, then check the direction, and then add the appropriate animation. We do not need to update the animations x,y coordinates because in their class file it is always updating itself, and knows when to remove itself. So all I need to do is find the appropriate time to add it and leave the rest to the animation's class.

My problem with this technique I tried was the code was really difficult to understand, it was a barrage of if else statements checking the factors mentioned above.

Here is my MovementReworked class which does not include the animations, so that you guys can actually read it. If you want me to edit the post and add the Movement class with sloppy animations code as well, I will, but it's pretty unreadable.

    import flash.display.Stage;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.TouchEvent;
    import flash.net.dns.AAAARecord;
    import flash.ui.Multitouch;
    import flash.ui.MultitouchInputMode;

    public class MovementReworked extends MovieClip
        public function MovementReworked(main:Game)
            // I will be changing these addChilds in the future
            // Just ignore it for now

            Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

            Game.playerPosKeeper_mc.x = 384;
            Game.playerPosKeeper_mc.y = 46;

            main.up_dpad.x = 55;
            main.up_dpad.y = 336;

            main.down_dpad.x = 57;
            main.down_dpad.y = 432;

            main.left_dpad.x = 19;
            main.left_dpad.y = 372;

            main.right_dpad.x = 118;
            main.right_dpad.y = 372;

            main.menu_dpad.x = 61;
            main.menu_dpad.y = 377;

            main.run_dpad.x = 684;
            main.run_dpad.y = 369;

            main.barrierRoof1_game.x = 0;
            main.barrierRoof1_game.y = 0;

            main.barrierRoof2_game.x = 0;
            main.barrierRoof2_game.y = 470;

            main.barrierRoof3_game.x = 0;
            main.barrierRoof3_game.y = 320;

            main.barrierSide1_game.x = 0;
            main.barrierSide1_game.y = 0;

            main.barrierSide2_game.x = 790;
            main.barrierSide2_game.y = 0;
            // I will be changing these addChilds in the future

            for each (var aButton:MovieClip in main.Buttons)
                aButton.addEventListener(TouchEvent.TOUCH_BEGIN, onDown);
                aButton.addEventListener(TouchEvent.TOUCH_OUT, onUp);
                aButton.addEventListener(TouchEvent.TOUCH_END, onUp);

            function onDown(e:TouchEvent):void
                switch (e.currentTarget)
                    case main.up_dpad :
                        Game.dir = 1;
                        Game._Direction.x = 0;
                        Game._Direction.y = Game.upWalkspeed;
                    case main.down_dpad :
                        Game.dir = 2;
                        Game._Direction.x = 0;
                        Game._Direction.y = Game.downWalkspeed;
                    case main.left_dpad :
                        Game.dir = 3;
                        Game._Direction.x = Game.leftWalkspeed;
                        Game._Direction.y = 0;
                    case main.right_dpad :
                        Game.dir = 4;
                        Game._Direction.x = Game.rightWalkspeed;
                        Game._Direction.y = 0;
                if (Game.idle)
                    Game.idle = false;
                    addEventListener(Event.ENTER_FRAME, onFrame);
            function onFrame(e:Event):void
                movePlayer(Game._Direction.x, Game._Direction.y);

            function onUp(e:TouchEvent):void
                Game.idle = true;
                removeEventListener(Event.ENTER_FRAME, onFrame);

            function movePlayer(movementX:Number, movementY:Number):void
                var originalX:Number = Game.playerPosKeeper_mc.x;
                var originalY:Number = Game.playerPosKeeper_mc.y;
                Game.playerPosKeeper_mc.x +=  movementX;
                if (checkCollision())
                    Game.playerPosKeeper_mc.x = originalX;
                Game.playerPosKeeper_mc.y +=  movementY;
                if (checkCollision())
                    Game.playerPosKeeper_mc.y = originalY;

            function checkCollision():Boolean
                for each (var StageCollisions:MovieClip in main.StageCollisions)
                    if (Game.playerPosKeeper_mc.hitTestObject(StageCollisions))
                        return true;
                        Game.idle = true;
                return false;

I want to make a wall by by repeating function by as3

I am student who still studying ActionScript 3.0 (So i am new on the language).

I want to make a game by creating Random questions, When It has been clicked in wright answer it will disappear ,and when it is wrong it will make the first step of wall, looping this process until several times . (for example : after 9 questions).

I made a function for one question ,but I want to do it again !

So How I can make this function below looping several times without affect the previous question please?

Thank you in Advance !

package  {
import flash.events.Event;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextFieldAutoSize;

public class Process extends MovieClip {

    public function Process() {
        // constructor code


    function create ():void
        var A_Que:Array= [
"Complete the word: ___________ historic.",
"Cars ___________ become more efficient in the future (90%).",
"An ___________ surface is not flat.",
"The next generation ___________ use more digital devices (70%).",
"___________ are sometimes afraid of new technology.",
"Complete the word: ___________ write.",
"Robots are machines ___________ can move on their own.",
"Scientists have ___________  to make this technology work.",
"Complete the word: ___________ safe.",
"There are many ___________ discoveries every year.",
"A badly programmed robot suit could ___________ the wearer.",
 "Imagine ___________ your own ironman suit.",
 "Inventions cost a lot of ___________ .",
"Do you think this ___________ is a good idea?",
"Complete the word: ___________ graduate.",
"Complete the word: ___________ use.",  
"We ___________ see humans walking on Mars soon (50%).",
"What ___________ you do if you owned a flying car?"]

var i :Number;
i = Math.round (Math.random()*4);
trace (i);
trace (A_Que[i]);

var mv_box :box = new box ();
stage.addChild (mv_box);
mv_box.x = 282;
mv_box.y = -25;
mv_box.height = 47;
mv_box.width = 459;
mv_box.txt.text= A_Que[i];
mv_box.txt.autoSize = TextFieldAutoSize.CENTER;

var answer_box:answerBox = new answerBox ();
stage.addChild (answer_box);
answer_box.width= 77.85;
answer_box.height = 30;
answer_box.y = -25;

switch (i)
     case 0 :answer_box.x = 324.70;break;
     case 1 : answer_box.x = 154.20; break;
     case 2 : answer_box.x = 232.65; break;
     case 3 : answer_box.x = 248.15; break;
     case 4 : answer_box.x = 141.65;break;
     case 5 :answer_box.x = 331.65;break;
     case 6 : answer_box.x = 273.65; break;
     case 7 : answer_box.x = 230.15; break;
     case 8 : answer_box.x = 335.65; break;
     case 9 : answer_box.x = 259.00;break;
     case 10 :answer_box.x = 374.50;break;
     case 11 : answer_box.x = 231.50; break;
     case 12 : answer_box.x = 361.00; break;
     case 13 : answer_box.x = 291.50; break;
     case 14 : answer_box.x = 320.00;break;
     case 15 :answer_box.x = 338.00;break;
     case 16 : answer_box.x = 153.50; break;
     case 17 : answer_box.x = 187.00; break;

addEventListener (Event.ENTER_FRAME, lol);  
btn_right.addEventListener (MouseEvent.CLICK, BtnClick);
btn_wrong.addEventListener (MouseEvent.CLICK ,BtnClick1);

function lol (event: Event):void
if ((mv_box.y <(stage.stageHeight - mv_box.height) &&(answer_box.y<(stage.stageHeight - answer_box.height)))){
if((!mv_box.hitTestObject(line)) && (!answer_box.hitTestObject(line)) )
    mv_box.y += 2;
    answer_box.y += 2;


 function BtnClick (evt:MouseEvent):void



 function BtnClick1 (evt:MouseEvent):void
 mv_box.x = 282;
 mv_box.y = 288;
 answer_box.y = 288;



Error #1010: A term is undefined and has no properties. at :MainTimeline/loop()_fla.MainTimeline::frame1:190]

im making a platform game and i can't figure out what's the problem specifically it says the problem is in this line:

if(background_mc.platform_mc.hitTestPoint(player_mc.x-xDistance,player_mc.y, true))

.hitTestPoint hitting multiple test points (AS3)

I can write a hitTestPoint trigger as such

if (mc1.hitTestPoint(mc2.x, mc2.y, true)) 

and if I want to have multiple test points I can write something like

if (mc1.hitTestPoint(mc2.x, mc2.y, true) || mc1.hitTestPoint(mc2.x-5, mc2.y, true) || mc1.hitTestPoint(mc2.x+5, mc2.y, true))

I am wondering though if there is anyway to define multiple hitpoints in the same statement. I've tried something like this with no luck...

if (mc1.hitTestPoint((mc2.x, mc2.y, true) || (mc2.x, mc2.y, true))) 


if (mc1.hitTestPoint((mc2.x+5 || mc2.x-5), mc2.y, true)) 

...and many others but nothing seems to work. It is a pain to write the new points out for the same object over and over especially when you have 20+ hitpoint that you need to check for. Is there any way to add multiple points in one statement?

vendredi 24 mars 2017

SWF file has timer that runs faster in debug player than release player (Adobe Animate, AS3)

I have an interactive animation that consists of a button and some lights that are lit in a sequence. The animation also has a timer that shows the passage of time to illustrate the interval between light transitions, so the user knows how much time has passed between each transition in the sequence (it took x amount of time to go from light 'a' to light 'b'). The button controls the speed.

I implemented the timer using the Timer class in AS3:

var MyTimer:Timer = new Timer(1);

Which means the timer should fire every millisecond.

Now, I am aware the this is nowhere near accurate, due to frame rate (24fps) and the fact that it has to run the code inside the handler function. But I am not going for an accurate timer, in fact I do need it to go slower so the user can see the time between transitions, a scaled/slowed timer if you will. The current time is displayed in a dynamic text field.

As is, when using the debug player in Adobe Animate, the speed of the timer runs at about 1/10th normal speed, taking about 10 seconds to show that a second has passed, which incidentally is great for my purposes. However, this animation will be used in a PDF, in which case, a release player of Flash will be used; and in the release version, the timer appears to be about half as fast, about 1/20th the speed, taking about 20 or more seconds to show that a second has passed.

I'm not sure why this is. How do I get the swf file to be played so that the timer behaves the same in both the debug and release versions of the Flash Player?

I have tried unticking 'Permit debugging' and ticking 'Omit trace statements' (and every combination of un/tick) in the Publish Settings as well as all the Hardware acceleration options.

I've also implemented a FPS counter as suggested here by user 'kglad':

published swf file is a lot slower than the 'test' mode?

But both debug and release versions show the FPS at 23-24.'kglad' gives the last reply in the thread as "the debug players are slower than the non-debug players". I'm not sure what he meant by this as this seems to be the opposite problem that me and the OP of that thread are having, unless s/he meant using the players in a browser.


How do I get a timer to behave the same in both the debug and release version of the Flash player?

Thanks in advance for any suggestions.

Getting child targets for mouse click event in OpenFL

I have a stage with multiple child object of different types. I have an event listener on the stage. I'd like to get the target child object on a mouse click so I can handle clicks on different object types.

Something along the lines of:

stage.addEventListener(MouseEvent.CLICK, onClick);

function onClick(e:Event):Void
    var target = e.target
    // if target type is Foo
    //     target.aFooMethod();
    // else if target type is Bar
    //     target.aBarMethod();


Whats the correct way of doing this? Tracing e.target seems to print the correct object type but I am unable to call any of the objects methods.

I vaguely remember in actionscript 3 being able to use target.name but return null in this case.

Many thanks.

Thanks fot any help.

Accessing properties after using getdefinitionbyname

I'm trying to access properties from a class like this:

public class Oak extends Tree //base class for tree classes
    public static const CLASS_NAME:String = getQualifiedClassName(Oak);

    public var branches:Array;

    public function Oak() 
        branches = 

The class trying to access the variable is shown here:

public class TreeTest extends BaseScreen //just extends Sprite, TreeTest is shown on the stage
    public var oak:Tree;

    private var inc:int;

    public function TreeTest(pModel:Model) 
        model = pModel;

        oak = model.getTree(Oak.CLASS_NAME);
        inc = 0;

        this.addMouseClickListener(0, treeHandler); //from BaseScreen

    private function treeHandler(e:MouseEvent):void 
        this.displayText.text = oak.branches[inc];

and the model is shown below:

public class Model 
    public var treeArray:Array;

    public function Model() 
        treeArray = new Array();

    public function createTree(pClassName:String):void 
        var name:String = pClassName;
        var ClassReference:Class = getDefinitionByName(name) as Class;
        var classInstance:Tree = new ClassReference;
        treeArray.push([name, classInstance]);

    public function getTree(pClassName:String):Tree
        var treeName:String = pCharacterClassName;
        var match:Boolean = false;
        var matchArrayRef:int = 0;

        for (var i:int = 0; i < treeArray.length; i++) 
            if (match == true) 

            if (treeArray[i][0] == treeName) 
                match = true;
                matchArrayRef = i;
                match = false;

        if (match == false) 
            return null; 
            return treeArray[matchArrayRef][1];

When I ran this, I got the error "Access of possibly undefined property branches through a reference with static type Tree".

After searching for a solution, I discovered that basically means that the branches array was not in the Tree class. To confirm this, if I went and took public var branches:Array away from the Oak class and put it in the Tree class, the code worked.

Why can I not access variables defined in the Oak class, and have to put everything in the Tree base class? Even if I change var classInstance:Tree to var classInstance:Oak, or even var classInstance:Object, I still get the same error if the array is in the Oak class, not the Tree class.

Like, if I create a new class Pine which would also extend Tree, do I have to put all of Pine's variables in the Tree class too?

jeudi 23 mars 2017

Actionscript, improving xor performance?

I am using the below code to process some large files.

var joinedBytes:ByteArray = new ByteArray;
joinedBytes.length = _chunkSize;

for (var i:Number = 0; i < _chunkSize; i++) {

Its taking about 2.5 seconds to process 10mb of data on a desktop.

Is this normal performance?

Does any way exist to speed it up?

I think that some of the time is writing to the byte array.

ActionScript 3.0 Switching Video by pressing a key

I'm writing a simple program that switch from a video to another when I press two different key. If I press the key F it will be displayed the video1 if I press the key 2 it will be displayed the video 2. While the video1 or the video2 are displayed if I press the key F or 2 I switch between the two video. I have a problem. If I press quickly 2 and F the fps start to drop and after some quick press of 2 and F the .swf crash. I think that it's a problem of my code cause it'isnt optimized. The base idea is that everytime that the user press F or 2 key while a video is displayed I close the stream of that video and I start to stream the other video and so on. This is the code:

package {
import flash.display.MovieClip;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.events.AsyncErrorEvent;
import flash.media.Video;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.utils.getTimer;

public class MainDisplayDifferentVideoOnCLick extends MovieClip {

    public function MainDisplayDifferentVideoOnCLick() {

    public function keyPressed(): void {
        stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
        function onKeyDown(myKey: KeyboardEvent): void {
            if (myKey.keyCode == 70) {
            if (myKey.keyCode == 50) {

    function playVideo1(): void {
        var networkConnection: NetConnection = new NetConnection();
        var networkStream: NetStream = new NetStream(networkConnection);
        networkStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, errorHandler);
        function errorHandler(error1: AsyncErrorEvent): void {
            // ingoro l' evento
        var myVideo1: Video = new Video();
        myVideo1.width = 1920;
        myVideo1.height = 1080;
        stage.addEventListener(KeyboardEvent.KEY_DOWN, on2Down);
        function on2Down(ev: KeyboardEvent): void {
            if (ev.keyCode == 50) {

    function playVideo2(): void {
        var networkConnection: NetConnection = new NetConnection();
        var networkStream: NetStream = new NetStream(networkConnection);
        networkStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, errorHandler);
        function errorHandler(error1: AsyncErrorEvent): void {
            // ingoro l' evento
        var myVideo2: Video = new Video();
        myVideo2.width = 1920;
        myVideo2.height = 1080;

        stage.addEventListener(KeyboardEvent.KEY_DOWN, onFDown);
        function onFDown(ev: KeyboardEvent): void {
            if (ev.keyCode == 70) {
    public function fpsNumber(): void {
        var frames: int = 0;
        var prevTimer: Number = 0;
        var curTimer: Number = 0;

        this.addEventListener(Event.ENTER_FRAME, performFrameTest);

        function performFrameTest(e: Event): void {
            frames += 1;
            curTimer = getTimer();
            if (curTimer - prevTimer >= 1000) {
                trace("FPS: ");
                trace(Math.round(frames * 1000 / (curTimer - prevTimer)));
                prevTimer = curTimer;
                frames = 0;


Do you have any advice? Thank you!

Actionscript error: syntax error, unexpected '<'

When I try to compile this Actionscript code code with 'as3compile.exe', I get this error :



    public class Main extends Sprite
        private var myvct:uint = 0;
        public function Start():void
            myvct = new Vector.<uint>();


        public function Main():void


error: syntax error, unexpected '<'

Can anyone please tell me whats is wrong here?

mercredi 22 mars 2017

Is there any way to predict next random number?

I want to make roulette wheel in ActionScript3. I have full source of other roulette, but it generates next number after spin(Eventclick), so I know next number as I click spin button(The value changes faster than visual, before ball stops rotating I know where it falls). In my roulette I want to know what will be next number, before player click spin button. Sorry if I can't explain what I want exactly, but hope you will understand.

package de.polygonal.core.math.random {

public class Random extends Object

    public function Random() : void
    }// end function

    public static function rand() : int
        return Math.random() * 2147483647;
    }// end function

    public static function randRange(param1:int, param2:int) : int
        var _loc_3:* = param1 - 0.4999;
        var _loc_4:* = param2 + 0.4999;
        return _loc_3 + (_loc_4 - _loc_3) * Math.random() + 16384.5 - 16384;
    }// end function

    public static function randSym(param1:int) : Number
        var _loc_2:* = -param1 - 0.4999;
        var _loc_3:* = param1 + 0.4999;
        return _loc_2 + (_loc_3 - _loc_2) * Math.random() + 16384.5 - 16384;
    }// end function

    public static function randBool() : Boolean
        return Math.random() < 0.5;
    }// end function

    public static function frand() : Number
        return Math.random();
    }// end function

    public static function frandRange(param1:Number, param2:Number) : Number
        return param1 + (param2 - param1) * Math.random();
    }// end function

    public static function frandSym(param1:Number) : Number
        var _loc_2:* = -param1;
        return _loc_2 + (param1 - _loc_2) * Math.random();
    }// end function



Having an issue with Flash Actionscript3

Wondering if you guys can help me. I've used online tutorials to create the following.

I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.

Basically, my question is "How do I add a button to the "Flappy" Scene without having a whole bunch of errors. Each time i try to do it and run a test, I'm getting a crazy flashing .swf

Main.as ("Flappy" Scene3)

    import flash.display.MovieClip;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    import flash.events.Event; //used for ENTER_FRAME event
    //import flash.events.MouseEvent;

    public class Main extends MovieClip{

        //These are all of the constants used.

        const gravity:Number = 1.5;            //gravity of the game. How fast ball falls
        const dist_btw_obstacles:Number = 300; //distance between two obstacles
        const ob_speed:Number = 8;             //speed of the obstacle
        const jump_force:Number = 15;          //force with which it jumps

        var player:Player = new Player();      
        var lastob:Obstacle = new Obstacle();  //varible to store the last obstacle in the obstacle array
        var obstacles:Array = new Array();     //an array to store all the obstacles
        var yspeed:Number = 0;                 //A variable representing the vertical speed of the bird
        var score:Number = 0;                  //A variable representing the score

        public function Main(){

        function init():void {
            //initialize all the variables
            player = new Player();
            lastob = new Obstacle();
            obstacles = new Array();
            yspeed = 0;
            score = 0;

            //add player to center of the stage the stage
            player.x = stage.stageWidth/2;
            player.y = stage.stageHeight/2;

            //create 3 obstacles ()

            //Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
            stage.addEventListener(KeyboardEvent.KEY_UP, key_up);

        private function key_up(event:KeyboardEvent){
            if(event.keyCode == Keyboard.SPACE){
                //If space is pressed then make the bird
                yspeed = -jump_force;

        function restart(){
                for(var i:int = 0; i < obstacles.length; ++i){
                    if(contains(obstacles[i]) && obstacles[i] != null)
                    obstacles[i] = null;

        function onEnterFrameHandler(event:Event){
            //update player
            yspeed += gravity;
            player.y += yspeed;

            //restart if the player touches the ground
            if(player.y + player.height/2 > stage.stageHeight){

            //Don't allow the sheep to go above the screen
            if(player.y - player.height/2 < 0){
                player.y = player.height/2;

            //update obstacles
            for(var i:int = 0;i<obstacles.length;++i){

            //display the score
            scoretxt.text = String(score);

        //This functions update the obstacle
        function updateObstacle(i:int){
            var ob:Obstacle = obstacles[i];

            if(ob == null)
            ob.x -= ob_speed;

            if(ob.x < -ob.width){
                //if an obstacle reaches left of the stage then change its position to the back of the last obstacle

            //If the bird hits an obstacle then restart the game
            if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
               || ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
               || ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
               || ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){

            //If the bird got through the obstacle without hitting it then increase the score
            if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
                ob.covered = true;

        //This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
        function changeObstacle(ob:Obstacle){
            ob.x = lastob.x + dist_btw_obstacles;
            ob.y = 100+Math.random()*(stage.stageHeight-200);
            lastob = ob;
            ob.covered = false;

        //this function creates an obstacle
        function createObstacle(){
            var ob:Obstacle = new Obstacle();
            if(lastob.x == 0)
            ob.x = 800;
            ob.x = lastob.x + dist_btw_obstacles;
            ob.y = 100+Math.random()*(stage.stageHeight-200);
            lastob = ob;

Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.


    import flash.events.MouseEvent;


    function cloudy (e:MouseEvent){
        cloud1.x = cloud1.x + 10;
        cloud2.x = cloud2.x - 10;


    pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    function mouseDownHandler(event:MouseEvent):void {
        gotoAndStop(1, "SheepyPong");

    dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
    function mouseDownHandler3(event:MouseEvent):void {
        gotoAndStop(1, "Flappy");

This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:

var upPressed:Boolean = false;
var downPressed:Boolean = false;

var velocityX:Number = 5;
var velocityY:Number = 5;

movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);

function fl_MoveInDirectionOfKey(event:Event)
    if (upPressed)
        movieClip_1.y -= 5;
    if (downPressed)
        movieClip_1.y += 5;
    sheep.x += velocityX;
    sheep.y += velocityY;

    if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
        velocityY *= -1

    if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
        velocityX *= -1;

    if (sheep.x < 0) {
        score2.text = (int(score2.text) +1).toString();
        sheep.x = 275;
        sheep.y = 200;
        velocityX *= -1;

    if (sheep.x > stage.stageWidth) {
        score1.text = (int(score1.text) +1).toString();
        sheep.x = 275;
        sheep.y = 200;
        velocityX *= -1;

    AI.y = sheep.y;

function fl_SetKeyPressed(event:KeyboardEvent):void
    switch (event.keyCode)
        case Keyboard.UP:
            upPressed = true;
        case Keyboard.DOWN:
            downPressed = true;


function fl_UnsetKeyPressed(event:KeyboardEvent):void
    switch (event.keyCode)
        case Keyboard.UP:
            upPressed = false;
        case Keyboard.DOWN:
            downPressed = false;

    }//end of switch
}//end of function 

home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
    gotoAndStop(1, "Scenery");

I'm also getting this error in output when I run it. It's not actually affecting the outpu

TypeError: Error #1009: Cannot access a property or method of a null object reference. at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]

Platform game. Jump to next level in next frame

I create a platform game with 20 levels for android devices. Every level has different walking platforms and new enemies with differents properties. I have the first frame with 20 buttons , The first button go to first level(frame 2) the second button go to second level(frame 3) and goes on until the final level in frame 21. I write all of my code in frame 2(level 1) player movement , enemies properties , coins , life etc. When the player die or the player complete the stage i go to frame 1 and im ready to click to level 2 button , go to second stage in frame 3. So , what part of my code i must transfer to second level ?

Here is part of my code in second frame. (i show only one enemy(medouza) and the controls that i move the player because is a large code)

function lbtisdown(e:TouchEvent)
  ldown = true;
function lbtisup(e:TouchEvent)
  ldown = false;
function rbtisdown(e:TouchEvent)
  rdown = true;
function rbtisup(e:TouchEvent)
  rdown = false;
function kbtisdown(e:TouchEvent)
  kdown = true;
function jbtisdown(e:TouchEvent)
  if (! jdown && onground && ! dizbl)
  jdown = true;
function fbtisdown(e:TouchEvent)
  fdown = true;
var movers = new Array(bg.ground.platkat0,bg.ground.plator0,bg.ground.platkat1,bg.ground.plator1,bg.ground .plator2,bg.ground.plator3);
var movedirs = new Array(0,1,0,1,1,1);
var movelimits = new Array([-57.5,60],[1853,2021],[-57.5,243],[1935,2072],[2548,2877],[2982,3073]);
var medouzaArr = new Array();
function addMedouza(med)
  med.xvel = 0;
  med.yvel = 0;
  med.hitpoints = 20;
  med.startAttack = 0;
  med.fireAttack = 3;
  med.sp = Math.random() * .7 + .7;
  med.dir = Math.floor(Math.random() * 2);
  med.locksp = med.sp;
function FramesEvents(e:Event)
function moveMedouza()
  for (var k1=0; k1<medouzaArr.length; k1++)
  var m = medouzaArr[k1];
  m.x +=  m.xvel;
  m.xvel *=  .3;
  m.y +=  m.yvel;
  m.yvel +=  GRA;
  if (m.x > savvito.x)
  m.scaleX = -1;
  if (m.x < savvito.x)
  m.scaleX = 1;
  if (m.startAttack > 4)
  m.fireAttack = 1 + Math.floor(Math.random() * 2);
  m.startAttack = 0;
  if (m.fireAttack == 0)
  if (m.fireAttack == 1)
  if (m.fireAttack == 2)
  if (m.medouza.currentFrame == 1 && m.medouza.medouza_iddle.currentFrame == m.medouza.medouza_iddle.totalFrames)
  m.startAttack +=  1;
  if (m.medouza.currentFrame == 2 && m.medouza.medouza_jump.currentFrame == m.medouza.medouza_jump.totalFrames)
  m.fireAttack = 0;
  var e = bg.addChild(new enemy1());
  e.x = m.x;
  e.y = m.y;
  if (m.medouza.currentFrame == 3 && m.medouza.medouza_attack.currentFrame == m.medouza.medouza_attack.totalFrames)
  m.fireAttack = 0;
  if (m.medouza.currentFrame == 3 && m.medouza.medouza_attack.currentFrame == 12)
  var s = bg.addChild(new parentsmos());
  s.x = m.x;
  s.y = m.y;
  if (m.scaleX == 1)
  s.scaleX = 1;
  if (m.scaleX == -1)
  s.scaleX = -1;
  if (savvito.hitTestObject(m.med_hit) && ! savvito.hit && ! die)
  savvito.hit = true;
  savvito.hitcv = 0;
  if (savvito.x < m.x)
  xvel = -8;
  xvel = +8;
  yvel = -6;
  if (savvito.hero.currentFrame == 4 && savvito.hero.attack.hitTestObject(m.med_box) && savvito.hero.attack.currentFrame == 6)
  m.hitpoints -=  15 + KnifeDamage;
  if (m.scaleX == 1)
  m.x = 700;
  if (m.scaleX == -1)
  m.x = 100;
  if (m.hitpoints <= 0)
  bg.stageClear.x = m.x;
  bg.stageClear.y = m.y + 7;
function completeStage()
  if (savvito.hitTestObject(bg.stageClear)&&numKey >= 5)
  kdown = false;
  ldown = false;
  rdown = false;
  jdown = false;
  dizbl = false;
  for (var rk1=0; rk1<medouzaArr.length; rk1++)
  var rm = medouzaArr[rk1];
  if (medouzaArr.length == 0)
  fl_CountDownTimerInstance.removeEventListener(TimerEvent.TIMER, fl_CountDownTimerHandler);
  fl_Countstart.removeEventListener(TimerEvent.TIMER, fl_CountDownstart);
function goto2()
  medouzaArr.length = 0;
  movers.length = 0;
  movedirs.length = 0;
  movelimits.length = 0;
  if (fl_SecondsElapsedw > 5 && herohitpoints <= 29)
  fl_TimerInstancew.removeEventListener(TimerEvent.TIMER, fl_TimerHandlerw);
  if (fl_SecondsElapsedw == 3 && herohitpoints < 29)
  savecoins.data.banksavecoins = coinscount + buycoins;
function empty1(e:Event)

Convert AS2 Code to AS3 Format

please help me out converting the code below into as3. I have no ideea what is "SHEMA" , "BASE", "GLANCE" etc for AS3. THanks a lot. This code is being written inside a movie clip.

function CopyFromShema(sframe)
    GLANCE.filters = SHEMA.GLANCE.filters;
    BASE.filters = SHEMA.BASE.filters;
    CAPTION.filters = SHEMA.CAPTION.filters;
SHEMA._visible = false;
BASE.scale9Grid = new flash.geom.Rectangle(10, 10, 100, 5);
GLANCE.scale9Grid = new flash.geom.Rectangle(10, 6, 100, 2);
onRollOver = function ()
onRollOut = function ()
onPress = function ()
onRelease = function ()
onDragOver = function ()
onDragOut = function ()

mardi 21 mars 2017

Adobe AIR and ACS3.0 - best tools for testing native apps?

i developed an Adobe Flash cs6 ,AIR for ios native app and i would like to ask if anyone has to suggest any straight forward tools for functional testing or unit and maybe other types of testing .

Click event on HTML Element of htmlText Property of MovieClip

I have few anchor tags created inside the htmlText property of a MovieClip object. I want to get the event dispatched whenever user clicks on any one of the anchor tag.

Example code:

myMovieClip.htmlText = "<a href=\"somelink1\">somelabel1</a><br/><a href=\"somelink2\">somelabel2</a>";

Universal Button AS3

how can I make a button that works for all scene and frame even tho I skipped the code layer.

For an example,

Button A on Scene 1- Normal Button Button B on Scene 2, Layer 1- Normal Button Button C on Scene 2, All layer - Universal Button

Example - Click Button A to go to scene that Contain Button B and Button C. Button C will work if Button A go to the first layer that contain the code for the button C. But I make another button on the same scene with Button A, but the new button take the user to Scene 2 , layer 3, for an example, the C Button wont work anymore because it skipped the code. How can I do button that works for all scene and layer?

lundi 20 mars 2017

Updating Android Application in Play Store Signing issue

I'll try my best to convey what my problem is, but I am having issues updating a clients application that is currently in the Play Store. The old version of the app was created by different developers.

  • The previous version of the app by the looks of things was created using Adobde Air, I don't have any experience at all with Adobe Air, so not too sure about the signing process with the APKs.

  • My new version is a new project (with same package name) created in Android Studio.

  • I obviously need to sign the release APK with the same certificate as the previous version. Can I do this via Android Studio using the Build > Generate Signed APK?

  • Will the previous developers have to provide a .keystore or .jks file? as I said i'm not sure how the signing process works when using Adobe Air.

Any help would be appreciated.


i want to choose and send file with actionscript with android device

i want to select a local file from android device and send or upload it to a server by using actionscript 3 and using animate cc. Also i want to use this in an android application.

is there anyone can help me?

How to add large image into pdf (in multiple pages) using alivepdf in flex?

I want to add one large image into pdf (in multiple pages). For that i used image snapshot for image. I want to split complete byte array into chunks and using addimage i want to add it into pdf in multiple pages. Thanks in advance.

Intelijj IDEA: Autocompletion on spacebar does not work

IntelliJ IDEA (ActionScript, SDK: air + asc 2.0).

Need auto-completion on the SPACE:

myVa -> [SPACE] -> myVariable

Now when I press on the spacebar just insert a whitespace. Input , . ; works as it should. The problem occurs in .as files. In java, xml files everything works fine.

Option is enabled (see screenshot). Intellij IDEA autocompletion settings

Block external access to swf

I have implemented an SWF application which I host to my website and use object and embed tags to load it in.

I observed that the same SWF file is referenced by external websites using the above html tags. Is there a way to block these references?

I tried setting X-Frame-Options to SAMEORIGIN but it didn't work.

Thank you in advance.

Can I manipulate a single array from multiple classes in AS3?

I have a class which contains an array. I seem to be able to manipulate that array fine from multiple classes, but it is not without bugs. In my debugging efforts, I came across this which makes me think that what I'm trying to do is the "wrong" way. Am I to understand that I can access an array from multiple classes (via getter/setter functions or making it a public property) but that if it is manipulated by 2 different classes in one frame/loop/tick, that the Array "reference" (or whatever) will not be up to date across all "references"?

If I've understood this correctly, a simple "yup" will do. If I'm missing something, please help.

Any tips on how to structure a program so that you don't run into this kind of issue?

dimanche 19 mars 2017

Using stop in action script 3.0 for two objects

I have an instance of Gear and one of bLine. When the Gear gets on the bLine, they both start moving simultaneously. I am trying to stop both of them at one frame, I don't want the objects to go off the stage. Since my gear's move was created through a motion tween and my bLine moves through a function, I am not sure how that can be accomplished.

Code inside of the Gear instance:

var ev2:Event = new Event("transfer");


Code inside of bLine:

import flash.events.Event;


function Move(e:Event):void {


Main timeline:


function transferGear(e:Event) {


I don't know if there is a way how I could stop the bLine inside of the Gear instance, in order to be able to stop both objects at the same time.

Passing values from c# to actionscript 3 and crossdomain questions

I have a c# console application that I want to use for a game server the client is being written is as3. I am going to embed the swf into a c# form later. I have a couple questions, I'm really hoping someone can help me figure this out. Currently I have it set up to send a request to log in to the server, at which point the server checks information you put in the username and password fields and verifies the information. If you are authenticated you get connected. My issue is I can't figure out how to send specific information back to flash, such as a string or int. I want to do this for things like displaying user stats for example. I looked at many tutorials but most are about using a flash application that is embedded in a c# server application, and does not operate the same way I need it to.

I just want to send a string or int from my c# server to my flash application that I have retrieved from mysql. so if anyone can just show me how to send a string or int to flash as a raw value please let me know :)

If you can please post a snippet of code... I am still very new as3 c# communication.

also if you need the source please contact me on skype Skype = Serifaz2 I don't want to just publicly post it ... sorry :(

error #1009 addChld() as3 with loop

when i try to addChild my class it says "Cannot access a property or method of a null object reference. at class_obj() at Main()" error #1009

i need to know how to have a class that has a gameloop for testing things like collision and stuff please help!

and if i dont have eventlistener enter frame on the object ir works but i need the listener for the loop.

Main class

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

    public class Main extends MovieClip
        var mc:class_obj;

        public function Main()
            mc = new class_obj();

object class


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

    public class class_obj extends MovieClip 

        public function class_obj() 
            // constructor code
            stage.addEventListener(Event.ENTER_FRAME, loop);
        public function loop(e:Event)
            trace("LOOPED CLASS");

EventDispatch error in action script 3

I am not sure if something is wrong with my code or if I have to handle the error differently. I have an instance of Gear and the other one is bLine. I am trying to make both move as soon as the gear falls on the line. So what I have inside of the instance coded is:

var ev2:Event = new Event("transfer");



In the bLine I have: `

import flash.events.Event;


function Move(e:Event):void {


Then, in the main timeline:

 import flash.events.Event;

function transferGear(e:MouseEvent) {


This is the output I'm getting: "TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@16bbd6bb7821 to flash.events.MouseEvent. at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent()

at Rube2_fla::mc_gear_4/frame24()"

So what am I doing wrong and how I could fix it?

samedi 18 mars 2017

Actionscript 3.0 -change the countdown time from a different frame with a button

i have a countdown timer on one of my frames and also two buttons on another frame . I want to change the timer based on the button clicked . For example : 1 min 3 min . I also have a navigation button which goes to the frame that the timer is placed.Any ideas?

vendredi 17 mars 2017

Automatic block generation tilemap

Is it possible to implement automatic painting of the map from the top by randomly selecting one of ten (eg) .tmx files? The width of the card itself should be the same (320 pixels or 10 tiles).

I want to make an infinite map in length (height) and I have several templates for maps in .txt format. I do not want to make a card of 10,000 tiles (10,000 * 32) long, and gradually, depending on the player's passing obstacles, load a random fragment of 10 templates (each for example will be 500 tiles long).

Flash AS2 - Cursor jumps to start of text fields (input and dynamic)

I'm working with an old project that's written in ActionScript 2 and recently a strange bug has appeared.

Sometimes, at any random moment, all text fields, both dynamic and input, will start acting strange. When this happens, everytime I go to highlight text or click somewhere in the field, my cursor jumps to the beginning of the text field. This just started happening recently and it happens to every single dynamic/input field, some that I haven't even edited in months.

I'm not sure if this is a bug with Flash Player or if it's something I might've accidentally changed. I've attached a gif of the issue so it makes more sense.

GIF of the problem :

Go to scene without using button in Flash ASC3

First, gotta say I have read another question about this here, but the solution didnt help and the thread is quite old so i'm creating another post...

I'm using ASC3 in Adobe Animate 2017. To sum it up, I'm having "Scene 1", inside it there's a movie clip which contains a button, clicking that button lead to another frame (in the same movie clip) and it plays to the last frame, where I want it to go back to the first frame of my "Scene 1". It's should be fine with putting

stop(); MovieClip(this.root).gotoAndPlay(1, "Scene 1");

at the last frame right? However I cant get it to work, it seem to just go back to the 1st frame of my movie clip, not my "Scene 1". Anyone could help me understand what should i do?


jeudi 16 mars 2017

Actionscript 3, can only part of a file be read without loading the whole file into memory

I am trying to load a 10mb chunk of a 600mb file in an Air desktop app. At first I tried loading the entire file however I got a "system out of memory" error, or the SWF would just quit without error.

I have not moved to reading only part of the file into a byte array, clearing the array and then reading the next part. This works better but it still gives memory issues towards the end of the file.

It is my understanding that the below method should only read the part of the file requested. But I think for some reason the file from the start to end of the chunk I want is actually read. My cut down code looks like this:

var file:File = File.desktopDirectory.resolvePath('input.txt');
var fileStream:FileStream = new FileStream();
fileStream.addEventListener(Event.COMPLETE, onLoaded);
fileStream.openAsync(file, FileMode.READ);  
fileStream.position = _currentPos;

on load:

var fileStream:FileStream = event.target as FileStream;
_fileSize = fileStream.bytesAvailable;
fileStream.readBytes(bytes, 0, 1000000); 

Then I do something with the bytes and call the above code again, this time the position is previous position plus length of the previous read.

When I examine the byte array I can see the size is equal to the start of the file to the end of the read. The byte array contains no data in elements before the start of the read, which is what I expected.

So am I only reading the chunk I want or the entire file?

If I am not can I do so?

How can I solve the memory issue?

How to know if a setter exists

How can I know, trying to access dynamically, if a given setter exists for an object, assuming a getter does exist. So the point is to know if a value can be set for that property, but using hasOwnProperty returns true as a property by that name does exist.

Actionscript 3 , generating random numbers and placing in byte array, faster?

I am trying to generate large byte arrays of random bytes. Using the below code I can generate 10 million random bytes and place in a byte array in about 4 seconds. 2 seconds for the generation and 2 second to place on the array.

for (var i:Number = 0; i < reqLength; i++){
    rnd = Math.random() * 255;

Does a faster way exist?

I am generating ints because I am creating a byte array of extended asci chars.

change protocol of endpoint in AMFChannel, how to fix it?

I am working on Flex and I find that when I give uri(https://jsonplaceholder.typicode.com/posts/1) to AMFChannel which content 'HTTPS' protocal but calculateEndpoint() method of Channel class change protocol from "HTTPS" to "HTTP".

I also made simple project to demonstrate how endpoint gets changed by AMFChannel.

<?xml version="1.0"?>
<s:Application xmlns:fx="http://ift.tt/rYUnH9" xmlns:s="library://ns.adobe.com/flex/spark">
    import mx.controls.Alert;
    import mx.messaging.ChannelSet;
    import mx.messaging.channels.AMFChannel;
    import mx.rpc.AbstractOperation;
    import mx.rpc.remoting.mxml.RemoteObject;

    private function button1_clickHandler(event:MouseEvent):void
        var amfChannelWeb:AMFChannel = new AMFChannel("amfChannel", txtInput.text);

        var remoteObj:RemoteObject = new RemoteObject();
        remoteObj.showBusyCursor = true;
        remoteObj.requestTimeout = 0;

        var channelSet = new ChannelSet();
        channelSet.channels = [amfChannelWeb];

        remoteObj.destination = "amfphp";
        remoteObj.channelSet = channelSet;

        var op:AbstractOperation = remoteObj.getOperation("testAmfData");
        op.addEventListener("result", resultHandler);
        op.addEventListener("fault", resultFaultHandler);
        lblEndpoint.text = amfChannelWeb.endpoint;

    private function resultHandler(e:Event):void
        lblChannelError.text = e.toString();

    private function resultFaultHandler(e:Event):void
        lblChannelError.text = e.toString();

<s:VGroup width="100%">

    <s:TextInput width="80%" id="txtInput" text="http://ift.tt/1QaOMPV"/>
    <s:Button click="button1_clickHandler(event)" label="Click"/>
    <s:Label id="lblEndpoint"/>
    <s:Label id="lblChannelError"/>


Is this issue or am I doing somthing wrong??

mercredi 15 mars 2017

Hit test object action script

I am trying to make a gear fall off a line using the hit test object. I have a background layer, a layer for the gear and one for the line. The gear rotates on the line and it also moves until to the point where it's going to fall. The code that I have right now is only added in the actual ball instance. The error that I have is access to undefined property Mc_gear_small as well as Mc_rack. What am I doing wrong?



function RotateTiny(e:Event):void {


function MoveTiny(e:Event):void {

function fallTiny(e:Event):void {

this.addEventListener(Event.ENTER_FRAME, Fall);

function Fall  ( e:Event ):void

if (mc_gear_small.hitTestObject(mc_rack))


Actionscript 3, reading two files then triggering a function, best practice

I need to read a part of two files, and once both parts of both files are loaded to trigger a function that does some work.

What is the best way to approach this problem.

I am currently triggering the second file load once the first is loaded, however it seems poor coding style, I think this because my OO code starts looking procedural.

Playing sounds on Actionscript

I have a simple drag and drop game started in flash and mostly working.

I have added my animals and you can drag and drop them in the right place.I have also added sound so that when the animal is dropped in the right spot , that is working however each time I add a new animal to the right spot it plays that sound and the last animal sound as well.

e.g. place pig in pig space , it plays pig sound place cow in cow space , it plays cow sound and pig sound place duck in duck space , it plays duck sound and cow sound and pig sound.

Obviously I only want to play the sound when the animal is placed in the right place - on drop ( not on next animal drop also )

Am not sure what I have done wrong

/* Drag and Drop Makes the specified symbol instance moveable with drag and drop. */ import flash.media.Sound;

  var offset:int = 10;

  var pigStartX:int = 196.80;
  var pigStartY:int = 292.10;

  var pigEndX:int = 578.40;
  var pigEndY:int = 208.50;

  Pig.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);

  function fl_ClickToDrag(event:MouseEvent):void

 stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);

  function fl_ReleaseToDrop(event:MouseEvent):void
// dragging and dropping the pieces while checking for correct   location 

    if(Pig.x < pigEndX - offset || Pig.x > pigEndX + offset || Pig.y <    pigEndY - offset ||Pig.y > pigEndY + offset){

    Pig.x = pigStartX;
    Pig.y = pigStartY;


     //set piece back to original position
     Pig.x = pigEndX;
     Pig.y = pigEndY;

     var oink:PigOink = new PigOink(); 
     var channel:SoundChannel = oink.play();



/* Drag and Drop Makes the specified symbol instance moveable with drag and drop. */

 var cowStartX:int = 324;
 var cowStartY:int = 317.95;

 var cowEndX:int = 411.50;
 var cowEndY:int = 140.95;

   Cow.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_2);

  function fl_ClickToDrag_2(event:MouseEvent):void

  stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_2);

 function fl_ReleaseToDrop_2(event:MouseEvent):void
// dragging and dropping the pieces while checking for correct  location 
 if(Cow.x < cowEndX - offset || Cow.x > cowEndX + offset || Cow.y <  cowEndY - offset ||Cow.y > cowEndY + offset){

      Cow.x = cowStartX;
      Cow.y = cowStartY;


    //set piece back to original position
      Cow.x = cowEndX;
      Cow.y = cowEndY;

    var moo:CowMoo = new CowMoo(); 
    var channel:SoundChannel = moo.play();



/* Drag and Drop Makes the specified symbol instance moveable with drag and drop. */

   var duckStartX:int = 209.45;
   var duckStartY:int = 402.05;

   var duckEndX:int = 56.45;
   var duckEndY:int = 225.05;

  Duck.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_3);

  function fl_ClickToDrag_3(event:MouseEvent):void

  stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_3);

  function fl_ReleaseToDrop_3(event:MouseEvent):void
// dragging and dropping the pieces while checking for correct location 
     if(Duck.x < duckEndX - offset || Duck.x > duckEndX + offset ||   Duck.y < duckEndY - offset ||Duck.y > duckEndY + offset){

    //set piece back to original position
        Duck.x = duckStartX;
        Duck.y = duckStartY;


        Duck.x = duckEndX;
        Duck.y = duckEndY;

        var quack:DuckQuack = new DuckQuack(); 
        var channel:SoundChannel = quack.play();


Flex Air Android : Disable back button

In some modern devices, the back button on Android is pure software. The classical method to disable the back button don't work for me Disable back button

Is there any other solution (the manifest or else) to disable the back button on Android ?

Thanks guys.

Generating truly unique UUIDs in JavaScript and AS3 - PRNGs and underlying algorimths

I'm working on a system that generates around 2 billion unique UUIDs a day. The UUIDs are generated using JavaScript \ Flash (AS3) on the client.

We recently noticed that our UUIDs are no where near unique. We have around 20% (!) of daily duplicates, most of which (relative to traffic volume) are coming from chrome.

I did some reading and I learned that the pseudo-random generation (PRNG) algorithm most browsers, and specifically chrome, implement is flawed. Chromium and Node.js use the V8 javaScript engine, which implements an algorithm called MWC1616.

In theory, UUIDs generated using a good PRNG should have a 2132 probability for collision, but with MWC1616, under some very realistic scenarios, this probability is around 1:30000.

To solve the problem, I considered the following options:

  1. Generate the IDs on the server (using Go)
  2. Generate a stronger ID on the client, by hashing some info like IP, UA, timestamp, etc. with the UUID.
  3. Replacing Math.random() with a better random generator.

Since I prefer to keep things on the client and I don't want to re-invent the wheel and modify the UUID creation logic, I want to stick with option 3.

The good news are that on newer browsers, there is the getRandomValues api. Unfortunately, I need to support older browsers.

So my questions are:

  1. What is a good and reliable JavaScript polyfill for


(that doesn't use Math.random internally)?

  1. Does AS3 Math.random() use the browser's Math.random()? Does it implement the same algorithm itself?

  2. Does flash.crypto.generateRandomBytes() use Math.random()? Does it use crypto.getRandomValues()? If not, which algorithm does it implement and will it be a good solution for the same issue in AS3? If not, which AS3 crypto library would you recommend?

P.S. I highly recommend the article I mentioned. I was aware of the issues with Math.random() for many years, but this article truly made it clear to me for good.

Drag & Drop - ActionScript3

I am developing a simple flash game - a drag and drop game for children.

I have created three animal instances which will be dragged and dropped to the correct space. I am just adding action script and am getting the following error when trying to add drag and drop functions;

Scene 1, Layer 'Actions', Frame 1, Line 10, Column 44 1119: Access of possibly undefined property startDragging through a reference with static type String.Scene 1, Layer 'Actions', Frame 1, Line 10, Column 44 1136: Incorrect number of arguments. Expected 2.

My code is as follows; import flash.events.MouseEvent;


//set up the buttons for the puzzle pieces



function startDragging(e:MouseEvent){



function stopDragging(e:MouseEvent){



Keep typing between Typescript and ActionScript 3

Is it possible to use Javascript object in parameter with Actionscript function bind with ExternalInterface.callBack method and get an instance of ActionScript class as parameter other than Array or Object ?

My purpose is to keep typing between Javascript and Actionscript.


var swfObject = document.getElementById(‘mySwfObject’);

var user = {
    id : 1337,
    name : ‘Foo’,
    surname : ‘BAR’


//Actionscript 3

ExternalInterface.addCallBack(“myFunction”, myFunction);

// Now
private static function myFunction(user : Object)  : void


// With your help
private static function myFunction(user : UserDTO) : void


Submit user input by click AS3

I am just starting my adventure with coding in AS3. I would love to learn how to submit my input by clicking a button and check if it is same as my "password" number. Then, display the message in the dynamic field about the results. I have written some code and it does not show any errors, but - as you may guess - it does not work either.

I thought that using the command button.addEventListener(MouseEvent.CLICK, handleClick); and then creating a simple if... else statement is enough, but somehow it does not work.

Would you kindly take a look at my code and point the mistake which has lead to my misery?

here is the code:

    private var Input:Object;
    private var Output:Object;
    private var yournr:String;
    public function Tehtava25a()
        var Input:TextField = new TextField();
        var Output:TextField = new TextField();
        var initialtxt:String = "Give me the password";

        Input.type = TextFieldType.INPUT;
        Input.border = true;
        Input.width = 200;
        Input.height = 200;
        Input.background =true;

        Output.type = TextFieldType.DYNAMIC;
        Output.text=  initialtxt;
        Output.background = true;
        Output.border = true;
        Output.background =true;
        Output.width = 200;
        Output.height = 200;
        Output.x = 200;
        var button:SimpleButton = new SimpleButton();
        button.x = 250;
        button.y = 250;

        button.upState = createCircle( 0x00FF00, 15 );
        button.overState = createCircle( 0xFFFFFF, 16 );
        button.downState = createCircle( 0xCCCCCC, 15 );
        addChild( button );
        button.hitTestState = createCircle( 0x000000, 50 );

        button.addEventListener(MouseEvent.CLICK, handleClick , false, 0, true);


    private function createCircle(param0:Number, param1:int):DisplayObject
    {var circle:Shape = new Shape(  );
        circle.graphics.lineStyle( 1, 0x000000 );
        circle.graphics.beginFill( 0xFF794B );
        circle.graphics.drawCircle( 0, 0, 30 );
        circle.graphics.endFill(  );
        return circle;

    protected function handleClick(event:MouseEvent):void
    {var yournr:String = Input.text;
    var mynr:String = "1234";
        if (yournr == mynr){
            Output.appendText = "the number is correct"}
        else { Output.appendText = "try again";

mardi 14 mars 2017

ActionScript 3.0 .fla file working, .swf file exported not working

I have another problem with an acrionscript swf file. I'm reading some text from a CSV file. I create the fla file and when I test it in the animate editor it works and I can see all the text inside the CSV file into a TextField. If I export the .swf and run it with Adobe Flash Player 11.4 r402 I can't see the text that there is in the CSV File. I created this fla file made up of one photogram in which I wrote this code:

import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.filesystem.*;
import flash.text.TextField;

var pathToFile:String = File.applicationDirectory.resolvePath('ex.csv').nativePath;

var requestedFile:URLRequest = new URLRequest(pathToFile);

var myTextField:TextField = new TextField();

myTextField.autoSize = TextFieldAutoSize.LEFT;

var documentLoader = new URLLoader();

documentLoader.addEventListener(Event.COMPLETE, onload);


function onload(evt:Event):void
  myTextField.text = evt.target.data;

How can I make the .swf file working? There is a way to read data from a CSV file into a .swf file? Thank you to everybody!

Error during external image load

I am getting error during external image load

": app:/META-INF/AIR", "trace: Extensions to load: 0"

This is what I've tried :

   function LoadImage() {
     loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onContentLoadInfo, false, 0, true);
     loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onContentLoadError, false, 0, true);
     loader.load(new URLRequest(sourcePath));

 function onContentLoadInfo(e: Event) {
     loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onContentLoadInfo);
     loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onContentLoadError);
     if (e.target.hasOwnProperty("content")) {
         this.bitmapData = e.target.content.bitmapData.clone();
         this.smoothing = true;
         this.dispatchEvent(new Event(EVENT_IMAGE_LOADED, false, false));

AIR Android - How to Make a Peer-To-Peer Connection?

I have developed an Android app using Flash / AIR and was wondering how I could set up a peer-to-peer connection (p2p) such that :

  • Users of the app can select certain choices in the app and search for peers.
  • If they are in proximity to other users with mutual selections then their phones vibrate.

Any assistance will be much appreciated.

1046: Type was not found or was not a compile-time constant: VideoContainer

I am new at this plateform and after a lot of search, I am unable to resolve this problem. My code is show error on "VideoContainer" in one project but in other project, it is working fine.

<VideoContainer id="videoDisplay" x="-2" y="0" width="640" height="480" click="hideCanvas()"/>

enter image description here

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

<mx:WindowedApplication xmlns:mx="http://ift.tt/1aBfKeP" 
                width="645" height="500"
            import flash.events.AsyncErrorEvent;
            import flash.media.*;
            import flash.media.H264Level;
            import flash.media.H264VideoStreamSettings;
            import flash.media.Video;
            import flash.media.VideoCodec;
            import flash.media.VideoStreamSettings;
            import flash.net.ObjectEncoding;

            import mx.controls.*;
            import mx.controls.Alert;
            import mx.controls.Label;
            import mx.controls.Menu;
            import mx.events.*;
            import mx.events.MenuEvent;
            import mx.events.SliderEvent;

            private var microphone:Microphone;
            private var camera:Camera;
            private var video:Video;

            private var h264Settings:H264VideoStreamSettings = new H264VideoStreamSettings();

            public var nc:NetConnection;
            public var ncl:NetStream;
            public var ncr:NetStream;
            private var mic:Microphone;
            private var customClient:Object;

            public var isSender:Boolean;

            private function init():void
                    nc = new NetConnection();
                    nc.objectEncoding = ObjectEncoding.AMF0;  //pass binary data between two servers.
                    nc.addEventListener( NetStatusEvent.NET_STATUS, netStatusHandler );
                nc.connect( "rtmp://wjzoiqyosa.rtmphost.com/fms01");
                nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncHandler);

            public function asyncHandler(Event:AsyncErrorEvent):void{
                trace("In asyncHandler");

            public function netStatusHandler( event:NetStatusEvent ):void
                switch( event.info.code ) {
                    case "NetConnection.Connect.Success":
                        // Connection succeeded now create components
                        // Change to Video view
                        //vsMain.selectedChild = pnlVideo;
                    case "NetConnection.Connect.Rejected":
                        Alert.show( "User limit exceed", "Restricted Usage" );
            public function connectComponents():void


            public var bandwidth:int;
            public var framerate:int;
            public var picture:int;
            public var keyframe:int;

            private function init2():void
                ncl = new NetStream( nc );  // used to send video on the server
                ncr = new NetStream( nc );
                video = new Video( 640, 480 );

                customClient = new Object();
                ncr.client = customClient;

                bandwidth= bandwidth_slider.value;
                framerate = sld_framerate.value;
                picture = sld_pic.value;
                keyframe = sld_keyframe.value;

                label1.text = bandwidth.toString();
                lbl_framerate.text = framerate.toString();
                lbl_pic.text = picture.toString();

                lbl_encoder.text = String(textLabel);

                    camera = Camera.getCamera("0".toString());
                    // 2k bytes (or ~16kbps) of bandwidth
                //  camera.setQuality( 65536 / 8, 80 );
                //  camera.setMode( 320, 240, 5, false );
                    // Set loopback as compressed
                    //camera.setLoopback( true );           
                    //video.attachCamera( camera );
                    camera.setMode(320,240,framerate, false );  // (height, width, frame rate)
                    //camera.setQuality( 62500, 0 );       // Ensure that no more than 62500 (?K/second) is used to send video
                    camera.setQuality( bandwidth, picture );

                    // with a minimum quality of 0
                    camera.setKeyFrameInterval(keyframe);  // interpolation

                    h264Settings.setProfileLevel(H264Profile.BASELINE, H264Level.LEVEL_2);
                    //ncl.bufferTime = 0.3;
                    ncl.videoStreamSettings = h264Settings;

                    /*this.mic = Microphone.getEnhancedMicrophone();
                    if (!this.mic){
                        this.mic = Microphone.getMicrophone(-1);
                    this.mic.codec = SoundCodec.SPEEX;
                    this.mic.framesPerPacket = 1;
                    this.mic.setSilenceLevel(0, 2000);
                    this.mic.encodeQuality = 10;

                    if (this.mic){
                        //this.mic.rate = 22;
                        if (this.mic.gain != 60){
                            this.mic.gain = 60;

                    ncl.attachCamera( camera ); //Specifies a video stream from a camera to be displayed within the boundaries of the Video object in the application.
                    microphone = Microphone.getMicrophone();
                    ncl.attachAudio( microphone );

                    video.attachNetStream( ncr );   //Specifies a video stream to be displayed within the boundaries of the Video object in the application.
                    //ncr.bufferTime = 0.3;
                    ncr.play( "my1" );                  

                videoDisplay.video = video;

            public function onBWDoneHandler(eventObj: Object):void{
                trace("**onBWDone:" +Number(eventObj)+"kbps");

            public function showHideCanvas():void{
                if(canvas.visible == false){
                    canvas.visible = true;
                    canvas.visible = false;

            private function hideCanvas():void{
                canvas.visible = false;

            private var myMenu:Menu;

            private function popUpEncoder():void{

                myMenu = new Menu();
                var dp:Object = [
                    {label: "H.264"},
                    {label: "Sorenson Spark"},
                    {label: "On2 VP6"}
                myMenu.dataProvider = dp;
                myMenu.addEventListener("itemClick", changeHandler);
                popup.popUp = myMenu;


            private var textLabel:String;

            private function changeHandler(event:MenuEvent):void{
                textLabel = event.label;
                popup.label = textLabel;


    <VideoContainer id="videoDisplay" x="-2" y="0" width="640" height="480" click="hideCanvas()"/>
    <s:Image id="img" x="0" y="0" width="24" height="24" click="showHideCanvas()" smooth="true"
    <mx:Canvas id="canvas" visible="false" x="0" y="34" width="208" height="267" backgroundAlpha="0.5"
               backgroundColor="#646464" borderAlpha="0.0" borderColor="#FFFFFF"
               borderVisible="false" color="#FFFFFF" cornerRadius="10">
        <mx:HSlider id="bandwidth_slider" x="79" y="5" width="75" maximum="70000"
                    minimum="0" snapInterval="500"/>
        <mx:Label id="label1" x="158" y="13" height="13" fontSize="8"/>
        <mx:Label x="12" y="9" color="#FFFFFF" fontFamily="Verdana" fontStyle="normal"
                  fontWeight="bold" text="Bandwith" textDecoration="none"/>
        <mx:HSlider id="sld_framerate" x="79" y="21" width="75" maximum="50"
                    minimum="0" snapInterval="1" value="15"/>
        <mx:Label id="lbl_framerate" x="158" y="29" height="15" fontSize="9"/>
        <mx:Label x="0" y="25" color="#FFFFFF" fontFamily="Verdana" fontWeight="bold"
                  text="Frame Rate"/>
        <mx:HSlider id="sld_pic" x="80" y="39" width="75" maximum="100" minimum="0"
        <mx:Label id="lbl_pic" x="158" y="48" width="19" height="13" fontSize="9"/>
        <mx:Label x="29" y="44" width="67" color="#FFFFFF" fontFamily="Verdana" fontWeight="bold"
        <mx:HSlider id="sld_keyframe" x="80" y="56" width="75" maximum="50"
                    value="5" minimum="0" snapInterval="1"/>
        <mx:Label x="4" y="61" fontFamily="Verdana" fontWeight="bold" text="Key Frame"/>
        <mx:Button x="69" y="141" label="Apply" chromeColor="#28A50F" click="init2();"
                   color="#FFFFFF" cornerRadius="0" fontFamily="Verdana" fontSize="10"
                   fontStyle="normal" fontWeight="bold"/>
        <mx:PopUpButton id="popup" x="52" y="85" label="Encoder" color="#0A0909"/>
        <mx:Label id="lbl_encoder" x="52" y="114" width="88" creationComplete="popUpEncoder()"/>


how can i make this into as3 format when its in as2?

iam a beginner in flash and often follow tutorials on :http://ift.tt/1m67A7c to learn how to make actionscripts and when i come upon this code i had no clue of as2 making this into as3
//how can i make this into as3 when its as2?// enter code here// import flash.filters.BevelFilter; var distance:Number = 2; var angleInDegrees:Number = 45; var highlightColor:Number = 0xff00ff; var highlightAlpha:Number = 1; var shadowColor:Number = 0xbb00bb; var shadowAlpha:Number = 1; var blurX:Number = 8; var blurY:Number = 8; var strength:Number = 10; var quality:Number = 3; var type:String = "inner"; var knockout:Boolean = false; var my_bevel_filter:BevelFilter = new BevelFilter(distance, angleInDegrees, highlightColor, highlightAlpha, shadowColor, shadowAlpha, blurX, blurY, strength, quality, type, knockout); //and this one is not supported by as3 anymore// terrain.lineStyle(20, 0xdd00dd, 100); terrain.filters = new Array(my_bevel_filter); //how can i make this into as3?// imdrawing = false; //onMouseDown = function () { if (imdrawing == false) { terrain.moveTo(_xmouse, _ymouse); imdrawing = true; } if (imdrawing == true) { onEnterFrame = function () { terrain.lineTo(_xmouse, _ymouse); }; } }; onMouseUp = function () { onEnterFrame = function () { imdrawing = false; }; };

lundi 13 mars 2017

AS3 not recieving myStatus from php login page

I am not receiving the myStatus when retrieving it from the php login. I get p_id and full name but not the status. I am parsing it to separate out the & but keep getting a null result from login. section 6 and section 7 are the areas I think I am having issues can anyone help?

login AS3

    package  {

import flash.display.MovieClip;
import flash.text.*;
import flash.events.*;
import flash.ui.Keyboard;
import flash.net.*;
import MainDocument;

public class Login extends MovieClip {

    public function Login() {
        // constructor code

        // modify existing text boxes
        login_txt.tabEnabled = true;
        login_txt.tabIndex = 1;
        login_txt.border = true;
        login_txt.borderColor = 0xAAAAAA;
        login_txt.background = true;
        login_txt.backgroundColor = 0xFFFFDD;

        pwd_txt.tabEnabled = true;
        pwd_txt.tabIndex = 2;
        pwd_txt.border = true;
        pwd_txt.borderColor = 0xAAAAAA;
        pwd_txt.background = true;
        pwd_txt.backgroundColor = 0xFFFFDD;

        login_btn.tabEnabled = true;
        login_btn.tabIndex = 3;

        //add button event listeners

        login_btn.addEventListener(MouseEvent.MOUSE_UP, doLogin);
        login_close_btn.addEventListener(MouseEvent.MOUSE_UP, doClose);
        addEventListener(KeyboardEvent.KEY_DOWN, onEnter);
    } // end construtor

            private function onEnter(e:KeyboardEvent):void{
        // nothing yet

        if(e.keyCode == Keyboard.ENTER){
            trace("User presses keyboard ENTER key");
            doLogin(null); // must be null to meet the need for a parameter
        }// end if
    }// end function

     // SECTION 1 – This is a function we need for removing extra whitespace coming from CWP server 
function trimWhitespace($string:String):String {
if ($string == null) {
    return "";
} //end if
return $string.replace(/^\s+|\s+$/g, ""); // see regular expressions
} // end function          

private function doLogin(e:MouseEvent):void{            
//trace("User presses OK button");

// SECTION 2 – URL request variable declared with path to server script
var req:URLRequest=new URLRequest(MainDocument.localPath + "login.php");
req.method = URLRequestMethod.POST; 

// SECTION 3 – Upload variables are named as URL variables
var vars:URLVariables=new URLVariables();
vars.login = login_txt.text;
vars.pwd = pwd_txt.text;
req.data = vars;    

// SECTION 4 – The URL Loader class instance is set to perform the HTTP                                                                                                                             POST
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;  

// SECTION 5 – listeners are added for both the HTTP status and COMPLETE    
loader.addEventListener(Event.COMPLETE, retrieveData);

// SECTION 6 – The complete handler function is embedded within the doLogin()                                                                                                                                                                                                  function
function retrieveData(e:Event):void { 
    // For the CWP server we must parse our own incoming data
    var rawString:String = trimWhitespace(unescape(e.target.data));     
    var stArray:Array = rawString.split("&"); //split on ampersand  character
    trace("retrieve data");
    for(var i:uint; i<stArray.length; i++){
        stArray[i] = trimWhitespace(stArray[i]);
        var pair:Array = stArray[i].split("=");
        pair[0] = trimWhitespace(pair[0]);
        switch (pair[0]){
            case "myStatus":
                var ms:String = trimWhitespace(pair[1]);    //  status data value
            case "p_id":
                var id:int = int(trimWhitespace(pair[1]));  // player id
            case "fullname":
                var fn:String = trimWhitespace(pair[1]);    // fullname
            default: // this is all the other junk---> dump
                //do nothing
        } // end switch
    } //end for 

// SECTION 7 – A switch statement to deal with cases of myStatus
    switch (ms){
        case "NOTOK" :
            MainDocument.doc.showMsg("There is a communication problem\nTry Again!");
        case "OK" :
            if(fn != "INVALID"){                            
                MainDocument.doc.showMsg("Welcome " + fn);                      
                //MainDocument.player_id = id;
                //MainDocument.player_name = fn;
                // start game here
                MainDocument.doc.showMsg("Login or password is incorrect. Try again, or \nif you are not a member,  please register");
            //MainDocument.doc.showMsg("An unknown problem has occured");
    } // end switch             
} // end function   

// SECTION 8 – Handler function for HTTP status – also embedded             
 function onHTTPStatus(event:HTTPStatusEvent):void { 
    //trace("HTTP response code " + event.status); 
        MainDocument.doc.showMsg("There is an I/O Error #" + event.status);
    } // end if
} // end function               
} // end function doLogin

    private function doClose(e:MouseEvent):void{
        // nothing yet
        trace("User presses Close button");

        MainDocument.doc.showMsg(""); // clears any message
    }// end function

   }//end class

 }// end package




 // Create vars and load with incoming POST data 

 $login = $_POST['login'];


 $login = $_GET['login'];


 $pwd = $_POST['pwd'];


 $pwd = $_GET['pwd'];





 if(!(isset($login) && isset($pwd))){

 print "myStatus=NOTOK&dummy=dummy";


$query = "SELECT `p_id`,`p_name` FROM `player` WHERE `p_login`='$login' AND `p_pwd`='$pwd'";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_row($result);

if($row[0] != null && $row[0] != ''){

    $p_id = $row[0];
    $fullname =  trim($row[1]);
    $myStatus = $row[2];
    print "myStatus=OK&p_id=" . trim($p_id) . "&fullname=" . trim($fullname) . "&dummy=dummy";      


    $fullname = "INVALID";  
    print "myStatus=OK&fullname=" . trim($fullname) . "&dummy=dummy";       

} //end else     

 } //end else               


Creates ball clockwise or anti clockwise

enter image description here

Create balls

  1. if bar moving towards point A (clockwise),create ball on direction of B (anticlockwise).
  2. if bar moving towards point B (anticlockwise),create ball on direction of A (clockwise).

Here is my existing code

var randomRotation:Number;          

randomRotation = randomRange(_bar.rotation - randomRange(150,250),_bar.rotation + randomRange(150,250));
ball.rotation = randomRotation;
ball.x = stage.stageWidth * 0.5;
ball.y = stage.stageHeight * 0.5;

Bar movement

  1. move towards the shortest radius.

Here is my existing code

var angleDiff:Number = 180 - Math.abs(Math.abs(_bar.rotation - ball.rotation) - 180);
var angleDiffPlus:Number = 180-Math.abs(Math.abs((_bar.rotation+speed)-ball.rotation)-180);
var angleDiffMinus:Number = 180-Math.abs(Math.abs((_bar.rotation-speed)-ball.rotation)-180);

if (angleDiffPlus < angleDiff)
    dr = 1;
else if (angleDiffMinus < angleDiff)
    dr = -1;
    _bar.rotation = ball.rotation;

_bar.rotation +=  speed * dr;

So how can those problem can be solve.

Thanks in advance