mardi 30 juin 2015

Actionscript 3 - How to Move Between Maps/Levels

I have a top down game and i just want to know how to make it so when the character hits the right side he will go to the right map/level. I feel like this is a basic necessary part of a lot of games so i don't know how nobody has a tutorial or guide for this. I would be so grateful for anyone that can help. I know this isn't alot of info so just comment if you want more info. Basically just how can you make an almost rpg style movement between maps?

How to change one object into another object?

This is mostly a question about code design. What you see here is a very condense version of the original code.

An example of the code is:

player.rest();

Which makes the player sleep.

There is a bunch more like, walk, run, talk etc which all work great. The one that is a problem is polymorph. That changes the player from a human object to another object. The solution I came up with is this:

class main
  {
      var human:Human = new Human;
      var alien:Alien = new Alien;
      var cow:Cow = new Cow;
      var player = human;

      enterframe loop{
       //other code 
       if (player does something)
       player.polymorph = "alien";

       switch (player.polymorph)
       {
         case "alien":
         player = alien;
         break;
         case "cow":
         player = cow;
         break;
         //etc
       }
       player.update();
     }
  }

I want something that looks like this:

  class main 
    {
      var human:Human = new Human;
      var alien:Alien = new Alien;
      var player = human;

      enterframe loop
      {
       player.polymorph(alien);
      }
    }

I know my original solution is the wrong way to go about things as it encourages spaghetti code. But how would I do it differently? I don't mind a whole rewrite, but need like a example to help push me in the right direction. I hope this makes sense and thanks for the help.

If the second one can work, what would the polymorph function look like?

I thought of making a class called player and changing what that extends, but to my knowledge that can't be done? Plus I would like to change the character to something already in game rather than a new object.

creating duplicate movieclips overwrites their references AS3

I am trying to create 5 movieclips and add to stage. Each movieclip has a textfield attached to it that shows the reference of the movieclip (i,e., clip1,clip2, etc)

I know how to use an array to store the references to the movieclips, but what I want to do is when I clicked on clip2, for example, I want an event specific to clip2. That does not work, as the last movieclip overwrites the referneces to the previousl duplicated clips.

Here is the very simple code

//code below resides on frame 1, Flash IDE
import com.Jim.util.drawLabel;
import flash.text.TextFormat;
import flash.display.MovieClip;
import flash.events.MouseEvent;

var d:drawLabel;//this is a class that creates the shapes, texts of the mcs
var f:TextFormat = new TextFormat("Arial");

for (var i:int=0; i<4; i++) {
    d = new drawLabel  ;
    d.idOf=i
    d.init("i "+i,i,f,50,50*i);//the drawlabel class has a public method that creates the shapes and the text; see below in the class
    d.addEventListener(MouseEvent.CLICK,checked);
    addChild(d);
}
function checked(e:MouseEvent):void {
    trace(d.idOf);
//result of the trace is 3, regardless of which movieclip I clicked on;
}

And this is the drawLabel class

package com.Jim.util{

    import flash.display.MovieClip;
    import flash.display.Shape;
    import flash.display.GradientType;
    import flash.geom.Matrix;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import flash.text.TextFormat;
    import flash.display.Sprite

    public class drawLabel extends MovieClip {


        public var bc:Sprite;
        public var idOf:Number
        public var label_txt:TextField;
        public var theSentence:String;

        public function drawLabel() {

        }
        public function init(theSentence,mc_id,whatFmt,sentenceL:Number=100,sx:Number=0,sy:Number=0,blockSize:Number=50,colorOf:uint=0xcccccc, alphaOf:int=1) {
            bc = new Sprite();
            idOf=mc_id
            label_txt = new TextField();
            bc.graphics.beginFill(colorOf,alphaOf);
            bc.graphics.drawRect(sx, sy, sentenceL, blockSize);
            bc.graphics.endFill();
            bc.mouseChildren=true
            bc.buttonMode=true
            label_txt.x = sx;
            label_txt.y = sy;
            label_txt.width = sentenceL;
            label_txt.height = blockSize;
            label_txt.multiline = true;
            label_txt.wordWrap = true;
            label_txt.border = false;
            label_txt.type = "dynamic";
            label_txt.selectable = false;
            label_txt.text = theSentence;
            label_txt.setTextFormat(whatFmt);
            addChild(bc);
            bc.addChild(label_txt);
            bc.addEventListener(MouseEvent.CLICK,clicked);
        }
    }
}

One more note, I could just copy the function that creates the movieclips into the main fla, and it works. But I thought why add more code when I can use the class. I hope this makes sense.

Thank you

Collision detection alghorithm for moving objects

Please anybody give me an idea. There are several (let's say ~20...) objects on screen that move and rotate about their center an each frame. When one object is rotates, his text hint rotates too. The problem is - if two hints come into collision, one of them must move at some angle so as not to collide with another hint. Please tell me which algorithm should be applied here?

Here is picture to understand it ;) - http://ift.tt/1JoIjQT

Actionscript - sbustring

How does Actionscript handle the following substrings? For the substrings below, what are the correct outputs?

var main = "1234567890"
var output = sbustring(main, 5,1) // output = 
var output = sbustring(main, 1,5) // output = 
var output = sbustring(main, 0,5) // output = 
var output = sbustring(main, 5,0) // output = 

Make Text change color in the As3

I want to make a black rectangle (called R_1) and a white text (a textfield called T_1) on it. After that, the rectangle R_1 should slowly reduces height and also the (T_1) change from white to black.

This is the example http://ift.tt/1egmckH enter image description here

web recorded video not played in ipad

I record video from web using flash media server. Now using flex default player i tried to play video but, it will not play ipad.(ios device)
I checked that video codec and it is something like following:

libxavs --enable-libxvid --enable-decklink --enable-zlib
  libavutil      52. 92.100 / 52. 92.100
  libavcodec     55. 69.100 / 55. 69.100
  libavformat    55. 45.100 / 55. 45.100
  libavdevice    55. 13.102 / 55. 13.102
  libavfilter     4. 10.100 /  4. 10.100
  libswscale      2.  6.100 /  2.  6.100
  libswresample   0. 19.100 /  0. 19.100
  libpostproc    52.  3.100 / 52.  3.100
[flv @ 0000000002b60220] Stream discovered after head already parsed
Input #0, flv, from 'C:\Users\Administrator\Desktop\123654789.flv':
  Metadata:
    canSeekToEnd    : false
    createdby       : FMS 4.5
    creationdate    : Tue Jun 30 16:27:22 2015
  Duration: 00:00:15.25, start: 0.000000, bitrate: 52 kb/s
    Stream #0:0: Video: flv1, yuv420p, 320x227, 1k tbr, 1k tbn, 1k tbc
    Stream #0:1: Audio: speex, 16000 Hz, mono, s16, 20 kb/s
    Stream #0:2: Data: none

I record video following ways:

netstream.publish("FILENAME","record");

Thanks.

How to removechild in as3?

this is my code:

var star:Sprite = new Sprite();
for (var i:Number = 0; i<50; ++i) //check if sky contains star , remove them
{
     if (sky.contains(star)) //this "if" didnt work!
     {
        sky.removeChild(star);
     }
}
for (i= 0; i<50; ++i) //add new stars to sky
{
    star = new Sprite();
    star.graphics.beginFill(0xFFFFFF);
    star.graphics.drawCircle(0, 0, ((Math.random() * 1.5) + 0.25));
    star.x = Math.random() * stage.stageWidth ;
    star.y = Math.random() * stage.stageHeight;
    sky.addChild(star);
}

the 1st "if" didnt work and in 2nd "for" stars add to sky over previous stars! what is the correct code to remove previous stars?thanks

how to create a dodging button in flash as3?

I want to create a button that "can't be clicked on", as in, when the cursor is near it, the button randomly changes it's position (within stage limitations). not sure how to look it up online, so i'm asking here :)

Is it possible compare DisplayObjects by content if flash?

We trace MovieClip, frame by frame, and want to find unique objects that preset on it(this is a rasterizer flash animations for opengl). We do this work, with code below:

    public function process():void
    {
        movieClip.addEventListener(Event.FRAME_CONSTRUCTED, onEnterFrame);
        onDone = false;

        currentFrame = 0;
        movieClip.gotoAndStop(1);

        while (!onDone)
        {
            movieClip.nextFrame();
        };
    }

    private function onEnterFrame(e:Event):void
    {
        if ( currentFrame >= movieClip.totalFrames )
        {
            convert(movieClip);
            movieClip.removeEventListener(Event.FRAME_CONSTRUCTED, onEnterFrame);

            onDone = true;
            onDoneCallback(movieClipItem);
        }
        else
        {
            frames[currentFrame] = new Vector.<Object>();
            labels.push(movieClip.currentFrameLabel);

            for (var j:int = 0; j < movieClip.numChildren; ++j)
            {
                var child:DisplayObject = movieClip.getChildAt(j);

                if ( child.visible )
                {
                    frames[currentFrame].push(getSnapshot(child));

                    if ( !(child in objects) )
                    {
                        objects[child] = [];
                    }

                    objects[child].push(currentFrame);
                }
            }

            currentFrame++;
        };
    }

As a result we have "frames" collections where on each frame we have objects that exists on that frame. Then we try to find same objects in frame collection, and use follow function for compare objects:

private function objectEqual(left:DisplayObject, right:DisplayObject):Boolean {
    return left === right && left.name == right.name;
}

but this compare give not good results. For example when the same movieclip added at frame 2 and at frame 10, objectEqual give us that this movie clip is different(this is different objects instance, but with the same content, so in our case thay must by equal). Also some times Shape objects may change they content, but instance and instance name will remain the same, so "objectEqual" also make mistake, and give us that "left" and "right" are same, but they different.

Check if hitTestObject finished with all the elements of an array

I have an array with seven movieclips that hitTestObject a movieclip called ousiastikaChest. That's works fine. I want to check if all elements of that array had hitTestObject so a well done message to appear. This part of my code is wrong. Can anyone help me? Thank you

This is my code

 var circles:Array = [ous1,ous2,ous3,ous4,ous5,ous6,ous7];
 for each(var circleMC:MovieClip in circles)
 {
     circleMC.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
     circleMC.addEventListener(MouseEvent.MOUSE_UP, dropIt);
     circleMC.startX = circleMC.x;
     circleMC.startY = circleMC.y;
}

 function pickUp(event:MouseEvent):void
 {
     event.target.startDrag(true);
     event.target.parent.addChild(event.target);

 }

function dropIt(event:MouseEvent):void
 {
     event.target.stopDrag();

     if(event.target.hitTestObject(ousiastikaChest)){
         event.target.buttonMode = false;
         event.target.alpha = 0 
         event.target.x = ousiastikaChest.x;
         event.target.y = ousiastikaChest.y;
         ousiastikaChest.gotoAndPlay(2);
    }
    else
     {
         event.target.x = event.target.startX;
         event.target.y = event.target.startY;
         event.target.buttonMode = true;
    }
 }
 //problem with that part of the code
 for(var i:int = 0; i<circles.length;i++){
      if(circles[i].hitTestObject(ousiastikaChest)){
         feedback.text="Well Done";
      }
 } 

Add Event-Listener for the whole Symbol

I´ve put a Label and a ComboBox together in a Symbol, like in the code below.

public class LabelCombo extends MovieClip {     


        //myLabel is an instance of fl.controls.Label
        //myCombo is an instance of fl.controls.ComboBox
        public function LabelCombo() {              
        }


        public function setLabelText(s:String):void{
            myLabel.text = s;
        }

        public function getLabelText():String{
            return myLabel.text;
        }



        public function removeAllItems():void{
            if(myCombo.dataProvider.length > 0)
                myCombo.removeAll();
        }


        public function setSingleItem(o:Object):void{
            removeAllItems();
            myCombo.addItem(o);
        }


        public function setList(itemList:Array):void{
            for(var i:int = 0; i < itemList.length; i++){
                if(i==0)
                    setSingleItem(itemList[i]);
                else
                    addSingleItem(itemList[i]);
            }
        }


        public function addSingleItem(o:Object):void{
            for(var i:int = 0; i < myCombo.dataProvider.length; i++){
                    if(o == myCombo.getItemAt(i))
                        return;
                }
            myCombo.addItem(o);
        }


        public function addList(itemList:Array):void{
            for(var i:int = 0; i < itemList.length; i++){
                addSingleItem(itemList[i]);
            }
        }

        public function getSelectedItem():Object{
            return myCombo.selectedItem;
        }

        public function getItemByLabel(s:String):Object{
            return Object(myCombo.getChildByName(s));
        }

        public function selectItemAt(index:int):void{
            myCombo.selectedIndex = index;
        }

        public function getselectedIndex():int{
            return myCombo.selectedIndex;
        }

    }

Now I want to addEventListener(Event.CHANGE, changeHandler) on the whole Symbol so I can do something like that

trace(LabelCombo(event.currentTarget).getLabelText())

trace(LabelCombo(event.currentTarget).getSelectedItem().data)

I need information from both single controls. It`d be nice if someone can show me how to do this.

Thanks in advance

lundi 29 juin 2015

Decrypt a file encrypted using openssl in as3?

I have a file encrypted using openssl that I need to decrypt in flash. The encrypted file was generated using this command in openssl:

openssl aes-256-cbc -in "file-to-be-encrypted.jpg" -out "encrypted-a.txt" -a

and in AS3, I use as3crypto with the following code:

var file:File = File.desktopDirectory.resolvePath("encrypted-a.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var ba:ByteArray = new ByteArray();
fileStream.readBytes(ba);
fileStream.close();         
var key:ByteArray = Hex.toArray("password");
var aes:AESKey = new AESKey(key);
var decryptedBytes:ByteArray =  Hex.toArray(Base64.decode(ba.readUTFBytes(ba.bytesAvailable)));
try {
    aes.decrypt( decryptedBytes );
}catch(xe:Error){}

var decryptedFile:File = File.desktopDirectory.resolvePath("decrypted-a.png");
var decryptedFileStream:FileStream = new FileStream();
decryptedFileStream.open(decryptedFile, FileMode.WRITE);
decryptedFileStream.writeBytes(decryptedBytes);
decryptedFileStream.close();

Unfortunately the decrypted file in as3 is not identical to the original file. Anybody have any ideas?

Adobe Flash game involving comparison of movie clips objects

  • layout on the game

I'm working on a simple food game where there are 9 pictures of ingredients and every dish has only two of these ingredients found in them. I can specify or hard code which pictures are correct. I dont need to shuffle them too.

The user when successfully clicked on the 2 correct ingredients, an output will be shown below to tell them they have got it correct. If its one or none, the game will reset.

  • The problem

I have done the shell so far where the layout of the game has been done but lacking the actionscript portion of the game, i have done some research on memory games but i feel that there is much difference in the coding.

Picture below:

1) The user will start by clicking any 2 square on the left (eg: sp1 and sp3)

2) If it is correct, the user will be brought to another frame to start on the second dish

3) If the combination is wrong, the blue box will show "incorrect" and game resets

Shouldn't parent Sprite dimensions reflect child content size?

I'm trying to track down a separate issue but I noticed an oddity I don't understand.

I have a Sprite into which I load two Bitmaps as children (code below). Then I have a function which sets size and position based on some XML settings.

I never set the size of the parent Sprite explicitly and so expect it to reflect the overall size of its children.

This is the Console output after setting the children size. The height of the parent is reported as 4 px greater than the child contents. I don't understand this. Both children are at (0,0) and are 200 x 200. Why is the container Sprite 4 px taller?

AFTER
     canvas 1024 768
     this dimensions 200 204.1 // <--- INCREASE OF 4 PX
     this xy 200 200
     buttonImage dimension 200 200
     buttonImage xy 0 0
     hitSprite dimension 200 200
     hitSprite xy 0 0


Code setting/reporting dimensions:

            this.buttonImage.width = newWidth;
            this.buttonImage.height = newHeight;
            this.hitSprite.width = newWidth;
            this.hitSprite.height = newHeight;

            trace("AFTER");
            trace("\t canvas", canvas.width, canvas.height);
            trace("\t this dimensions", this.width, this.height);
            trace("\t this xy", this.x, this.y);
            trace("\t buttonImage dimension", this.buttonImage.width, this.buttonImage.height);
            trace("\t buttonImage xy", this.buttonImage.x, this.buttonImage.y);
            trace("\t hitSprite dimension", this.hitSprite.width, this.hitSprite.height);
            trace("\t hitSprite xy", this.hitSprite.x, this.hitSprite.y);

Creating Sprite children:

                buttonImage = new Bitmap(upImageData);
                buttonImage.smoothing = true;
                this.addChild(buttonImage);

                hitSprite = createHitArea(upImageData, 4);
                this.addChild(hitSprite);
                hitSprite.visible = false;
                hitSprite.mouseEnabled = false;
                this.hitArea = hitSprite;

Action Script 3: substr output

What would actionscript output in the following examples?

var str = "Hello from Paris, Texas!!!";

str.substring(11,15)) str.substring(15,11)) str.substring(15,2)) str.substring(15,2)) str.substring(0,15)) str.substring(15,0))

actionscript make tutorial appear only once when launching game 1st time

I maka a mobile game for Android and I need tutorial for my game that appears only once when game installed and opened first time. Is there a nice way to do it? What to add in my code for this?

SourceTree won't track changes in ActionScript files

SourceTree for Mac which I'm using with my AS3 project do not track changes in class files. More accurately speaking, it treats them more like a single line of code rather than a sequence of lines. So, when I change something, version control shows that the whole file has changed. It doesn't happen in all AS3 projects, but in some of them, so I'm guessing it has something to do with project Git settings.

How can I fix this?

AS3 Access MovieClip on Stage?

I have a Movie Clip added to my timeline frame 1 and I am trying to figure out how I can access it, I have a button that when I press it I want to restart the movie clip from frame 1 and play. I know how to do that but I can't seem to figure out how to access it.

I exposed it to actionscript with the class of MyMovie.

I can create a new instance of it by going

var mymovie:MovieClip = new MyMovie();

But I want to access the one I added to the timeline frame, not create a new one.

How to update SQL server table based on modified values?

I am currently developing an AS3 module which loads content from a SQL Server Table in a data grid. Whenever the data grid is changed, the changed values should be stored in the database. My question is, Is there anyway I can accomplish this with just one SQL query?

Currently I am firing queries based on changes in each cell which is inefficient.

Thank you.

Regex to find Last name, first name or just first name

trying to write a regex that will extract a first and last name or just a first name depending on the format.

The two possible formats will be:

<Last name> / <first name>

Or:

<first name>

Is there a single regular expression that I can use to extract (with groups) the last name and first name if in the first format, or just the first name in the second format?

Thanks! Kyle

Issue with browser zoom in Flex app

We have an issue with our Flex application. It has Flex UI component and a backend java component. When the browser is zoomed to more than 100%, application becomes completely frozen (no component not even scroll bar responds).

Am new to Flex, any pointers to fix this issue would be really helpful.

Adobe Scout: gotoAndPlay() function is heavier than it seems?

profiling the game with Adobe Scout

At some point of development of my new game, I stumbled upon a problem which lead me to discovery of Adobe Scout. The problem occurred after some time of gameplay when the game started lagging more and more heavily up to the point when the whole application crashed. I did some profiling with Scout, and here's what I found: most, if not every heavy memory load is caused by gotoAndPlay() function (if I understand the data presented by the profiler correctly). This function always seemed and even felt like an easy task for Flash, but turns out it's not? Or is it caused by using text labels instead of frame numbers? I am currently looking for possible workarounds to use this method less, and while I do, it would be infinitely helpful to hear thoughts or possible options from people who are aware of this issue.

How to connect button to create tree menu?

How to connect button to create a file xml for a drop-down list "tree menu" in AS3 Like this

dynamic loading images by name from library

i have a small problem with loading specific images in flash...

In my project I want to load a certain image from the library (f.ex. "event1_pic.jpg") - the actual number is stored in an int variable.

I already exported the jpg for actionscript and it works fine when i directly call the image by its full name...

That's the current working solution (calling the full name of the image) :

var event_pic = new event1_pic();
bmp = new Bitmap(event_pic);
addChild(bmp);

My attempt on integrating the int variable in the name (event_number=1):

var event_pic = new this["event"+event_number+"_pic"]();
big_pic = "event"+event_number+"_pic";
var event_pic = new this.big_pic();  

Can anyone please help me with that problem? Or maybe anyone knows another solution on loading specific images that only differ in name?

Flash Programming ActionScript3, double import swf to the main Stage from another class

Let me explain my situation: We have a file named Main.fla which links to the class MAIN( it's included in the MAIN.as file). I also have a secondary User.as file with a User class.

I managed to import a classic swf button to my stage from the User.as class but i'm finding trouble on adding the pop up window, when the button is clicked. Here are the codes:

MAIN.as

import flash.display.*;
import flash.net.*;
import flash.events.*;

import User;                          //Importing our User class

public class MAIN extends MovieClip
{


    public function MAIN() 
    {
            var k = new User();   
            k.logocons(this);      //This function is made on User class and 
                                   //it takes a stage:Object as definition
    }
}

User.as

import flash.display.*;
import flash.net.*;
import flash.events.*;

public class User extends MovieClip                                             
{

    var myLoader:Loader = new Loader();                                         


    public function User()
    {
      var url:URLRequest = new URLRequest("C:/Project/Button.swf");
      myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded);
      myLoader.load(url);
    }

    function swfLoaded(event:Event):void 
    {
        myLoader.x = 50;                                       
        myLoader.y = 50;                                        
    }

    public function logocons(stage:Object)                                  
    {                                                                           
        stage.stop();
        stage.addChild(myLoader);
    }
}

This works normally so far When i test the file the Button works perfectly

What i want now is when the button is clicked to show at my MAIN.Stage a pop up window which is also in the same folder named PopUp.swf.

I tried really many things but i couldn't find how i can access the MAIN.stage from another class.

Thanks in advance

Latest AIR SDK and intellij idea 12

I've created pure as3 project and downloaded air sdk 18. I want to use latest sdk instead of included with flex 4.6.0. Merged flex and air directories. After that idea says "check your AIR: 18.0.0.143". If I revert merging, I see "Invalid namespace: http://ift.tt/1Hpsvh6". What to do?

dimanche 28 juin 2015

select specific data in a xml file

I've got this xml file

<data-set xmlns:xsi="http://ift.tt/ra1lAU">
    <record>
        <Date>1 July</Date>
        <Ville>New-York</Ville>
        <haute>6h50</haute>
        <basse>1h14</basse>
        <haute2>20h01</haute2>
        <basse2>13h16</basse2>
    </record>
    <record>
        <Date>2 July</Date>
        <Ville>New-York</Ville>
        <haute>7h36</haute>
        <basse>1h59</basse>
        <haute2>20h41</haute2>
        <basse2>13h56</basse2>
    </record>
    <record>
        <Date>3 July</Date>
        <Ville>Miami</Ville>
        <haute>8h21</haute>
        <basse>2h44</basse>
        <haute2>21h22</haute2>
        <basse2>14h37</basse2>
    </record>
</data-set>

I would like, in my AS3 code, to be able to select specific data from this xml file.

Example :

var currentDate=new Date();
var day=currentDate.getDate();

If the day == one of the day of the xml, display "haute" of the corresponding day.

Is it possible ? How can I do that ?

Read stored data with AS3

I would like to create an AIR app that can read and search into a table (xml file ? xls file ? don't know the simpliest).

Example : I've got a table with 500 lines and 6 columns.

enter image description here

I would like to tell my AS3 code :

If ("date == 6 July" && City == "San Francisco"){
show the hours();

Do you know the simplisest way to do something like that ?

Update event in AS3

 board.addEventListener(MouseEvent.CLICK, abc);

 function abc(event:MouseEvent):void {
       var slate:Sprite = new Sprite;
       slate.x = mouseX;
       slate.y = mouseY;


       var rectangle:Shape = new Shape;
       rectangle.graphics.beginFill(0xFFFF00);
       rectangle.graphics.drawRect(0, 0, 100,100);
       rectangle.graphics.endFill();


       var txtField:TextField = new TextField;
       txtField.width = 90;
       txtField.height = 90;
       txtField.type = "input";
       txtField.wordWrap = true;


       slate.addChild(rectangle);
       slate.addChild(txtField);
       board.addChild(slate);


       updateAfterEvent();
 }

I want that If I close the swf file and reopen it the events which were happened before closing the swf will be stay.That is what I am trying to say is if I take a text-field by clicking on the board and then close the swf file and later I open it again I will find that a there is a text-field on the board and It will continue so. I tried as follow..

here board a movie clip.

Search informations in a XML database

I've got this xml database :

    <!--
    - Base de données :  'Database_test'
    -->
    <database name="Database_test">
        <!-- Table daytime -->
        <table name="daytime">
            <column name="temps">27 June 2015</column>
            <column name="username">New-York</column>
            <column name="up">6h20</column>
            <column name="down">14h32</column>

        </table>
        <table name="daytime">
            <column name="temps">29 June 2015</column>
            <column name="username">New-York/column>
            <column name="up">8h32</column>
            <column name="down">15h32</column>

        </table>
        <table name="daytime">
            <column name="temps">28 June 2015</column>
            <column name="username">San Francisco</column>
            <column name="up">0h</column>
            <column name="down">12h</column>

        </table>
...
...
...
    </database>

I would like to display in my AIR app (AS3), in a dynamic text field, two variables : up and down but with variables.

Example : if daytime is 28 June 2015 display "up" and "down". or if daytime is 28 June 2015 AND username is "San Francisco" display "up" and "down".

How do I do ?

So far, I've got :

var loader:URLLoader = new URLLoader();
loader.load( new URLRequest( "daytime.xml" ) );
loader.addEventListener(Event.COMPLETE, handleComplete);

But I don't know how to retrieve a specific variable ("up" for example).

Thank you

netStream seek on Android for Adobe Air

I have net stream that plays mp4 files form Amazon S3.

Currently when I call _ns.seek(time) if the file is buffered to that point the seek will work, else it will wait until the video is linear buffered to start playing.

How to make the net stream start playing immediately from seek point?

Linking multiple objects to one coding name

I am trying to make an rpg style game in Flash AS3. I am trying to get my character to stop when he hits objects such as trees and buildings. Is there a way I can link multiple objects together and make the code say something like 'take object1, object2, and object3 and name it multipleobjects'? I have the code set up so that the character stops at one tree but I'm not positive how/if you can combine objects so that he won't go through multiple at one time. Thank you very very much in advanced! Objects: manmc (my character), treer1_MC (the first tree) treer2_MC (second tree) and so on

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;

manmc.gotoAndStop ("Stand Front Frame");

var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var manSpeed:Number = 3;

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);

function keyDownHandler (keyEvent:KeyboardEvent):void
{
    if(keyEvent.keyCode == Keyboard.RIGHT)
    {
        rightPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.LEFT)
    {
        leftPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.UP)
    {
        upPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.DOWN)
    {
        downPressed = true;
    }
}

function keyUpHandler (keyEvent:KeyboardEvent):void
{
    if(keyEvent.keyCode == Keyboard.RIGHT)
    {
        rightPressed = false;
        manmc.gotoAndStop("Stand Right Frame");
    }
    else if(keyEvent.keyCode == Keyboard.LEFT)
    {
        leftPressed = false;
        manmc.gotoAndStop("Stand Left Frame");
    }
    else if(keyEvent.keyCode == Keyboard.UP)
    {
        upPressed = false;
        manmc.gotoAndStop("Stand Back Frame");
    }
    else if(keyEvent.keyCode == Keyboard.DOWN)
    {
        downPressed = false;
        manmc.gotoAndStop("Stand Front Frame");
    }
}

function gameLoop(loopEvent:Event):void
{
    if(rightPressed)
    {
        if(manmc.x < 1050)
        {
            manmc.x += manSpeed;
        }
        manmc.gotoAndStop("Walk Right Frame");

        if (manmc.hitTestObject(treer1_MC))
    {
        trace("leftHit");
        manmc.x -= 3;
    }
}
    else if(leftPressed)
    {
        if (manmc.x > 145)
        {
            manmc.x -= manSpeed;
        }
        manmc.gotoAndStop("Walk Left Frame");

        if (manmc.hitTestObject(treer1_MC))
    {
        trace("rightHit");
        manmc.x += 3;
    }
} 
      else if(downPressed)
{
    if(manmc.y < 780)
    {
    manmc.y += manSpeed;
    }
    manmc.gotoAndStop("Walk Front Frame");

    if (manmc.hitTestObject(treer1_MC))
    {
        trace("downHit");
        manmc.y -= 3;
    }
}
        else if(upPressed)
{
    if(manmc.y > 145)
    {
    manmc.y -= manSpeed;
    }
    manmc.gotoAndStop("Walk Back Frame");

    if (manmc.hitTestObject(treer1_MC))
    {
        trace("upHit");
        manmc.y += 3;
    }
}
}

Air WebView HTML/Javascript-Page does not show in iOS if it is generated at runtime

i am trying do display a small map in a crossplatform mobile application developed in Air. Since there is no native Map-API I decided to just use a simple Leaflet map and display it in a StagWebView. It works perfectly, when I load the HTML from a server, but does not show in the iOS Simulator or on a device if i pass the HTML as a String.

Is this maybe some security restriction because of the Javascript?

this is the html code:

<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="http://ift.tt/1TWUABO" />
    <title>Hello Map</title>
</head>
<body>
    <h1>Hello Map</h1>
    <div id="map" style="width: 200px; height: 200px"></div>
    <script src="http://ift.tt/1oZnLGo"></script>
    <script>
        var def_lat=42;
        var def_lng=13;
        var def_zoom_lvl=15;
        var def_position=[def_lat, def_lng];
        var mymap = L.map("map",{attributionControl: true}).setView(def_position, def_zoom_lvl);
        var openstreet= L.tileLayer('http://ift.tt/UdqNor', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="http://ift.tt/ItuEqj">OpenStreetMap</a>',
        });
        openstreet.addTo(mymap);
    </script>
</body>

and this is the simple AS code:

public static var XML_DATA:XML=<html lang="en">
        <head>
            <meta charset="utf-8">
        .....
        like above in html code

and then:

_map = new WebView();
_map.loadString(XML_DATA.valueOf().toString());
addChild(_map);

thanks for help.

samedi 27 juin 2015

Object Barriers in AS3?

I am a beginner at coding but I am trying to make a flash rpg type game. I have a barrier around my game and a walking person (manmc). I have been watching videos/reading articles on how to make object barriers but I can not seem to get the coding right without getting errors. I am trying to get my character to stop when he hits a tree. The tree is coded as (treer1_MC). I only tried to code it on the down press but it does nothing and it causes the character to not be able to walk back up.

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Stage;

manmc.gotoAndStop ("Stand Front Frame");

var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var manSpeed:Number = 3;

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);

function keyDownHandler (keyEvent:KeyboardEvent):void
{
    if(keyEvent.keyCode == Keyboard.RIGHT)
    {
        rightPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.LEFT)
    {
        leftPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.UP)
    {
        upPressed = true;
    }
    else if(keyEvent.keyCode == Keyboard.DOWN)
    {
        downPressed = true;
    }
}

function keyUpHandler (keyEvent:KeyboardEvent):void
{
    if(keyEvent.keyCode == Keyboard.RIGHT)
    {
        rightPressed = false;
        manmc.gotoAndStop("Stand Right Frame");
    }
    else if(keyEvent.keyCode == Keyboard.LEFT)
    {
        leftPressed = false;
        manmc.gotoAndStop("Stand Left Frame");
    }
    else if(keyEvent.keyCode == Keyboard.UP)
    {
        upPressed = false;
        manmc.gotoAndStop("Stand Back Frame");
    }
    else if(keyEvent.keyCode == Keyboard.DOWN)
    {
        downPressed = false;
        manmc.gotoAndStop("Stand Front Frame");
    }
}

function gameLoop(loopEvent:Event):void
{
    if(rightPressed)
    {
        if(manmc.x < 1050)
        {
            manmc.x += manSpeed;
        }
        manmc.gotoAndStop("Walk Right Frame");
    }
    else if(leftPressed)
    {
        if (manmc.x > 145)
        {
            manmc.x -= manSpeed;
        }
        manmc.gotoAndStop("Walk Left Frame");
    } 
    else if(downPressed)
    {
        if(manmc.y < 780)
        {
        manmc.y += manSpeed;
        }
        manmc.gotoAndStop("Walk Front Frame");
    }
        if (manmc.hitTest(treer1_MC))
    {
            trace("leftHit");
            manmc._x += 3;

    }
    else if(upPressed)
    {
        if(manmc.y > 145)
        {
            manmc.y -= manSpeed;
        }
        manmc.gotoAndStop("Walk Back Frame");
    }
}

This is the coding a tutorial said to use. Any suggestions?

if (manmc.hitTest(treer1_MC))
        trace("leftHit");
        manmc._x += 3;

AS3: hitTestObject turning up null for no apparent reason

I'm currently coding a game, and in one part of the code, it's checking to see if the player is close enough to a monster in mArray for its health bar to appear. I use hitTestObject for this with var i incrementing to go through the list. However, I will randomly get this error message:

TypeError: Error #2007: Parameter hitTestObject must be non-null.

After seeing this for the first time, I put the test all under the conditional if (mArray.length > 0) to make sure the Array() was filled before even attempting the test... but it still occurs at random times. I even used trace(i) to see if it happened on a certain part of the list, but it's completely random each debug session! I know the player portion can't be null since it is on the screen at all times during the hitTest, so I'm at a loss for words right now.

The portion of code in question (nothing else is related to this except for the use of mArray[i] in different places):

for (var i:int = 0; i < mArray.length; i++) {
    if (mArray.length > 0) {

        trace(i); //my attempt to see if it occurred at a specific incrementation of i

        if (player.hitTestObject(mArray[i])) {
            mArray[i].healthBar.visible = true;
        } else {
            mArray[i].healthBar.visible = false;
        }

    }
}

Again, it works perfectly for everything all of the time except for random cases it gives me the TypeError. Is this just a hiccup in my code, is there some obvious problem that I'm overlooking, or does the code just like to throwback to 2007?

EDIT: The debug session ALWAYS points to the line with if (player.hitTestObject(mArray[i])).

Use Custom Numbers in Flash Game

Hello! I am making a 8bit game, where I basically want to use old-school solutions for different things.

How can I use custom numbers (for example png-files of 0-9) instead of the regular font to show score and etc? For example; I have seen the sprite sheet of Flappy Bird, where there were custom number, which were used. I know I can use other fonts, but if this is possible, I think I will find this most satisfying for this project.

Thanks :)

How to Switch to a Frame Visually, Without Running its Actionscript?

I've run to a problem. I've got a SWF that is divided into frames. What I'm trying to do, is switch to one of my frames which has actionscript code, but I just want the visual elements to be displayed, without executing the actionscript code it contains.

I am trying to switch to this frame using gotoAndStop("frame-name");

I've tried to add a boolean value to the code in this frame, that decides whether or not it gets executed, I set the value the first time that frame's actionscript is executed, but this value is ignored as if using gotoAndStop creates a new instance of that frame's actionscript code, so it doesn't retain the boolean value I set.

Is there any way to not allow actionscript execution of this frame?

Thanks,

-CausingUnderFlowsEverywhere

How to convert interactive FLASH content into HTML5

We have lot of FLASH banners which need to be converted into HTML5. Googled a lot and came to a conclusion that only non-interactive FLASH content can be easily converted into HTML5. What is the right approach to convert 'interactive' flash content like the one below into HTML5

Button click
Opening a url in browser
Filling a input field or playing a youtube video

AS3 Running an External Program

So I am making something for a bit of fun but I was just wondering if it was possible to run an external program for example opening Chrome (and maybe even searching on it) by pressing a button.

Fisher-Yates Algorithm Explanation?

I'm wondering if some of you understand how the Fisher-Yates shuffle works and can explain it to me. so I found this Fisher-Yates Shuffle code online:

public function Main() {
var tempArray:Array = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
ShuffleArray(tempArray);
trace(tempArray);
}
public function ShuffleArray(input:Array)
{
for (var i:int = input.length-1; i >=0; i--)
{
var randomIndex:int = Math.floor(Math.random()*(i+1));
var itemAtIndex:Object = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
}

That code works perfectly but I'm still confused

  1. I changed the loop to "input.length" and it doesn't work well, I still got "0" values sometimes. I have no idea why should I use "input.length-1" instead of "input.length"
  2. At the randomize section, why should I randomize the index from 0 to the value (i+1), why don't we just randomize it from 0 to (i) instead?

If some of you understand it, can you please explain it to me? Thank you so much

Use the same array to next frame

Im making a game and i complete the level1 at frame1. When im trying to make the level2 to frame2 i dont know how to transfer my Arrays to frame2.All the other buttons and functions are working(i copy the eventListeners to frame2)but my enemies wich are in Arrays does nothing!! Thanks a lot!!! import flash.events.Event;

stop();
//variables the helicopters
var enemy1Array:Array = new Array();
    for (var e1:int = numChildren - 1; e1 >= 0; e1--) 
    {
        var child:DisplayObject = getChildAt(e1);
        if (child.name == "enemy1") 
        {
          enemy1Array.push(child);
        }
    }

stage.addEventListener(Event.ENTER_FRAME, allloop);
function allloop(event:Event):void
{
//move the helicopters
for each(var enemy1:Sprite in enemy1Array)
{
   enemy1.x = enemy1.x -= enemy1speed;
   if(enemy1.hitTestObject(defense))
   {
            addChild(explotionbonus3);
            explotionbonus3.gotoAndPlay(2);
            explotionbonus3.x = enemy1.x;
            explotionbonus3.y = enemy1.y;
            enemy1.y = 1000;
            score -=5;
            scoretxt.text = String (score);
   }
}
}

AS3 - Change MovieClip-Color Using Filters

I wonder how I can create an "Adjust Color"-filter in AS3.

I created a red box in Photoshop (8x8px), saved it as a PNG-file, then I imported it to Flash. I converted the file to a MovieClip-symbol. I applied an "Adjust Color"-filter. With that I can change the color easily, but I want to get the same effect in AS3.

Does anyone have a clue on how? Thanks:)

vendredi 26 juin 2015

AS3 Change picture-color inside symbol

I am kinda new to Adobe Flash, but I got some experience. I am trying to create a simple game. I was using the basic vector-based graphic which is simply made inside Flash. I created a square with the rectangle tool, but I recently decided that it would look better if it was more "old-school", so i created a 8x8px image in Adobe Photoshop. I imported that to Flash and converted it to a symbol. Then I added it to the stage, added an Adjust Color-filter, and then I was able to change the color of the image using those filter-adjustments.

I want to be able to change the color of the boxes in AS3. I see that I can create several layers with different colors and etc., but I want to do that using AS3. I am planning to use the box as the player-character, so I want to make it easy to change the color from for example green to blue, and blue to red (for different skins). Any suggestions? :)

How to Improve FLVPlayback - Reduce Choppy Video

I have a 1920x1080 video playing inside a flash project with the same dimensions, using Firefox. The project is using CC2015, Latest Flash Player, Latest FF. I should note that this project is using locally stored videos.

I'm using AS3, FLVPlayback component, and the videos have been compressed (by production).

Heres the code that uses the playback component

function playVideoByString(source: String): void {
    hideTheButtons();
    attractTimer.stop();
    movie_container = new MovieClip();
    addChild(movie_container);
    movie_container.x = 0;
    movie_container.y = 0;

    launchVideo(movie_container, source);
}

function launchVideo(vBox, vFile): void {
    attractTimer.stop();
    flvPlayer = new FLVPlayback();
    flvPlayer.source = vFile;
    flvPlayer.skinAutoHide = true;
    flvPlayer.skinBackgroundColor = 0x000000;
    flvPlayer.width = 1920;
    flvPlayer.height = 1080;
    flvPlayer.autoRewind = false;
    cuePt.time = 0.9;
    cuePt.name = "ASpt1";
    cuePt.type = "actionscript";
    flvPlayer.addASCuePoint(cuePt);
    vBox.addChild(flvPlayer);
    // adding listeners in here
    flvPlayer.addEventListener(MetadataEvent.CUE_POINT, cp_listener);
    flvPlayer.addEventListener(fl.video.VideoEvent.COMPLETE, completeHandler);
}

Playback is experiencing some degradation in the form of what looks like frames dropping, or "stutter." The animations look glass smooth when the MP4 is opened in Firefox and played back using FFs player. They also look fine when played in QuickTime (obviously). The video is 30FPS, as is the Flash Project, though from what I understand, FLVPlayback will use the videos encoded frame rate regardless of Flash's FPS.

Is there anything I can do to improve the video playback, and possibly smooth the videos out without loosing quality?

C# communication with a flash server

This question may seem simple but I am just starting out and I can't find conclusive answers on the tutorials and other questions I am trying to search through. The basic project idea is a client, which I intend to program in c#, that will communicate with an external flash server using AS3, interpret the data and send commands back, ie a bot that isn't one of the click macros that most posts are on because this wouldn't be interesting from an academic perspective which is the whole point of the endevour, I would be replicating the commands sent by the actual client. The question this brings, as the first major hurdle of the project is how do I sent these commands, in terms of syntax? If I set up a socket I don't understand how I would parse the data going between if they are both in seperate languages, which is a necessity as AS3 isn't suited to my needs at all. Would I be sending a strong containing as3 syntax?

Thanks in advance, T

ActionScript - Number.toExponential rounding

I'm developing a Scientific Calculator using Adobe AIR. I'm aware Flash is not a great platform for math, however that is decided. I expect Flash's double-precision floating-point format should be adequate for a scientific calculator comparable to a hardware one (e.g. Casio FX series). I've become aware about the many pitfalls of using binary floating-point formats for computations with (decimal) numbers, and will surely ask more questions about that lately.

I'm developing the calculation results display, for that I need to format a numeric value into one of several display modes. Depending on the mode, I need to either round half away from zero, or round towards zero (truncate extra digits). I've written my own formatting function which converts the Number to a string using Number.toExponential, breaks down the string using RegExp, rounds to the desired number of digits with the desired rounding mode and returns the string in the desired format. The reason I used Number.toExponential because it's the only function that outputs any number from very small to very large in the same format, so that is easy to parse and work with.

However I found out that toExponential have some strange behaviour when it comes to rounding. It appears to me that it truncates the extra digits instead of rounding half away from zero (or half to even or whatever). AS3 docs don't mention any details about rounding.

const number1:Number = 0.000000123455555555544;
trace(number1.toString());        // 1.23455555555544e-7
trace(number1.toExponential(14)); // 1.23455555555543e-7
trace(number1.toExponential(20)); // 1.23455555555543993039e-7
const number2:Number = 0.000000123455555555567;
trace(number2.toString());        // 1.23455555555567e-7
trace(number2.toExponential(14)); // 1.23455555555566e-7
trace(number2.toExponential(20)); // 1.23455555555566995278e-7

It appears that Number.toString() performs correct rounding and returns the same number as the literal values used in the code to initialize the constants. But toExponential, set to print the same number of digits as toString returns for these particular numbers, appears to always round to zero.

Some more examples.

const DOUBLE_MIN:Number = 4.94065645841246544176e-324;
trace(DOUBLE_MIN.toString());        // 4.9406564584124654e-324
trace(DOUBLE_MIN.toExponential(16)); // 4.9406564584124654e-324
trace(DOUBLE_MIN.toExponential(20)); // 4.94065645841246544176e-324
const DOUBLE_MIN_NORMAL:Number = 2.22507385850720138309e-308;
trace(DOUBLE_MIN_NORMAL.toString());        // 2.2250738585072014e-308
trace(DOUBLE_MIN_NORMAL.toExponential(16)); // 2.2250738585072013e-308
trace(DOUBLE_MIN_NORMAL.toExponential(20)); // 2.22507385850720138309e-308
const DOUBLE_MAX:Number = 1.79769313486231570814e+308;
trace(DOUBLE_MAX.toString());        // 1.79769313486231e+308
trace(DOUBLE_MAX.toExponential(14)); // 1.79769313486231e+308
trace(DOUBLE_MAX.toExponential(20)); // 1.79769313486231570814e+308

Is this the expected behavior of toExponential? If so, I'm forced to use toString and have two different RegExps (or one more complicated RegExp), depending on if toString prints the number in normal format or exponential notation.

I was also considering using toExponential, then rounding it to 16 (or 15?) digits, and then finally rounding to my desired number of digits (according to the display mode). However such double rounding generally can create problems (e.g. assuming half away from zero rounding, 9.49 rounded to 1 decimal digit gives 9.5, then rounded second time to whole number gives 10; but 9.49 rounded straight to whole number gives 9). I wonder if in this situation there's some reason double rounding could be used?

Any advice is welcome, as well as explanations (or refuting examples) on why my ideas are wrong.

Apologies for such verbose writing, when I'm writing I can never figure out what I should cut, cut, cut. And apologies if I made mistakes with my language, English is not my native language.

call a function multiple times without conflict in actionscript

I have some dots on stage and want to connect them with lines . i use this function to Animate drawing of lines . i found it here

var fromX:Number;
var fromY:Number;
var toX:Number;
var toY:Number;
var dx:Number;
var dy:Number;
var increment:Number;
var origToX:Number;
var origToY:Number;
var origDiffX:Number;
var origDiffY:Number;
var pDiffX:Number;
var pDiffY:Number;
var multiplier:Number;

function drawLineProgressively(fromX:Number, fromY:Number, toX:Number, toY:Number, multiplier:Number):void
{
      trace("Public function drawLineProgressively called.")
      this.fromX = fromX;
      this.fromY = fromY;
      this.toX = toX;
      this.toY = toY;
      origToX = toX;
      origToY = toY;
      dx = toX - fromX;
      dy = toY - fromY;
      increment = Math.max(Math.abs(dx), Math.abs(dy));
      increment = Math.round(increment / multiplier);
      dx /= increment;
      dy /= increment;
      graphics.lineStyle(1, 0Xff0000)
      addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onEnterFrame(e:Event):void
{
      var tx:Number;
      var ty:Number;
      trace("Adding:", dx, "to x.");
      trace("Adding:", dy, "to y.");
      tx = fromX + dx;
      ty = fromY + dy;
      origDiffX = Math.abs(tx - origToX);
      origDiffY = Math.abs(ty - origToY);
      origDiffX = Math.round(origDiffX);
      origDiffY = Math.round(origDiffY);
      trace("Orig DiffX:", origDiffX);
      trace("Orig DiffY:", origDiffY);
      if ((pDiffX > origDiffX) || (pDiffY > origDiffY) || (!pDiffX) || (!pDiffY))
      {
              trace("true 2");
              trace("Drawing from: ", fromX, ",", fromY, "to:, ", tx, ",", ty);
              graphics.moveTo(fromX, fromY);
              graphics.lineTo(tx, ty);
              pDiffX = origDiffX;
              pDiffY = origDiffY;
      }
      else
      {
            tx = origToX;
            ty = origToY;
            trace("Last Draw!")
            trace("Drawing from: ", fromX, ",", fromY, "to:, ", tx, ",", ty);
            graphics.moveTo(fromX, fromY);
            graphics.lineTo(tx, ty)
            increment = 0;
      }
      fromX = tx;
      fromY = ty;
      increment--;
      if(increment <= 0)
        removeEventListener(Event.ENTER_FRAME, onEnterFrame); 
}

then i call it in different frames like this

drawLineProgressively(nude1.x, nude1.y, nude2.x, nude2.y,5);

the problem is when it draw lines at the same time it stops working and i cant use it to draw multiple of lines at the same time

drawLineProgressively(nude2.x, nude2.y, nude3.x, nude3.y, 20);
drawLineProgressively(nude2.x, nude2.y, nude4.x, nude4.y, 10);

im new in flash and sorry for my bad en

Flash CS6/as3: Using cursor to draw rectangle dynamically in a published swf

I'm having a bit of a problem. I'm creating a swf that will allow someone to draw a rectangle dynamically in a published swf, then they can drag a shape and place it within the rectangle they just drew.

I have the swf working so that you can draw a rectangle, no problem. Where the issue arises is when trying to drag one of the shapes on the screen into the newly-drawn rectangle, it ends up drawing another rectangle while the shape is being dragged.

My question, I guess, is how do I "turn off" the code that allows for a rectangle to be drawn after I've drawn the one I want to use?

This is the code I used for drawing the rectangle (I got this from a tutorial online). The draggable shapes don't show up until the rectangle has been drawn (they are on the next frame):

stop();

import flash.display.Shape;

var temporaryDrawing:Shape = new Shape();
addChild(temporaryDrawing);
temporaryDrawing.graphics.lineStyle(3, 0x000000, 1);

var myDrawing:Shape = new Shape();
addChild(myDrawing);
myDrawing.graphics.lineStyle(3, 0x000000, 1);

var mouseHolding:Boolean=false;
var clickedX:Number;
var clickedY:Number;


stage.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mUp);

function mDown(MouseEvent):void{
    mouseHolding = true;
    clickedX = mouseX;
    clickedY = mouseY;
}

function mUp(MouseEvent):void{
    mouseHolding = false;
    myDrawing.graphics.drawRect(clickedX, clickedY, mouseX-clickedX, mouseY-clickedY);
    nextFrame();
    clearTemp ()
}

stage.addEventListener(MouseEvent.MOUSE_MOVE, mMove);
function mMove(MouseEvent):void{
    if (mouseHolding){
        clearTemp ();
        temporaryDrawing.graphics.drawRect(clickedX, clickedY, mouseX-clickedX, mouseY-clickedY)

    }
}

function clearTemp():void{
    temporaryDrawing.graphics.clear();
    temporaryDrawing.graphics.lineStyle(3, 0x000000, 1)
}

ActionScript: Number.toExponential returns incorrect results for some values

I found at least two numbers for which ActionScript's Number.toExponential(20) returns incorrect results.

The most obvious value is 0.

trace(Number(0).toExponential(20)); // 0.00000000000000000000e-16
trace(Number(0).toExponential(2));  // 0.00e-16
trace(Number(0).toExponential(1));  // 0.0e-16
trace(Number(0).toExponential(0));  // 1e-15 - even worse!

I've made a class Double for playing around with Numbers (which are IEEE 754 double-precision binary floating point format numbers). It takes a Number and extracts all the bits into sign, bits and significand (the latter is printed including the implicit leading bit), or can generate a Number provided sign, bits and significand. There are methods to get the next and prior nearest representable numbers. Here's what 0 looks like internally:

[Double number=0.00000000000000000000e-16 sign=1 exponent=-1023 isZero
significand=00000000000000000000000000000000000000000000000000000]

The other incorrect results are the nearest representable Number greater than Number.MAX_VALUE / 2 and Number.MAX_VALUE / 4.

// Number.MAX_VALUE / 2.
trace(Number(8.98846567431157854072e+307).toExponential(20)); // 8.98846567431157854072e+307
// Nearest representable Number greater than Number.MAX_VALUE / 2. Printed incorrectly!
trace(Number(8.98846567431157953864e+307).toExponential(20)); // 0.e+327
// A Number two ULPs greater than Number.MAX_VALUE / 2.
trace(Number(8.98846567431158153448e+307).toExponential(20)); // 8.98846567431158153448e+307
// Nearest representable Number greater than Number.MAX_VALUE / 4. Printed incorrectly!
trace(Number(4.49423283715578976932e+307).toExponential(20)); // 0.e+327

Here's what these 4 numbers look like internally:

[Double number=8.98846567431157854072e+307 sign=1 exponent=1022 
significand=11111111111111111111111111111111111111111111111111111]
[Double number=0.e+327 sign=1 exponent=1023 
significand=10000000000000000000000000000000000000000000000000000]
[Double number=8.98846567431158153448e+307 sign=1 exponent=1023 
significand=10000000000000000000000000000000000000000000000000001]
[Double number=0.e+327 sign=1 exponent=1022 
significand=10000000000000000000000000000000000000000000000000000]

So far all three numbers that are printed incorrectly have a 0 significand (with implicit leading 1), and the exponent values of 1023 (Emax for normal numbers), 1022 (Emax - 1), or -1023 (special exponent value for ±zero and subnormal numbers, Emin - 1).

Looks like toExponent doesn't correctly handle at least these three cases . Are there any other numbers that would print incorrectly?

Trying to check if toExponential would produce correct results with other precision values.

trace(Number(8.98846567431157953864e+307).toExponential(2)); // 0.e+309
trace(Number(8.98846567431157953864e+307).toExponential(1)); // 0.e+308
trace(Number(8.98846567431157953864e+307).toExponential(0)); // 1e+308 - less bad!

If anyone interested in my Double class I will post it. I've also written faster implementations next(x:Number) and prior(x:Number) functions which work pretty fast without messing with internal bits of the numbers.

References: http://ift.tt/1pP815z

Trigger a function when specific frame number is reached - AS3

I wanted friends, do the following when my MC get a determanido internal quandro, it triggers a function to another MC. for example when the ball hit the wall, a person goes to search - la, I have tried using :

("root") {root.MC.play ()}

Translation from comments:
Friends, I have an MC_1 with 10 frames, when it reaches frame 5, I want another movieClip MC_2 to respond (eg: to move or fade etc)

Are there any Problems with unclosed sockets

I`m writing a little server programm in C++, client is a Flash AS3 SWF. At the moment I use polling if there is any input from the client. If I would close the client programm, is it possible to send one last message that the programm will close and the server will close too, or is it not and I have to close the server by hand and leave some unclosed sockets. If so, will I get in trouble with these unclosed sockets? I´d be nice if you can give me some solutions/answers for my problem/question

Tanks ins advance

ColorTransform for multiple movie clips

Despite searching both the web and youtube for a solution, it remains difficult to find information on colorTransforming multiple movie clips in AS3. I found a video on youtube about colorTransform which i followed steps to create a fully functional colorTransform for a single clip but i would like to use it for multiple clips and be able to change colors for each on a mouse click.

I have included the code below and perhaps someone knows how i can add more movie clips to it. When i copy and change mc1. EventListener code to mc2, i get a duplicate function error which i don't know how to fix.

import flash.geom.ColorTransform;
import flash.geom.ColorTransform;
import flash.events.MouseEvent;

// this here is the little movieclip where the main clip gets its color from,the clip is made up of two movieclips but can also be one movieclip
// instead of brushColor i have used myColor and instead of brush.tip i have used square.
var myColor:ColorTransform=new ColorTransform();
myColor.color=0xffffff; square.transform.colorTransform=myColor

red.addEventListener(MouseEvent.CLICK,onclick);
green.addEventListener(MouseEvent.CLICK,onclick);
blue.addEventListener(MouseEvent.CLICK,onclick);
orange.addEventListener(MouseEvent.CLICK,onclick);
yellow.addEventListener(MouseEvent.CLICK,onclick);
pink.addEventListener(MouseEvent.CLICK,onclick);

function onclick(event:MouseEvent){

    if(event.target==red)
    {myColor.color=0xff0000}

    else if(event.target==green)
    {myColor.color=0x99ff33}

    else if(event.target==blue)
    {myColor.color=0x00ccff}

    else if(event.target==orange)
    {myColor.color=0xffcc33}


    enter code here
    else if(event.target==yellow)
    {myColor.color=0xffff66}

    else if(event.target==pink)
    {myColor.color=0xff99ff}

    else
    {myColor.color=0x666666}
    square.transform.colorTransform=myColor

}


mc1.addEventListener(MouseEvent.CLICK, colorChange);
function colorChange(event:MouseEvent)
{
    mc1.transform.colorTransform=myColor;
}


// upto here the code works fine but from below i get a  duplicate fuction error which i don't know how to fix.
// the idea is to add more movie clips so i can change their colors just like i can do for mc1.

1021: DUPLICATE FUNCTION DEFINITION "ERROR"

mc2.addEventListener(MouseEvent.CLICK, colorChange);
function colorChange(event:MouseEvent)
{
    mc2.transform.colorTransform=myColor;
}

Will appreciate your help,

Best regards,

lottorist

Rotate video in video player adobe flex

I am trying to rotate video in default video player in adobe flex like following way.

videoPlayer.videoDisplay.rotation = 90;

It will rotate video but can not change video width and height. It will display with small width.

I tried changing video width like:

videoPlayer.videoDisplay.width = 600;

But not success.
Is there any solution for that?

jeudi 25 juin 2015

Is it possible to call secure flash SWF function from non secure page?

I have a non secure (http) page, which is loading a secure (https) SWF and a secure (https) JS. When I try to call a Flash SWF function from the JS, it isn't getting called at all.

this.thisMovie(this.id).addButton(controlName);

I have crossdomain policy files properly defined in all the servers and Flash has the code added for Security.allowDomain("*"). *allowScriptAccess *is also set to always. The call works fine when the page is secure (https) or when everything is non secure.

I am wondering if it's even possible, and if yes, what do I need to do?

Create AS3 countdown clock without using users system Clock

I need to create an as3 countdown clock for a TV display with no system clock.

How can I utilize the Date object for this?

Adobe Flash App -- Unique Device ID

I'm developing an application using Adobe Flash (AS3) which runs mainly on tablets. I would like users to pay. So they have to activate their application. To do this I thought about providing an activation Code that is built using a univoque Device Identifier (UDID) So, the customer provides me his UDID and I return the activation code which works only on his device. My problem is (I searched everywhere)... how can I obtain an UDID using AS3? Or also, do you suggest a different approch to reach my goal?

Thank you very much!

Daniele

Adobe AIR Stage.contentsScaleFactor always 1 on iPhone4s and iPad mini

My application is just a template AIR Mobile AS3 project from FlashDevelop: application.xml file, and a Main class.

In the Main class, I create a text field with stage.contentsScaleFactor value as a text after the first Event.RESIZE:

var textField:TextField = new TextField();
textField.appendText("Size: " + stage.stageWidth + " x " + stage.stageHeight + "\n");
textField.appendText("Scale: " + stage.contentsScaleFactor + "\n");
addChild(textField);

On my iPhone with retina support, i get

Size: 960 x 640

Scale: 1

for

<requestedDisplayResolution>high</requestedDisplayResolution>

and

Size: 480 x 320

Scale: 1

for

<requestedDisplayResolution>standard</requestedDisplayResolution>.

Almost the same for iPad,

Size: 2048 x 1536

Scale: 1

for high, and

Size: 1024 x 768

Scale: 1

for standard.

I'm compiling with the latest AIR SDK 18.0.0.142 (beta), -swf-version=29. Same results for release AIR SDK 18.

For AIR 14 SDK and -swf-version=25, I get some garbage values for size (it looks like my swf width and height multiplied by what contentsScaleFactor should be), but still 1 for contentsScaleFactor.

Am I missing something important about contentsScaleFactor property? Or how can I determine that my application is running on hidpi display?

How to change bitmap without adding another child to the stage

I know exactly what this function is doing, however I don't know how to change it so that the 3 symbols only ever add once and only the bitmaps change. Thank you for your help! It's probably something simple, but I can't seem to figure it out, I am an intermediate as3 programmer but still have some holes in my knowledge.

var randCount:int = 3
        function loadImage():void
        {
            for(var i:int = 0; i<randCount; i++)
            {
                var imgLoader:Loader = new Loader();
                var imgRequest:URLRequest = new URLRequest();
                imgRequest.url = "../img/planet" + int(2*Math.random()) +".png";
                trace(imgRequest.url);
                imgLoader.load(imgRequest);
                imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedImg);
            }
        }

        function onLoadedImg(e:Event):void
        {
            e.currentTarget.removeEventListener(Event.COMPLETE, onLoadedImg);
            var bmp:Bitmap = e.currentTarget.content;
            bmp.x = 600;
            bmp.y = Math.random() * 520;
            bmp.width = 80;
            bmp.height = 80;
            addChild(bmp);

        }
button.addEventListener(MouseEvent.CLICK, changeBitmap);
        function changeBitmap(event:MouseEvent):void {
            loadImage();
        }

Can't make MovieClip in function dissapear

I'm trying to make simple shooting game with Fiat Multipla falling up to bottom of the screen. I have created function to generate falling multipla and within this function I have a problem.

The main issue is that after change of multideath status to 1 "Death" function does nothing even if It is kept with ENTER_FRAME. Child becomes invisible as I implemented it in multipla movieclip, but even after response from there with Death = 1, nothing happens.

I'm new to all this, I've met and solved few issues during programming, but here's my brickwall for now. Code's either failing completely or I don't know something that's obvious. As I said, I'm newbie.

Thanks a lot for help!

Here's the function:

import flash.events.Event;
import flash.desktop.NativeApplication;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;

Mouse.hide();
var velocity = 0;
var ammo = 6;
LGUI.LGUIammo.gotoAndStop(6);

var counter = 0;

function multiplarain()
{

var x1 = Math.ceil(Math.random() * 280);
var y1 = -200;
var random:Multipla = new Multipla();
var life = 265;
var multideath = 0;

random.x = 100 + x1;
random.y = y1
addChild(random);
random.gotoAndStop(1);
setChildIndex(random, +1);

addEventListener(Event.ENTER_FRAME, Death);
    function Death(event:Event):void
    {
        if(multideath >= 1)
        {
        removeEventListener(Event.ENTER_FRAME, Death);
        removeChild(random);
        }
    }

addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);

    function fl_EnterFrameHandler(event:Event):void
        {
            if(random.y >= 680)
            {
            removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler)
            removeChild(random);
            trace("rofl");
            }
        }

random.addEventListener(Event.ENTER_FRAME, fl_AnimateVertically);

    function fl_AnimateVertically(event:Event)
    {
        velocity = velocity + 0.000035;
        random.y += 1.5 + velocity;
    }

random.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler);

    function fl_TapHandler(event:TouchEvent):void
    {
        counter = counter + 1;
        ammo -= 1;
    }

if(ammo == 6)
{
    LGUI.LGUIammo.gotoAndStop(6);
}       
if(ammo == 5)
{
    LGUI.LGUIammo.gotoAndStop(5);
}               
if(ammo == 4)
{
    LGUI.LGUIammo.gotoAndStop(4);
}
if(ammo == 3)
{
    LGUI.LGUIammo.gotoAndStop(3);
}
if(ammo == 2)
{
    LGUI.LGUIammo.gotoAndStop(2);
}
if(ammo == 1)
{
    LGUI.LGUIammo.gotoAndStop(1);
}
if(ammo <= 0)
{
    LGUI.LGUIammo.gotoAndStop(7);
}

HGUI.saved.text = counter;  
this.addEventListener( Event.ENTER_FRAME, handleCollision)

var kucyk = LGUI.LGUIlife.lifeitself;

function handleCollision(e:Event):void
{
    if (random.hitTestObject(LGUI))
    {
        kucyk = LGUI.LGUIlife.lifeitself;
        kucyk.width -= 0.1;
    }
    /*if (kucyk.width == 0.75)
        {
            trace("cycki");
            NativeApplication.nativeApplication.exit(); 
        }*/
    }
}

and here's multipla's movieclip in library code:

Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
this.addEventListener(TouchEvent.TOUCH_TAP, fl_TapHandler2);

function fl_TapHandler2(event:TouchEvent):void
{
    this.gotoAndPlay(2);
}


addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);

function fl_EnterFrameHandler(event:Event):void
{
    if(this.currentFrame == 60)
    {
        this.visible = false;
        MovieClip(root).multideath = 1;
        trace(MovieClip(root).multideath);
        removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
        removeEventListener(Event.ENTER_FRAME, fl_TapHandler2);
    }
}

How to fix the landscape issue for flash android games

I developed the game Which should be in landscape.If my app is maximized some times it will display half of the screen only remaining it shows blank screen.But it will Occur some times only. The width and heights are interchanged.

I used the aspectRatio : landscape

stage.scaleMode = StageScaleMode.EXACT_FIT; stage.align = StageAlign.TOP_LEFT;

but my android app is should be in landscape mode and fit to all the screens. How can I resolve this issue. I am new for the mobile development.

Can we get supported paper size of printer in Actionscript 3

Can we get supported paper size of printer in Actionscript 3? I read the help document of adobe PrintJob class but can not find the method to get the list of paper size of printer. Thanks.

Adobe Air - Starling/Features | Controls and device simulator

I have few questions here, regarding creating app in Adobe Air using Starling and feathers.

I created yet a very simple app, which has Feathers list controller with static data provided to its dataProvider. According to the code it should work fine, but there are three major issues I am facing.

1: Touch/Click Positions

I am using:

list.addEventListener( Event.CHANGE, list_changeHandler );

Now the problem is, clicking coordinates are not correct. Clicking on 3rd Item triggered 4th item, to trigger 3rd, 2nd item needs to be clicked it's half way through etc.

2: Nothing, without Theme

I am using a custom theme, came along with a tutorial. If I don't use the theme, I am unable to see anything on the screen, somehow.

3: Resolution (Device Simulator) Problem

Though buggy, but it works with Theme, but my app doesn't fit with the resolution for each device simulator. Either its, iPad or iPhone 4 or any android simulator.

Also, can anyone please also explains, what is significance and use of Context3D render mode in starling class.

Any help is appreciated:

Thanks in advance Waqar Iqbal

ActionScript3: removeEventListener with function parameter

how can i removeVentListener from movieclip in actionsctip? Below is my sample code.

import flash.events.MouseEvent;
import flash.geom.ColorTransform;
var color: ColorTransform = new ColorTransform();
color.color = 0x00CC66;
colorChange_mc.buttonMode = true;
colorChange_mc.addEventListener(MouseEvent.MOUSE_OVER, changeColor(color));
colorChange_mc.addEventListener(MouseEvent.MOUSE_OUT, changeColorToNormal);

function changeColor(color: ColorTransform): Function {
    return function (e: MouseEvent): void {

        colorChange_mc.transform.colorTransform = color;
      }
 }

 function changeColorToNormal(e: MouseEvent): void {
      var color: ColorTransform = new ColorTransform();
      color.color = 0x000033;
       colorChange_mc.transform.colorTransform = color;
 }


  changer_mc.buttonMode = true;
  changer_mc.addEventListener(MouseEvent.MOUSE_DOWN, removeEvent);
  function removeEvent(e: MouseEvent): void {
       colorChange_mc.removeEventListener(MouseEvent.MOUSE_OVER,      changeColor(color));

  }

I created wto movieClips on the stage , colorChange_mc has two eventListeners one for mouseDown and one for mouseOut. When change_mc button is pressed I want to remove one of the eventListener. I was able to remove eventListener without passing parameter to changeColor function. But in my real class this parameter plays crucial role.

App Screen is moved down (on ios device)

Steps to reproduce:

  1. I opened social login form(vk)
  2. Change phone rotation.
  3. Click "Cancel" on form and back to app.
  4. App screen is moved down.

My AS3/Adobe Air app on ios with settings

<fullScreen>true</fullScreen> <autoOrients>false</autoOrients> <renderMode>direct</renderMode> <visible>true</visible> <aspectRatio>portrait</aspectRatio>

and

stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT;

use flex sdk 4.6.0.23201 air 17.0.0.123

Can I disable rotation or something?

mercredi 24 juin 2015

How can I tell Adobe AIR is running an APK on BlackBerry OS?

I repacked an APK into a BlackBerry BAR and uploaded it successfully to the BlackBerry market. I am using Adobe AIR. How can I tell if my app is running on an actual Android device or a Blackberry device ? If I use Capabilities.manufacturer, it always returns "Android".

Thanks !

download values of sql table for offline reuse

I've got a Flash app that calls an online php file in order to read some values of my SQL table.

So I've got a line like this in my AS3 code:

var urlReq:URLRequest = new URLRequest ("http://ift.tt/1Ke84WK");

And this in my php :

 $connection = mysql_connect("mysql***.perso", "test", "password") or die ("Couldn't connect to the server.");

Problem : if the user is offline he can't access the values.

Is there way to download the SQL table with AS3 code (when the user have internet) in order to access it offline.

Like :

function onConnection(e:Event = null):void{
if(monitor.available)
            {
                trace("You are connected to the internet");
                read_php_online();
            }
            else
            {
                trace("You are not connected to the internet");
                read_php_offline();
            }

            monitor.stop();
        }

function read_php_offline():void{
    var urlReq:URLRequest = new URLRequest ("local/sql_result_offline.php");
..
..
}

And what should have sql_result_offline.php in order to access an offline SQL Table ?

 $connection = mysql_connect("LOCAL", "user", "password");

Thank you,

How to create delay/interval after receiving data from Arduino to Flash

I am working on both arduino and flash, I wanted to create a delay(like the timer function) when receiving data and display it in flash swf file.

I've successfully in displaying the data coming from arduino to flash, however, every time i pressed the pressure sensor, the data display in swf become clustered due to not having the interval/delay/timer function.

I've tried around and look through forums to get and idea but it unsuccesfull, I am relatively noob to action script 3.0, could anyone shed some light/guidance to what am I doing wrong?

Do I need to create seperate timer and create a new function and if so, how would I associate it with the "onTick2"?

Thank you.

a.addEventListener(ArduinoEvent.ANALOG_DATA, onTick2);

function onTick2(e:ArduinoEvent):void
{
  var forceValue:Number;
  var forceNum:Number;
  forceValue = a.getAnalogData(0); //this is the code to get the data from the sensor data in arduino
  forceNum = (forceValue/9.1);


  myFormat = new TextFormat();
  myFormat.font = "Arial";
  myFormat.size = 36;
  myFormat.color = 0xFFFFFF;

  myText = new TextField();
  myText.x = 250;
  myText.y = 240;
  myText.text ="\n"+forceNum.toString()+" Avg. Pressure";
  myText.height = 200;
  myText.width = 200;
  myText.defaultTextFormat = myFormat;

  addChild(myText);

}

Is there an event I can listen for that will tell when the Flash object was paused?

If I pause the entire Flash object (E.G, swfobject.getObjectById('Object').StopPlay();) is there an event that I can capture within Flash to tell me when this has happened?

Removing child from MovieClip's timeline

I'm loading swf file and creating MovieClip object from Linkage in swf Library. There are two frames in MovieClip timeline, separated, no tween. There is no code in frames or at objects. All the objects in frames are MovieClips and has one frame with graphic in it. There are 12 objects at first frame and 1 at second frame.

swf file first frame

I'm trying to remove one of the objects from first frame:

var mc:MovieClip = new clss() as MovieClip;
trace("total frames: "+mc.totalFrames);
mc.gotoAndStop(1);
trace("first frame numChildren: "+mc.numChildren);
mc.removeChildAt(0);
trace("first frame numChildren: "+mc.numChildren);
mc.gotoAndStop(2);
trace("second frame numChildren: "+mc.numChildren);
mc.gotoAndStop(1);
trace("first frame numChildren: "+mc.numChildren);

And I got:

total frames: 2
first frame numChildren: 12
first frame numChildren: 11
second frame numChildren: 1
first frame numChildren: 12

Why is there again 12 objects?

How to get username of a user logged in using this ANE in Google Play Services?

I am using this (http://ift.tt/1h7HxNv) ANE to login to Google Play Services and everything is okay, but there is no function to get logged in username.

Is there a work-around for this ? Like creating a function in ANE and rebuild or other ANE alternatives ?

Any help would be appreciated. Thanks!

How to embed HTML url pages in adobe flex?

I have a desktop adobe flex application and would like to show the content of an URL. How could a HTML page be best embedded into a desktop flex app?

I know there is some old mx:HTML location="{url}" but this seems to have many rendering and javascript issues.

I don't want to open an external browser window.

Adobe AIR Android: SWF is reloaded when app is reactivated after being idle

I'm porting my AIR game to Android.

When the app is deactivated (loses fucus, but it's still running in the background), for example by pressing the Home key, and then user taps the app's icon to bring it into focus again, the runtime re-loads the SWF and there's two instances of the same SWF running on top of each other.

As far as I can tell, the runtime itself is not reloaded, only the SWF.

When I manually kill the process, and re-launch the app, all is fine. The whole thing happens only if the app remains in memory and is re-activated after being idle.

Is this a bug, or am I missing some property that needs to be set?

The runtime version is 17.

Thanks.

how to fix error 1009 in flash as3

hi i have been trying to fix this by searching the net for hours and have had no luck so all help is appreciated (it happened when i put the snow in) Thanks in Advance

Here's my code:

Quit.addEventListener(MouseEvent.CLICK, func22);

function func22(event:MouseEvent):void
{
    gotoAndStop(2);
    myTimer3.stop(); myTimer3.removeEventListener(TimerEvent.TIMER, timerListener3);
    myTimer4.stop(); myTimer4.removeEventListener(TimerEvent.TIMER, timerListener4);
}

Help.addEventListener(MouseEvent.CLICK, func33);

function func33(event:MouseEvent):void
{
    gotoAndStop(23);
    myTimer3.stop(); myTimer3.removeEventListener(TimerEvent.TIMER, timerListener3);
    myTimer4.stop(); myTimer4.removeEventListener(TimerEvent.TIMER, timerListener4);
}

var myTimer3:Timer = new Timer(2000,0);
myTimer3.addEventListener(TimerEvent.TIMER, timerListener3);
function timerListener3(e:TimerEvent):void {
Hungry_bar.scaleX-=0.05;
if(Hungry_bar.scaleX<=0.05){
        gotoAndStop(12)
        myTimer3.stop(); myTimer3.removeEventListener(TimerEvent.TIMER, timerListener);
        myTimer4.stop(); myTimer4.removeEventListener(TimerEvent.TIMER, timerListener);
    }
}
myTimer3.start();

var myTimer4:Timer = new Timer(3000,0);
myTimer4.addEventListener(TimerEvent.TIMER, timerListener4);
function timerListener4(e:TimerEvent):void {
Fun_bar.scaleX-=0.05;
if(Fun_bar.scaleX<=0.05){
        gotoAndStop(13)
        myTimer3.stop(); myTimer3.removeEventListener(TimerEvent.TIMER, timerListener3);
        myTimer4.stop(); myTimer4.removeEventListener(TimerEvent.TIMER, timerListener4);
    }
}
myTimer4.start();

Feed.addEventListener(MouseEvent.CLICK,feed2)
function feed2(e:MouseEvent){
Hungry_bar.scaleX+=0.05
if(Hungry_bar.scaleX>=1.5){
    gotoAndStop(14)
    myTimer3.stop(); myTimer3.removeEventListener(TimerEvent.TIMER, timerListener3);
    myTimer4.stop(); myTimer4.removeEventListener(TimerEvent.TIMER, timerListener4);
    }
}

Fun.addEventListener(MouseEvent.CLICK,happy2)
function happy2(e:MouseEvent){
    Fun_bar.scaleX+=0.05
    if(Fun_bar.scaleX>=1.5){
    gotoAndStop(15)
    myTimer3.stop(); myTimer3.removeEventListener(TimerEvent.TIMER, timerListener);
    myTimer4.stop(); myTimer4.removeEventListener(TimerEvent.TIMER, timerListener);
    }
}

//snow

var snowflakes:Array = new Array();
var snowflakeProps:Dictionary= new Dictionary(true);
var max_snowsize:Number = .04;
// pixels
var snowflakesCnt:Number = 150;
var oheight:Number;
var owidth:Number;
init();
function init():void {

    owidth = width;
    oheight = height;
    // quantity
    for (var i:int=0; i<snowflakesCnt; i++) {

    var t:MovieClip = new SnowFlake();//
    t.name = "snowflake"+i;

    t.alpha = .2+Math.random()*.6;
    t.x = -(owidth/2)+Math.random()*(1.5*owidth);
    t.y = -(oheight/2)+Math.random()*(1.5*oheight);
    t.scaleX = t.scaleY=.5+Math.random()*(max_snowsize*10);
    var o:Object = new Object();
    o.k = 1+Math.random()*2;
    o.wind = -1.5+Math.random()*(1.4*3);

    snowflakeProps[t] = o;

    addChild(t);
    snowflakes.push(t);
}
addEventListener(Event.ENTER_FRAME, snowFlakeMover);
}
function shakeUp():void{
for (var i:int=0; i<snowflakes.length; i++) {
    var t:MovieClip = snowflakes[i] as MovieClip;
    t.x = -(owidth/2)+Math.random()*(1.5*owidth);
    t.y = -(oheight/2)+Math.random()*(1.5*oheight);
    }
}
function snowFlakeMover(evt:Event):void {
var dO:MovieClip;
var o :Object;
if(visible && parent.visible){
for (var i:int = 0; i < snowflakes.length; i++) {
    dO = snowflakes[i] as MovieClip;
    o = snowflakeProps[dO];
    dO.y += o.k;
    dO.x += o.wind;
    if (dO.y>oheight+10) {

        dO.y = -20;

    }
    if (dO.x>owidth+20) {

        dO.x = -(owidth/2)+Math.random()*(1.5*owidth);
        dO.y = -20;

    } else if (dO.x<-20) {

        dO.x= -(owidth/2)+Math.random()*(1.5*owidth);
        dO.y = -20;
    }

}
}
}

and here is the error:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at petgamewithweather_fla::MainTimeline/frame2()[petgamewithweather_fla.MainTimeline::frame2:9]
at flash.display::MovieClip/gotoAndStop()
at petgamewithweather_fla::MainTimeline/func22()[petgamewithweather_fla.MainTimeline::frame16:5]

Validate same values on change

Hello I have a problem with validating identical values in input boxes. Event called must be "on change" value of input box, but I have a problem with numbers.I want to write for example "17", but before there was value "1" already inputted in previous input box and it will report error because before we write 17 there is "1"- 7. So there is my question: is there a option to check identical values with this event type while dodging this error?

my android app some times display half of the screen only when maximize

I am using the scale-mode, alignment and aspect-ratio like this in flash cs6.

stage.scaleMode = StageScaleMode.EXACT_FIT;

stage.align = StageAlign.TOP_LEFT;

Aspect Ratio : landscape

When my app is maximized(after minimize) some times it will display half of the screen only. In some devices user logged out.

converting XML data into an array of objects AS3

I'm using Flash AS4 and Ive created and array that holds xml data which works fine with the following loop

for(var i:int = 0; i < uNavXML.length(); i++){
    navArray.push(uNavXML..navRef.text()[i]);

The XML data is actually the names of movie clips that I have on stage:

    xmlLIST :<uNav>
  <unavNavID>1</unavNavID>
  <navRef>navBtns.nav01</navRef>
</uNav>
<uNav>
  <unavNavID>2</unavNavID>
  <navRef>navBtns.nav02</navRef>
</uNav>
<uNav>
  <unavNavID>3</unavNavID>
  <navRef>navBtns.nav03</navRef>
</uNav>
<uNav>
  <unavNavID>4</unavNavID>
  <navRef>navBtns.nav04</navRef>
</uNav>
<uNav>
  <unavNavID>5</unavNavID>
  <navRef>navBtns.nav05</navRef>
</uNav>
<uNav>
  <unavNavID>7</unavNavID>
  <navRef>navBtns.nav07</navRef>
</uNav>
<uNav>
  <unavNavID>8</unavNavID>
  <navRef>navBtns.nav08</navRef>
</uNav>
<uNav>
  <unavNavID>10</unavNavID>
  <navRef>navBtns.nav10</navRef>
</uNav>
<uNav>
  <unavNavID>12</unavNavID>
  <navRef>navBtns.nav12</navRef>
</uNav>
<uNav>
  <unavNavID>13</unavNavID>
  <navRef>navBtns.nav13</navRef>
</uNav>
<uNav>
  <unavNavID>14</unavNavID>
  <navRef>navBtns.nav14</navRef>
</uNav>
<uNav>
  <unavNavID>15</unavNavID>
  <navRef>navBtns.nav15</navRef>
</uNav>

So, what I want to do is to take these xml values, make them objects in the for loop so that I can then assign eventlisteners to them like this

navObj[i].addEventListener(MouseEvent.MOUSE_OVER, mOvNav); navObj[i].addEventListener(MouseEvent.MOUSE_OUT,mOuNav); navObj[i].addEventListener(MouseEvent.CLICK,goPage);

Is there a way to do this in Flash actionScript? I'm not terribly experienced with AS3 and I've never had to convert an array from String to Object before so I'm struggling. If anyone can off help it would be warmly received...

Answer found via this and on previous SO quesiotn Converting String values to MovieClip in AS 3.0

For my issue here was the answer to remove the "navBtns." prfix and just supply the navButton instance name via navShort

for each (var nav:String in navShrt) {
    var navInst:MovieClip = navBtns[nav] as MovieClip;

Then I was able to reference via navInst.addEventListener.... etc

dispatch event not fired in action script 2.0

I have created a class named CheckBoxSelectAll in which I am triggering an event as below.

import mx.events.EventDispatcher;
import flash.filters.GlowFilter;
class CheckBoxSelectAll  
{
    public function dispatchEvent() {};
    public function addEventListener() {};
    public function removeEventListener() {};

    private var checkbox_mc:MovieClip;
    private var parent_mc:MovieClip;                        

    function CheckBoxSelectAll()
    {
        mx.events.EventDispatcher.initialize(this);
    }

    function CreateCheckBox(c_mc:MovieClip)
    {                               
        var labelGlow:GlowFilter = new GlowFilter(0xFFFFFF, .30, 4, 4, 3, 3);
        var labelFilters:Array = [labelGlow];

        this.parent_mc = c_mc;                  
        checkbox_mc = parent_mc.createEmptyMovieClip("",this.checkbox_mc.getNextHighestDepth() );

        checkbox_mc._x =450;// boxX;
        checkbox_mc._y =143;// boxY;
        checkbox_mc.lineStyle(1, 0);
        checkbox_mc.beginFill(currentFill, currentAlpha);
        checkbox_mc.moveTo(0, triSize);
        checkbox_mc.lineTo(triSize, triSize);
        checkbox_mc.lineTo(triSize, 0);
        checkbox_mc.lineTo(0, 0);
        checkbox_mc.lineTo(0, triSize);
        checkbox_mc.endFill();              
        checkbox_mc._visible = true;
        checkbox_mc.onPress = function() {
            var eventObject:Object = {target:this, type:'onDataReady'};                         
            dispatchEvent(eventObject);
            trace("OnPress refresh...");
        }
    }   
}

In Parent movie clip, used following code

var select_all_listener:Object = new Object();
select_all_listener.onDataReady = triggerDisksLoad;       

    var select_all_box:CheckBoxSelectAll;
    select_all_box = new CheckBoxSelectAll(); 
    select_all_box.addEventListener("onDataReady", select_all_listener);
    select_all_box.CreateCheckBox(this);

function triggerDisksLoad(evtObj) {     trace("triggerDisksLoad called...!!!"); }

Here function triggerDisksLoad is not called. Kindly suggest the fix for this.

How to server flash policy file with socket-io 1.3.5 (node server)?

I'm trying to serve inline flash policy file on port 3000, but with no luck.

I can not catch any callback from flash policy call (<policy-file-request/>\0). And I don't know how to serve send policy file back to flash through the socket.

Somethig like this: Setting up a socket policy file server from Adobe

This is code from server:

var server   = require('http').createServer();
var io       = require('socket.io')(server);

var port = 3000;

var xml = '<?xml version="1.0"?>\n<!DOCTYPE cross-domain-policy SYSTEM \n"http://ift.tt/1d1B8yI">\n<cross-domain-policy>\n';
    xml += '<site-control permitted-cross-domain-policies="master-only"/>\n';
    xml += '<allow-access-from domain="*" to-ports="*"/>\n';
    xml += '</cross-domain-policy>\n';

io.on('connection', function (socket) {
    socket.on('<policy-file-request/>\0', function (data, callback) {
        console.log('socket policy-file-request 0');
        callback(xml);
    });
});

server.listen(port, function () {
    info('Server listening at ' + port);
});

And from client:

Security.loadPolicyFile("xmlsocket://example.com:3000");

please help my..Why not show the full picture, but part of the White?

enter image description here

working code but the picture does not show the full??

enter image description here

AS3/Adobe AIR Error with Orientation

After opening the native modal window(of social network) (and rotating iOS device in landscape) and closing it again. App is still in portrait, as it is designed to be, but the viewport is shifted down about half the screen (496 pixels, to be precise: behind the game center overlay, the stage gets rotated into landscape, so only the top 640 px (screen width) are visible. Use:

 <fullScreen>true</fullScreen>
<autoOrients>false</autoOrients>
<renderMode>direct</renderMode>
<visible>true</visible>
<aspectRatio>portrait</aspectRatio>

and in app:

stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; App should stay in portrait orientation. What I can do?

mardi 23 juin 2015

please help :Sound12 button does not disappear?

I want your help? When you receive this message View -AS3 -flash CS6

Sound12 button does not disappear???

enter image description here

Warning: No libraries were linked as Runtime Shared Libraries (RSLs) because of your publish settings: AIR 3.4 for Android

TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::Stage@265ef81 to flash.display.MovieClip.

at qa2016_fla::allpages_143/frame3()[qa2016_fla.allpages_143::frame3:6]
at flash.display::Sprite/constructChildren()
at flash.display::Sprite()
at flash.display::MovieClip()
at qa2016_fla::myWholePlayer_180()
at flash.display::MovieClip/gotoAndStop()
at qa2016_fla::MainTimeline/frame7()[qa2016_fla.MainTimeline::frame7:5]
at flash.display::MovieClip/prevFrame()
at qa2016_fla::MainTimeline/btn_enter()[qa2016_fla.MainTimeline::frame2:95]

[UnloadSWF] qa2016.swf Test Movie terminated.

how to fix error #1009: Cannot access a property or method of a null object reference

hi im making my flash game this pops up when i test it i am new to flash so i have no idea how to fix it ive searched the web for 2 hours trying fix but no luck all help is appreciated so heres my code:

stop();
Quit.addEventListener(MouseEvent.CLICK, func55);

function func55(event:MouseEvent):void
{
    gotoAndStop(2);
    myTimer.stop(); myTimer.removeEventListener(TimerEvent.TIMER, timerListener);
    myTimer2.stop(); myTimer2.removeEventListener(TimerEvent.TIMER, timerListener);
}

Help.addEventListener(MouseEvent.CLICK, func49);

function func49(event:MouseEvent):void
{
    gotoAndStop(4);
    myTimer.stop(); myTimer.removeEventListener(TimerEvent.TIMER, timerListener);
    myTimer2.stop(); myTimer2.removeEventListener(TimerEvent.TIMER, timerListener);
}

var mytimer13:Timer = new Timer(2000,0);
mytimer13.addEventListener(TimerEvent.TIMER, timerListener10);
function timerListener10(e:TimerEvent):void {
Hungry_bar.scaleX-=0.05;
if(Hungry_bar.scaleX<=0.05){
        gotoAndStop(12)
        myTimer.stop(); myTimer.removeEventListener(TimerEvent.TIMER, timerListener);
        myTimer2.stop(); myTimer2.removeEventListener(TimerEvent.TIMER, timerListener);
    }
}
myTimer.start();

var mytimer15:Timer = new Timer(3000,0);
mytimer15.addEventListener(TimerEvent.TIMER, timerListener12);
function timerListener12(e:TimerEvent):void {
Fun_bar.scaleX-=0.05;
if(Fun_bar.scaleX<=0.05){
        gotoAndStop(13)
        myTimer.stop(); myTimer.removeEventListener(TimerEvent.TIMER, timerListener);
        myTimer2.stop(); myTimer2.removeEventListener(TimerEvent.TIMER, timerListener);
    }
}
myTimer2.start();

Feed.addEventListener(MouseEvent.CLICK,feed)
function feed11(e:MouseEvent){
    Hungry_bar.scaleX+=0.05
    if(Hungry_bar.scaleX>=1.5){
        gotoAndStop(14)
        myTimer.stop(); myTimer.removeEventListener(TimerEvent.TIMER, timerListener);
        myTimer2.stop(); myTimer2.removeEventListener(TimerEvent.TIMER, timerListener);
    }
}

Fun.addEventListener(MouseEvent.CLICK,happy)
function happy11(e:MouseEvent){
    Fun_bar.scaleX+=0.05
    if(Fun_bar.scaleX>=1.5){
        gotoAndStop(15)
        myTimer.stop(); myTimer.removeEventListener(TimerEvent.TIMER, timerListener);
        myTimer2.stop(); myTimer2.removeEventListener(TimerEvent.TIMER, timerListener);
    }
}

Get values of a php in AS3

I've managed to get a value from a sql table in my AS3 code, but I don't understand why I can't get a second value.

In my php file I've got :

// create SQL
 $sql = "SELECT * FROM dt_base where username = '$username'";

// execute SQL query and get result
 $sql_result = mysql_query($sql, $connection) or die ("Couldn't execute query.");

// get number of rows in $result.
 $num = mysql_numrows($sql_result);

$phpConfirm = "";
$phpConfirmSecond = "";
$counter = 0;

while ($row = mysql_fetch_array($sql_result)) {

 $up= $row["up"];
 $down= $row["down"];
 if ($counter == 0) {
 $phpConfirm .= $up;
 $phpConfirmSecond .= $down;

 } else {
 // Use a item limiter "|" to seperate the records
 $phpConfirm .= "|" . $up;
 $phpConfirmSecond .= "|" . $down;
 }
 $counter++;
 }
?> 

And in my AS3 code :

function loadComplete(evt:Event):void {

    //Display the value with variable name "totalItem"
    total_txt.text = evt.target.data.totalItem

    //Get the value (string) with variable name "phpConfirm"
    var myResult:String = evt.target.data.phpConfirm;
    trace(evt.target.data.phpConfirm);

    var myResultSecond:String = evt.target.data.phpConfirmSecond;
    trace(evt.target.data.phpConfirmSecond);


//Split the string into an Array
    var myArray:Array = myResult.split("|");
    var myArraySecond:Array = myResultSecond.split("|");

    var finalString = "";
    var finalStringSecond = "";
    var i:int;

    for (i = 0; i < myArray.length; i++) {

        finalString = finalString + myArray[i] + "<br>";
        finalStringSecond = finalStringSecond + myArraySecond[i] + "<br>";
    }

    output_txt.htmlText = finalString;
    output_txtSecond.htmlText = finalStringSecond;
}

trace(evt.target.data.phpConfirm) results with the value of "up", so it's working. But trace(evt.target.data.phpConfirmSecond) results with "undefined" instead of the value of "down".

Any idea why ?